diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index a5655430abd..6c6683fabed 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: 82**: 27–81 are all claimed (27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their rows below); 49–54 proposed by active #4586 (the persister @@ -128,7 +128,7 @@ renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by by open branches with no row here yet (62 both `ErrorShieldedClaimBindingMismatch` and `ErrorIdentityRevisionMismatch`, 63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 -to 76 proposed for DashPay private contact requests; 28, 30, +to 76 proposed for DashPay private contact requests; 77–79 proposed by #5865 for the shielded spend plan; 80 proposed by #5860 for the failed recipient lookup of the external identity top-up; 81 proposed by #5924's tracked-lock identity recipient for `ErrorAssetLockRecipientUnknown`; 28, 30, 32 and 33 reserved). **28, 30, 32 and 33 are RESERVED, not free**: 28 and 30 were vacated when the reservation trio moved to 34–36; 32 and 33 lapsed when their in-repo owners @@ -192,6 +192,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 74 | `ErrorPrivateContactStoreNotRead` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactStoreNotRead`: DashPay's private contact request store was not read to its end for the identity, with the keys Platform proves it holds, before a contact request or acceptance, public or private, was decided (every one reads it from the identity's cursor first). Nothing was reserved, sealed, paid or broadcast; calling again continues the read from where it stopped. A node behind the store already seen, or keys that kept changing, stop it. It was reported as 71 before, which says not to submit again. Mapped by the blanket conversion and kept by the shielded spend contract (`map_spend_result`). Swift types it (`PlatformWalletError.privateContactStoreNotRead`, `ErrorHandlingTests` pin) and SwiftExampleApp offers a retry with no pending row; Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactStoreNotRead`, `DashSdkErrorTest` pin) and KotlinExampleApp offers a retry with no pending row | | 75 | `ErrorSdkPinnedBelowProtocolVersion` | DashPay private contact requests | Proposed. The SDK refused a request without sending it because the SDK itself is pinned below the protocol version the request needs (`dash_sdk::Error::ProtocolVersionNotActive` with `pinned`), whatever the network runs: for example every contact request's private store read with the SDK pinned below protocol version 15 on a network at 15. A network upgrade does not lift it; only raising or removing the pin does. Before, it shared 70 with a network proven below the version, which lifts by itself. Mapped by the blanket conversion. Swift types it (`PlatformWalletError.sdkPinnedBelowProtocolVersion`, `ErrorHandlingTests` pin) and SwiftExampleApp shows a developer-facing message; Kotlin types it (`DashSdkError.PlatformWallet.SdkPinnedBelowProtocolVersion`, `DashSdkErrorTest` pin) and KotlinExampleApp shows a developer-facing message | | 76 | `ErrorPublicContactRequestUnconfirmed` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PublicContactRequestUnconfirmed`: a public contact request to that identity was broadcast and may have been delivered, and no proof settled its outcome yet, so the wallet holds the pair and signs nothing new to it, public or private. The send or accept that broadcast it reported 20; every later one is refused with 76 until a public contact request sync settles it (its document proved on Platform: recorded as sent; its transition proved unable to write it: the pair freed), broadcasting the same signed bytes again meanwhile. Not a private request pending (71). Mapped by the blanket conversion and by `map_spend_result`. `platform_wallet_get_public_contact_request_unconfirmed` reads the hold per pair (`DashPayView::public_contact_request_unconfirmed`; 7 for a sender the wallet does not hold). Swift types it (`PlatformWalletError.publicContactRequestUnconfirmed`, `ErrorHandlingTests` pin) and wraps the read (`ManagedPlatformWallet.publicContactRequestUnconfirmed`); SwiftExampleApp shows the pair as being checked, with no request or accept offered, until the read says settled, and its refreshes run the DashPay sync that settles it; Kotlin types it (`DashSdkError.PlatformWallet.PublicContactRequestUnconfirmed`, `DashSdkErrorTest` pin), bridges the read (`DashpayNative.publicContactRequestUnconfirmed`, `Dashpay.publicContactRequestsUnconfirmed`), and KotlinExampleApp shows the pair as SwiftExampleApp does | +| 81 | `ErrorAssetLockRecipientUnknown` | dashpay/platform#5924 (identity recipient recorded on an unbound top-up lock) | Proposed. Maps `PlatformWalletError::AssetLockRecipientUnknown`: an unbound identity top-up lock (`IdentityTopUpNotBound`) records no identity to pay — it was rebuilt from the chain, for example after a restore from the seed, and its credit output names none — so no resume pays it. Nothing was submitted or paid. Not retryable as is: the user assigns the lock a recipient (`platform_wallet_assign_identity_top_up_recipient`), after which a resume to that identity proceeds. A resume or assignment naming a different identity than the one recorded is 61, which this PR widens to identity recipients (`PlatformWalletError::AssetLockIdentityRecipientMismatch`). 77–79 are held by #5865 and 80 by #5860, neither yet on `v5.2-dev` | **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/asset_lock/manager.rs b/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs index 69141b9a065..f27c783bf5a 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs @@ -38,6 +38,19 @@ pub struct TrackedAssetLockFFI { /// The raw 43-byte Orchard recipient a resume of this lock pays, valid /// only when `has_shielded_recipient` is true (all zero otherwise). pub shielded_recipient_raw_43: [u8; 43], + /// Whether `identity_recipient_32` carries the identity an unbound + /// identity top-up (funding type 2) pays. A resume of the lock pays that + /// identity and refuses any other. + pub has_identity_recipient: bool, + /// The identity a resume of this lock pays, valid only when + /// `has_identity_recipient` is true (all zero otherwise). + pub identity_recipient_32: [u8; 32], + /// An unbound identity top-up, not consumed, that records no identity + /// (rebuilt from the chain, for example after a restore from the seed): + /// no resume pays it until the user assigns it a recipient with + /// `platform_wallet_assign_identity_top_up_recipient`. Hosts list it + /// for the user rather than resuming it into one of their identities. + pub identity_recipient_unassigned: bool, } /// Destroy an AssetLockManager handle. @@ -95,6 +108,12 @@ pub unsafe extern "C" fn asset_lock_manager_list_tracked_locks( has_proof: lock.proof.is_some(), has_shielded_recipient: lock.shielded_recipient.is_some(), shielded_recipient_raw_43: lock.shielded_recipient.unwrap_or([0; 43]), + has_identity_recipient: lock.identity_recipient.is_some(), + identity_recipient_32: lock + .identity_recipient + .map(|identity| identity.to_buffer()) + .unwrap_or([0; 32]), + identity_recipient_unassigned: lock.is_unassigned_identity_top_up(), } }) .collect(); diff --git a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs index cc86c34013d..5e92a96a189 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs @@ -163,6 +163,18 @@ fn parse_outpoint(txid: *const [u8; 32], vout: u32) -> dashcore::OutPoint { /// the next stage's responsibility (e.g. /// [`crate::platform_wallet_register_identity_with_funding_signer`]). /// +/// # Recorded recipients +/// +/// This export hands back the proof and key path of any tracked lock, with +/// no check of whom the lock was built to pay. A lock that records a +/// recipient (`has_identity_recipient` / `has_shielded_recipient` on the +/// tracked-lock lists) must be consumed only for that recipient: the record +/// is wallet policy, not something the signature enforces, and whoever holds +/// the key can sign the lock to anyone. To top up an identity from a tracked +/// lock, use +/// [`crate::platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`], +/// which pays the identity the lock records and no other. +/// /// # Timeouts /// /// `timeout_secs` bounds only the stages that still have to WAIT for a diff --git a/packages/rs-platform-wallet-ffi/src/core_wallet_types.rs b/packages/rs-platform-wallet-ffi/src/core_wallet_types.rs index 5e5c28d9546..79c61506d09 100644 --- a/packages/rs-platform-wallet-ffi/src/core_wallet_types.rs +++ b/packages/rs-platform-wallet-ffi/src/core_wallet_types.rs @@ -935,6 +935,18 @@ pub struct TrackedAssetLockEntryFFI { pub registration_index: u32, pub instant_lock_present: bool, pub chain_lock_height: u32, + /// Whether `identity_recipient` carries the identity an unbound identity + /// top-up (lock type 2) pays. A resume pays that identity and refuses any + /// other, the host's own identities included. + pub has_identity_recipient: bool, + /// Valid only when `has_identity_recipient` is true (all zero otherwise). + pub identity_recipient: [u8; 32], + /// An unbound identity top-up, not consumed, recording no identity + /// (rebuilt from the chain, for example after a restore from the seed). + /// No resume pays it; a host lists it for the user, who assigns a + /// recipient with `platform_wallet_assign_identity_top_up_recipient`, + /// rather than resuming it into one of the host's identities. + pub identity_recipient_unassigned: bool, } /// Snapshot of the per-account metadata for one account. Strings are diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 58194bf7197..0b08b6234e0 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -654,6 +654,11 @@ pub enum PlatformWalletFFIResultCode { /// was submitted and nothing was paid; resume with the recorded recipient /// (the row exposes it). Rows tracked before the recipient was recorded /// carry none and accept the caller's. + /// + /// Also an unbound identity top-up lock resumed (or assigned) to a + /// different identity than the one its row recorded + /// (`PlatformWalletError::AssetLockIdentityRecipientMismatch`): nothing + /// was submitted; resume to the recorded identity, which the row exposes. ErrorAssetLockRecipientMismatch = 61, /// Maps `PlatformWalletError::PrivateContactRequestNeedsPrivateReply`: @@ -768,6 +773,16 @@ pub enum PlatformWalletFFIResultCode { /// [`Self::ErrorPrivateContactRequestPending`] (71). ErrorPublicContactRequestUnconfirmed = 76, + /// Maps `PlatformWalletError::AssetLockRecipientUnknown`: an unbound + /// identity top-up lock records no identity to pay (it was rebuilt from + /// the chain, for example after a restore from the seed, and its credit + /// output names none), so no resume pays it: it may have been meant for + /// someone else's identity. Nothing was submitted or paid. Not retryable + /// as is: the funds stay recoverable once the user assigns the lock a + /// recipient (`platform_wallet_assign_identity_top_up_recipient`), + /// after which a resume to that identity proceeds. + ErrorAssetLockRecipientUnknown = 81, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1064,6 +1079,12 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::IdentityNotFound(..) => { PlatformWalletFFIResultCode::ErrorIdentityNotFound } + // A bound top-up lock whose identity (at its registration index) + // is not loaded yet: the identity is not found locally, and + // nothing was submitted. + PlatformWalletError::AssetLockIdentityNotLoaded { .. } => { + PlatformWalletFFIResultCode::ErrorIdentityNotFound + } // The two shielded broadcast/wait variants. Today nothing routes // them through this blanket impl — the dedicated match in // `platform_wallet_manager_shielded_identity_create_from_pool` @@ -1218,9 +1239,13 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::AssetLockTooManyInputs { .. } => { PlatformWalletFFIResultCode::ErrorAssetLockTooManyInputs } - PlatformWalletError::AssetLockRecipientMismatch { .. } => { + PlatformWalletError::AssetLockRecipientMismatch { .. } + | PlatformWalletError::AssetLockIdentityRecipientMismatch { .. } => { PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch } + PlatformWalletError::AssetLockRecipientUnknown(..) => { + PlatformWalletFFIResultCode::ErrorAssetLockRecipientUnknown + } // A quiesce/drain barrier that did not complete within budget // (clear/reset paths). The host must fail closed: keep its // callback context alive and skip any paired persistence wipe. @@ -2600,6 +2625,54 @@ mod tests { assert!(message.contains(&hex::encode(recorded))); } + #[test] + fn should_map_an_unbound_top_up_resumed_to_another_identity_to_61() { + let recorded = dpp::prelude::Identifier::from([1u8; 32]); + let result: PlatformWalletFFIResult = + PlatformWalletError::AssetLockIdentityRecipientMismatch { + out_point: dashcore::OutPoint::null(), + recorded, + requested: dpp::prelude::Identifier::from([2u8; 32]), + } + .into(); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch + ); + assert!(message_of(&result).contains(&format!("{recorded}"))); + } + + /// A bound top-up lock whose identity the wallet has not loaded yet + /// crosses as "identity not found": nothing was submitted. + #[test] + fn should_report_a_bound_lock_without_its_identity_as_identity_not_found() { + let result: PlatformWalletFFIResult = PlatformWalletError::AssetLockIdentityNotLoaded { + out_point: dashcore::OutPoint::null(), + identity_index: 3, + } + .into(); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorIdentityNotFound + ); + assert!(message_of(&result).contains("index 3")); + } + + #[test] + fn should_pin_the_unassigned_unbound_top_up_code_at_81() { + assert_eq!( + PlatformWalletFFIResultCode::ErrorAssetLockRecipientUnknown as i32, + 81 + ); + let result: PlatformWalletFFIResult = + PlatformWalletError::AssetLockRecipientUnknown(dashcore::OutPoint::null()).into(); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorAssetLockRecipientUnknown + ); + assert!(message_of(&result).contains("assign a recipient")); + } + #[test] fn asset_lock_input_conflict_code_is_pinned_at_47() { use dashcore::OutPoint; diff --git a/packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs b/packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs index 69e83d6a28c..9a87d99fb23 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs @@ -25,6 +25,7 @@ use crate::core_wallet_types::OutPointFFI; use crate::error::*; use crate::handle::*; use crate::identity_registration_with_signer::{decode_identity_pubkeys, IdentityPubkeyFFI}; +use crate::identity_top_up::catch_top_up_panic; use crate::runtime::block_on_worker; use crate::{unwrap_option_or_return, unwrap_result_or_return}; use rs_sdk_ffi::MnemonicResolverCoreSigner; @@ -284,6 +285,16 @@ pub unsafe extern "C" fn platform_wallet_resume_identity_with_existing_asset_loc /// `true`; every generic top-up/crash-recovery surface must pass `false` /// and is refused invitation locks by the funding resolver. /// +/// `identity_id` must be one of this wallet's own identities; any other is +/// refused (`ErrorIdentityNotFound` (7) for one the wallet does not hold), +/// even when the lock records it. An unbound +/// top-up lock pays only the identity it recorded: another identity is +/// `ErrorAssetLockRecipientMismatch` (61), and a lock recording none is +/// `ErrorAssetLockRecipientUnknown` (81). For crash recovery prefer +/// [`platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`], +/// which takes no identity, pays the one the lock is for (in this wallet or +/// not), and resumes bound and unbound top-up locks alike. +/// /// # Safety /// - `out_point` must be a valid, non-null `*const OutPointFFI`; the caller /// retains ownership. @@ -346,6 +357,196 @@ pub unsafe extern "C" fn platform_wallet_topup_identity_with_existing_asset_lock PlatformWalletFFIResult::ok() } +/// Resume an interrupted identity top-up to the identity its lock pays — the +/// caller names no identity, so a recovery cannot pay someone else's top-up +/// into one of the host's identities, and needs no classification of its +/// own: this resumes every identity top-up lock. Wraps +/// `IdentityWallet::resume_identity_top_up_to_recorded_recipient`: +/// +/// - a bound top-up lock pays the wallet's identity at the lock's +/// registration index; +/// - an unbound top-up lock pays the identity its row recorded. +/// +/// An identity the wallet holds is topped up as a managed identity (its +/// local balance updated), any other as an external one. +/// +/// On success `out_identity_id` receives the identity paid and +/// `out_new_balance` its proved new balance. Errors: `ErrorAssetLockNotTracked` +/// (23), `ErrorAssetLockAlreadyConsumed` (24), `ErrorIdentityNotFound` (7) +/// for a bound lock whose identity the wallet has not loaded yet (resume +/// once identities are synced), `ErrorAssetLockRecipientUnknown` (81) for an +/// unbound lock recording no identity (assign one first with +/// [`platform_wallet_assign_identity_top_up_recipient`]), and the funding +/// mismatch error for a lock that is not an identity top-up. +/// +/// # Safety +/// - `out_point` must be a valid, non-null `*const OutPointFFI`. +/// - `core_signer_handle` must be a valid, non-destroyed +/// `*mut MnemonicResolverHandle`; the caller retains ownership. +/// - `out_identity_id` must point to 32 writable bytes and +/// `out_new_balance` must be a valid `*mut u64`. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_resume_identity_top_up_to_recorded_recipient_signer( + wallet_handle: Handle, + out_point: *const OutPointFFI, + core_signer_handle: *mut MnemonicResolverHandle, + out_identity_id: *mut [u8; 32], + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + // A panic must not reach this `extern "C"` frame. The resume may have + // broadcast the lock or submitted the top-up before it, so the ambiguous + // broadcast-unconfirmed contract applies. + catch_top_up_panic("identity top-up resume", || { + resume_identity_top_up_to_recorded_recipient_signer_inner( + wallet_handle, + out_point, + core_signer_handle, + out_identity_id, + out_new_balance, + ) + }) +} + +/// Body of +/// [`platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`], as +/// an ordinary Rust function so a panic unwinds into [`catch_top_up_panic`] +/// instead of across the C ABI. +/// +/// # Safety +/// Identical contract to the export that calls it. +unsafe fn resume_identity_top_up_to_recorded_recipient_signer_inner( + wallet_handle: Handle, + out_point: *const OutPointFFI, + core_signer_handle: *mut MnemonicResolverHandle, + out_identity_id: *mut [u8; 32], + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + check_ptr!(out_point); + check_ptr!(core_signer_handle); + check_ptr!(out_identity_id); + check_ptr!(out_new_balance); + *out_identity_id = [0; 32]; + *out_new_balance = 0; + let out_point = dashcore::OutPoint::from(&*out_point); + let core_signer_addr = core_signer_handle as usize; + + // Read what the call needs out of the registry, then release it before + // the resume awaits the network and the host's signer and persister. + let (identity_wallet, wallet_id, network) = unwrap_option_or_return!(PLATFORM_WALLET_STORAGE + .with_item(wallet_handle, |wallet| { + ( + wallet.identity().clone(), + wallet.wallet_id(), + wallet.sdk().network, + ) + })); + let result = block_on_worker(async move { + // SAFETY: see the fn-level safety doc — the handle is pinned alive + // for the duration of this FFI call. + let asset_lock_signer = unsafe { + MnemonicResolverCoreSigner::new( + core_signer_addr as *mut MnemonicResolverHandle, + wallet_id, + network, + ) + }; + identity_wallet + .resume_identity_top_up_to_recorded_recipient(out_point, &asset_lock_signer, None) + .await + }); + let (identity_id, new_balance) = unwrap_result_or_return!(result); + *out_identity_id = identity_id.to_buffer(); + *out_new_balance = new_balance; + PlatformWalletFFIResult::ok() +} + +/// Assign the identity an unassigned unbound identity top-up lock pays, as +/// the user chose it. A lock is unassigned when it records no identity +/// (`identity_recipient_unassigned` on the tracked-lock lists): it was rebuilt +/// from the chain, for example after a restore from the seed, and its credit +/// output names none, so no resume pays it. Afterwards resume it with +/// [`platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`], +/// which pays this identity, whether or not this wallet holds it, and +/// refuses any other. +/// +/// The identity is looked up on Platform first, because an assignment is +/// permanent: an identity Platform does not know is `ErrorIdentityNotFound` +/// (7) and nothing is assigned; a failed lookup is the SDK's error. +/// +/// Errors: `ErrorAssetLockNotTracked` (23) for an unknown outpoint, +/// `ErrorAssetLockAlreadyConsumed` (24) for a consumed lock, +/// `ErrorAssetLockRecipientMismatch` (61) when the lock already records a +/// different identity (assigning the recorded one again is a no-op), and a +/// persistence error when the host's persister does not keep identity +/// recipients (`ASSET_LOCK_IDENTITY_RECIPIENTS`) or the store fails. After a +/// failed store the assignment still holds for this session and another +/// identity is refused (61); calling again with the same identity retries +/// the store. A lock +/// that is not an unbound identity top-up is refused. A wallet removed or +/// re-created under its id during the lookup is `NotFound`, with nothing +/// assigned. +/// +/// # Safety +/// - `out_point` must be a valid, non-null `*const OutPointFFI`. +/// - `identity_id` must point to 32 readable bytes. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_assign_identity_top_up_recipient( + wallet_handle: Handle, + out_point: *const OutPointFFI, + identity_id: *const [u8; 32], +) -> PlatformWalletFFIResult { + // A panic must not reach this `extern "C"` frame. An assignment pays + // nothing, so a plain wallet-operation error is enough. + catch_assignment_panic("identity top-up recipient assignment", || { + assign_identity_top_up_recipient_inner(wallet_handle, out_point, identity_id) + }) +} + +/// [`catch_panic_to_code`] for [`platform_wallet_assign_identity_top_up_recipient`]: +/// an assignment sends nothing, so a panic is an `ErrorWalletOperation`. +fn catch_assignment_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorWalletOperation, + "Nothing was paid. The assignment may or may not have been stored; assigning the same \ + identity again is safe.", + body, + ) +} + +/// Body of [`platform_wallet_assign_identity_top_up_recipient`], as an +/// ordinary Rust function so a panic unwinds into [`catch_assignment_panic`] +/// instead of across the C ABI. +/// +/// # Safety +/// Identical contract to the export that calls it. +unsafe fn assign_identity_top_up_recipient_inner( + wallet_handle: Handle, + out_point: *const OutPointFFI, + identity_id: *const [u8; 32], +) -> PlatformWalletFFIResult { + check_ptr!(out_point); + check_ptr!(identity_id); + let out_point = dashcore::OutPoint::from(&*out_point); + let identity_id = Identifier::from(*identity_id); + // Clone the identity wallet out of the registry, so the registry is not + // held while the assignment looks the identity up on Platform, awaits the + // wallet and calls the host's persister. + let identity_wallet = unwrap_option_or_return!( + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()) + ); + let result = block_on_worker(async move { + identity_wallet + .assign_identity_top_up_recipient(&out_point, &identity_id) + .await + }); + unwrap_result_or_return!(result); + PlatformWalletFFIResult::ok() +} + #[cfg(test)] mod topup_existing_lock_guard_tests { use super::*; @@ -381,6 +582,100 @@ mod topup_existing_lock_guard_tests { assert_eq!(res.code, PlatformWalletFFIResultCode::ErrorNullPointer); } + #[test] + fn should_refuse_a_recorded_recipient_resume_with_a_null_pointer_or_an_unknown_wallet() { + let op = zero_out_point(); + let mut identity = [9u8; 32]; + let mut balance = 9u64; + let call = |op: *const OutPointFFI, + signer: *mut MnemonicResolverHandle, + identity: *mut [u8; 32], + balance: *mut u64| unsafe { + platform_wallet_resume_identity_top_up_to_recorded_recipient_signer( + u64::MAX, + op, + signer, + identity, + balance, + ) + }; + for code in [ + call( + std::ptr::null(), + dangling_core_signer(), + &mut identity, + &mut balance, + ) + .code, + call(&op, std::ptr::null_mut(), &mut identity, &mut balance).code, + call( + &op, + dangling_core_signer(), + std::ptr::null_mut(), + &mut balance, + ) + .code, + call( + &op, + dangling_core_signer(), + &mut identity, + std::ptr::null_mut(), + ) + .code, + ] { + assert_eq!(code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + assert_eq!( + call(&op, dangling_core_signer(), &mut identity, &mut balance).code, + PlatformWalletFFIResultCode::NotFound + ); + assert_eq!((identity, balance), ([0; 32], 0)); + } + + /// A panic inside the assignment export must not unwind into the + /// `extern "C"` frame; an assignment pays nothing, so it is a plain + /// wallet-operation error. + #[test] + fn should_map_an_assignment_panic_to_a_wallet_operation_error() { + let mut result = catch_assignment_panic("identity top-up recipient assignment", || { + panic!("tokio worker panicked"); + }); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = unsafe { std::ffi::CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned(); + assert!( + message.contains("assignment panicked") && message.contains("Nothing was paid"), + "{message}" + ); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + } + + #[test] + fn should_refuse_an_assignment_with_a_null_pointer_or_an_unknown_wallet() { + let op = zero_out_point(); + let id = [7u8; 32]; + let null_out_point = + unsafe { platform_wallet_assign_identity_top_up_recipient(0, std::ptr::null(), &id) }; + assert_eq!( + null_out_point.code, + PlatformWalletFFIResultCode::ErrorNullPointer + ); + let null_identity = + unsafe { platform_wallet_assign_identity_top_up_recipient(0, &op, std::ptr::null()) }; + assert_eq!( + null_identity.code, + PlatformWalletFFIResultCode::ErrorNullPointer + ); + let unknown_wallet = + unsafe { platform_wallet_assign_identity_top_up_recipient(u64::MAX, &op, &id) }; + assert_eq!(unknown_wallet.code, PlatformWalletFFIResultCode::NotFound); + } + #[test] fn rejects_null_identity_id() { let op = zero_out_point(); diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index 49c51337af8..2862a1aec96 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -145,23 +145,6 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( PlatformWalletFFIResult::ok() } -/// Minimum asset-lock funding for a Core-funded identity top-up, in duffs. -/// -/// Platform rejects an `IdentityTopUp` whose asset-lock output value (in -/// credits) is below `IdentityTopUpTransition::calculate_min_required_fee`. -/// Under the active fee version (v1) that minimum is -/// `identity_topup_base_cost` (500_000 credits = 500 duffs) **plus** -/// `required_asset_lock_duff_balance_for_processing_start_for_identity_top_up` -/// (50_000 duffs) — i.e. 50_500 duffs. Below that, a lock built and broadcast -/// here is accepted by Core (spending real UTXOs) but rejected by Platform, -/// stranding the funds in a lock that can never complete the top-up. Reject -/// sub-floor amounts up front so no such lock is ever broadcast. -/// -/// (The bare 50_000 asset-lock floor alone was the fee-v0 minimum; the active -/// v1 calc — `STATE_TRANSITION_VERSIONS_V3`, protocol v11+ — adds the base -/// cost, so this constant must include it.) -const MIN_TOP_UP_DUFFS: u64 = 50_500; - /// Top up an existing identity's credit balance by building and /// broadcasting a **new Core asset lock** (the same funding mechanism as /// identity registration), distinct from @@ -188,8 +171,11 @@ const MIN_TOP_UP_DUFFS: u64 = 50_500; /// credit balance Platform returns; the local `ManagedIdentity` balance is /// updated + queued for persistence inside the library call. /// -/// `amount_duffs` must be at least [`MIN_TOP_UP_DUFFS`]; a smaller amount is -/// rejected with `ErrorInvalidParameter` before any lock is broadcast. +/// `amount_duffs` must be at least Platform's top-up minimum, the largest +/// across the protocol versions this build supports +/// ([`min_top_up_duffs`](platform_wallet::wallet::identity::network::min_top_up_duffs), +/// 50_500 duffs today); the wallet rejects a smaller amount with +/// `ErrorInvalidParameter` before any lock is built. /// /// # Safety /// - `wallet_handle` must come from the platform-wallet handle registry. @@ -216,12 +202,6 @@ pub unsafe extern "C" fn platform_wallet_top_up_identity_with_funding_signer( // FFI-safe sentinel before any fallible work, matching the sibling // `platform_wallet_topup_identity_with_existing_asset_lock_signer`. *out_new_balance = 0; - if amount_duffs < MIN_TOP_UP_DUFFS { - return PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "`amount_duffs` is below the minimum top-up asset-lock balance", - ); - } let identity_id_bytes: [u8; 32] = *identity_id; let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); @@ -266,11 +246,159 @@ pub unsafe extern "C" fn platform_wallet_top_up_identity_with_funding_signer( PlatformWalletFFIResult::ok() } +/// Top up someone else's identity — one this wallet does not manage — by +/// building and broadcasting a new Core asset lock from the wallet's +/// balance. The external counterpart of +/// [`platform_wallet_top_up_identity_with_funding_signer`]. +/// +/// Wraps +/// `IdentityWallet::top_up_external_identity_with_funding` with +/// `AssetLockFunding::FromWalletBalance`: the identity is fetched from +/// Platform, the lock is funded from the wallet's unbound top-up account and +/// its row records `identity_id` before the broadcast, so an interrupted +/// top-up resumes to this identity only +/// ([`crate::platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`]). +/// No identity is added to the wallet (one the wallet already holds gets its +/// local balance updated). On success +/// `out_new_balance` receives the identity's proved post-transition balance. +/// +/// Errors before anything is built: `ErrorInvalidParameter` for an amount +/// below [`min_top_up_duffs`](platform_wallet::wallet::identity::network::min_top_up_duffs) +/// (the largest top-up minimum across the supported protocol versions, 50_500 +/// duffs today), `ErrorIdentityNotFound` (7) for an identity +/// Platform does not know, and a persistence error when the host's persister +/// does not declare `ASSET_LOCK_IDENTITY_RECIPIENTS`. A failed lookup is +/// reported as the SDK error for now; it becomes `ErrorIdentityLookupFailed` +/// (80) with dashpay/platform#5860. +/// +/// Once the lock is built, a failure may leave it tracked: it then appears on +/// the tracked-lock lists recording `identity_id`. Do not build a new lock to +/// retry; resume that one with +/// [`crate::platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`], +/// or the identity may be paid twice. +/// +/// # Safety +/// Same contract as [`platform_wallet_top_up_identity_with_funding_signer`]. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_top_up_external_identity_with_funding_signer( + wallet_handle: Handle, + identity_id: *const [u8; 32], + amount_duffs: u64, + account_index: u32, + core_signer_handle: *mut MnemonicResolverHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + // The whole body runs under `catch_unwind`: a panic (most concretely + // `block_on_worker`'s `.expect` on a panicking top-up task) must not reach + // this `extern "C"` frame. It can strike after the lock was broadcast, so + // the ambiguous broadcast-unconfirmed contract applies. + catch_top_up_panic("external identity top-up", || { + top_up_external_identity_with_funding_signer_inner( + wallet_handle, + identity_id, + amount_duffs, + account_index, + core_signer_handle, + out_new_balance, + ) + }) +} + +/// Body of [`platform_wallet_top_up_external_identity_with_funding_signer`], +/// as an ordinary Rust function so a panic unwinds into +/// [`catch_top_up_panic`] instead of across the C ABI. +/// +/// # Safety +/// Identical contract to the export that calls it. +unsafe fn top_up_external_identity_with_funding_signer_inner( + wallet_handle: Handle, + identity_id: *const [u8; 32], + amount_duffs: u64, + account_index: u32, + core_signer_handle: *mut MnemonicResolverHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + check_ptr!(identity_id); + check_ptr!(core_signer_handle); + check_ptr!(out_new_balance); + *out_new_balance = 0; + let identity_id = Identifier::from(*identity_id); + let core_signer_addr = core_signer_handle as usize; + + // Read what the call needs out of the registry, then release it before + // the top-up awaits the network and the host's signer and persister. + let (identity_wallet, wallet_id, network) = unwrap_option_or_return!(PLATFORM_WALLET_STORAGE + .with_item(wallet_handle, |wallet| { + ( + wallet.identity().clone(), + wallet.wallet_id(), + wallet.sdk().network, + ) + })); + let result = block_on_worker(async move { + // SAFETY: see the fn-level safety doc — the handle is pinned alive + // for the duration of this FFI call. + let asset_lock_signer = unsafe { + MnemonicResolverCoreSigner::new( + core_signer_addr as *mut MnemonicResolverHandle, + wallet_id, + network, + ) + }; + identity_wallet + .top_up_external_identity_with_funding( + &identity_id, + AssetLockFunding::FromWalletBalance { + amount_duffs, + account_index, + }, + &asset_lock_signer, + None, + ) + .await + }); + *out_new_balance = unwrap_result_or_return!(result); + PlatformWalletFFIResult::ok() +} + +/// Post-panic guidance for the exports that may have paid an identity +/// top-up. Paired with `ErrorTransactionBroadcastUnconfirmed` in +/// [`catch_top_up_panic`]. +const TOP_UP_PANIC_GUIDANCE: &str = "The asset lock may or may not have been broadcast and \ + the top-up may or may not have been submitted — do NOT build a new lock to retry; resume \ + the tracked lock with platform_wallet_resume_identity_top_up_to_recorded_recipient_signer, \ + or the identity may be paid twice."; + +/// [`catch_panic_to_code`] for the exports that fund or resume an identity +/// top-up from a Core asset lock. +/// +/// The panic is mapped to +/// [`PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed`], not +/// to a definitive failure: it can strike after the lock reached the wire or +/// after Platform accepted the top-up, so the outcome is ambiguous, and that +/// code's contract (do not retry, the lock stays tracked and resumable) is +/// the conservative one. +pub(crate) fn catch_top_up_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed, + TOP_UP_PANIC_GUIDANCE, + body, + ) +} + #[cfg(test)] mod top_up_with_funding_guard_tests { use super::*; use crate::error::PlatformWalletFFIResultCode; + /// Any amount: every guard under test answers before the minimum check. + const AMOUNT_DUFFS: u64 = 50_500; + /// A non-null but never-dereferenced core-signer pointer. Every guard /// under test returns before the handle is used, so a dangling pointer /// is sufficient (and never unsound here). @@ -278,6 +406,32 @@ mod top_up_with_funding_guard_tests { std::ptr::NonNull::::dangling().as_ptr() } + /// A panic inside a top-up export must not unwind into the `extern "C"` + /// frame. It becomes `ErrorTransactionBroadcastUnconfirmed`, the + /// ambiguous do-not-retry contract, because it can strike after the lock + /// was broadcast. + #[test] + fn should_map_a_top_up_panic_to_the_broadcast_unconfirmed_contract() { + let mut result = catch_top_up_panic("external identity top-up", || { + panic!("tokio worker panicked"); + }); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed + ); + let message = unsafe { std::ffi::CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned(); + assert!( + message.contains("external identity top-up panicked") + && message.contains("tokio worker panicked") + && message.contains("do NOT build a new lock"), + "{message}" + ); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + } + #[test] fn rejects_null_identity_id() { let mut balance = 0u64; @@ -285,7 +439,7 @@ mod top_up_with_funding_guard_tests { platform_wallet_top_up_identity_with_funding_signer( 0, std::ptr::null(), - MIN_TOP_UP_DUFFS, + AMOUNT_DUFFS, 0, dangling_core_signer(), &mut balance, @@ -302,7 +456,7 @@ mod top_up_with_funding_guard_tests { platform_wallet_top_up_identity_with_funding_signer( 0, &id, - MIN_TOP_UP_DUFFS, + AMOUNT_DUFFS, 0, std::ptr::null_mut(), &mut balance, @@ -318,7 +472,7 @@ mod top_up_with_funding_guard_tests { platform_wallet_top_up_identity_with_funding_signer( 0, &id, - MIN_TOP_UP_DUFFS, + AMOUNT_DUFFS, 0, dangling_core_signer(), std::ptr::null_mut(), @@ -327,26 +481,39 @@ mod top_up_with_funding_guard_tests { assert_eq!(res.code, PlatformWalletFFIResultCode::ErrorNullPointer); } + /// The external export guards its pointers like the managed one; the + /// minimum amount is the wallet's check, so an unknown wallet answers + /// first here. #[test] - fn rejects_sub_floor_amount() { + fn should_refuse_an_external_top_up_with_a_null_pointer_or_an_unknown_wallet() { let id = [0u8; 32]; - let mut balance = 0u64; - for amount in [0u64, MIN_TOP_UP_DUFFS - 1] { - let res = unsafe { - platform_wallet_top_up_identity_with_funding_signer( - 0, - &id, - amount, - 0, - dangling_core_signer(), - &mut balance, - ) - }; - assert_eq!( - res.code, - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "amount {amount} below MIN_TOP_UP_DUFFS should be rejected" - ); + let mut balance = 7u64; + let call = |identity: *const [u8; 32], + signer: *mut MnemonicResolverHandle, + out: *mut u64| unsafe { + platform_wallet_top_up_external_identity_with_funding_signer( + u64::MAX, + identity, + AMOUNT_DUFFS, + 0, + signer, + out, + ) + }; + for code in [ + call(std::ptr::null(), dangling_core_signer(), &mut balance).code, + call(&id, std::ptr::null_mut(), &mut balance).code, + call(&id, dangling_core_signer(), std::ptr::null_mut()).code, + ] { + assert_eq!(code, PlatformWalletFFIResultCode::ErrorNullPointer); } + assert_eq!( + call(&id, dangling_core_signer(), &mut balance).code, + PlatformWalletFFIResultCode::NotFound + ); + assert_eq!( + balance, 0, + "the out-param is reset before any fallible work" + ); } } diff --git a/packages/rs-platform-wallet-ffi/src/manager.rs b/packages/rs-platform-wallet-ffi/src/manager.rs index 51e38104709..23a5f090389 100644 --- a/packages/rs-platform-wallet-ffi/src/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/manager.rs @@ -9,9 +9,10 @@ use crate::event_handler::{ use crate::handle::*; use crate::persistence::{ FFIPersister, FreePrivateContactScanStateFn, FreePrivateContactScanStateWalletsFn, - FreeTrackedMasternodesFn, LoadAssetLockOperationIdFn, LoadAssetLockShieldedRecipientFn, - LoadIdentityBalanceBlockTimeFn, LoadPrivateContactScanStateFn, - LoadPrivateContactScanStateWalletsFn, LoadTrackedMasternodesFn, PersistAssetLockOperationIdFn, + FreeTrackedMasternodesFn, LoadAssetLockIdentityRecipientFn, LoadAssetLockOperationIdFn, + LoadAssetLockShieldedRecipientFn, LoadIdentityBalanceBlockTimeFn, + LoadPrivateContactScanStateFn, LoadPrivateContactScanStateWalletsFn, LoadTrackedMasternodesFn, + PersistAssetLockIdentityRecipientFn, PersistAssetLockOperationIdFn, PersistAssetLockShieldedRecipientFn, PersistDpnsNameStatesFn, PersistIdentityBalanceBlockTimeFn, PersistPrivateContactScanStateFn, PersistTrackedMasternodesFn, PersistWalletChangesetChainLockHeightFn, @@ -408,6 +409,14 @@ unsafe fn persistence_extension_callbacks( on_load_private_contact_scan_state_wallets_free_fn, FreePrivateContactScanStateWalletsFn ), + persist_asset_lock_identity_recipient: slot!( + on_persist_asset_lock_identity_recipient_fn, + PersistAssetLockIdentityRecipientFn + ), + load_asset_lock_identity_recipient: slot!( + on_load_asset_lock_identity_recipient_fn, + LoadAssetLockIdentityRecipientFn + ), } } diff --git a/packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs b/packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs index 12c330a6340..54964b13db4 100644 --- a/packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs +++ b/packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs @@ -288,6 +288,12 @@ pub unsafe extern "C" fn platform_wallet_tracked_asset_locks_list( registration_index: s.registration_index, instant_lock_present: s.instant_lock_present, chain_lock_height: s.chain_lock_height, + has_identity_recipient: s.identity_recipient.is_some(), + identity_recipient: s + .identity_recipient + .map(|identity| identity.to_buffer()) + .unwrap_or([0; 32]), + identity_recipient_unassigned: s.identity_recipient_unassigned, }) .collect(); let count = entries.len(); diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 8495c4464ac..21cdfb7553a 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -198,6 +198,15 @@ pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS: /// un-ignore stores the sender's removal and the read-position rewind it /// brings in one changeset. pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE: u64 = 1 << 15; +/// The identity an unbound identity top-up was built (or assigned) to pay +/// survives store and load with its row, so a resume after restart pays that +/// identity and refuses another. Attested when the host wires both +/// `on_persist_asset_lock_identity_recipient_fn` and +/// `on_load_asset_lock_identity_recipient_fn` next to the legacy asset-lock +/// persist/load callbacks and the wallet-list restore pair. Required: the +/// wallet builds no unbound top-up lock, and assigns no recipient, for a host +/// that does not declare it. +pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS: u64 = 1 << 17; /// Version of [`PersistenceCallbacksExtension`]. The extension is deliberately /// separate from [`PersistenceCallbacks`]: existing hosts pass the latter by @@ -456,6 +465,29 @@ pub type FreePrivateContactScanStateWalletsFn = unsafe extern "C" fn( wallet_ids_count: usize, ); +/// Associate the immutable 32-byte identity id an unbound identity top-up pays +/// with a 36-byte raw outpoint. Runs after the legacy asset-lock upsert (and the +/// other sidecars), inside the same atomic changeset. All three byte pointers +/// are readable for the duration of the callback. A host must refuse (non-zero) +/// a different identity for an outpoint that already records one. +pub type PersistAssetLockIdentityRecipientFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + identity_id_32: *const u8, +) -> i32; + +/// Read the optional identity recipient for a restored outpoint. +/// `out_identity_id_32` points to 32 writable bytes. An unreadable or missing +/// asset-lock row must return an error, not a successful `out_found = false`. +pub type LoadAssetLockIdentityRecipientFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_identity_id_32: *mut u8, +) -> i32; + /// Size- and version-tagged additive persistence callbacks. /// /// `context` is the context in the accompanying [`PersistenceCallbacks`] @@ -709,6 +741,28 @@ pub struct PersistenceCallbacksExtension { wallet_ids_count: usize, ), >, + /// Additive sidecar for the identity an unbound identity top-up pays (see + /// [`PersistAssetLockIdentityRecipientFn`]). Appended under the same + /// version for the same reason as the slots above. Both slots, the legacy + /// asset-lock persist callback and the wallet-list restore pair are + /// required before the host can attest `ASSET_LOCK_IDENTITY_RECIPIENTS`. + pub on_persist_asset_lock_identity_recipient_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + identity_id_32: *const u8, + ) -> i32, + >, + pub on_load_asset_lock_identity_recipient_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_identity_id_32: *mut u8, + ) -> i32, + >, } impl Default for PersistenceCallbacksExtension { @@ -736,6 +790,8 @@ impl Default for PersistenceCallbacksExtension { on_load_private_contact_scan_state_free_fn: None, on_load_private_contact_scan_state_wallets_fn: None, on_load_private_contact_scan_state_wallets_free_fn: None, + on_persist_asset_lock_identity_recipient_fn: None, + on_load_asset_lock_identity_recipient_fn: None, } } } @@ -764,6 +820,8 @@ pub struct PersistenceExtensionCallbacks { pub load_private_contact_scan_state_free: Option, pub load_private_contact_scan_state_wallets: Option, pub load_private_contact_scan_state_wallets_free: Option, + pub persist_asset_lock_identity_recipient: Option, + pub load_asset_lock_identity_recipient: Option, } /// Return value by which a persistence callback reports a **retryable** @@ -1909,6 +1967,20 @@ impl FFIPersister { capabilities = capabilities.union(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS); } + if wallet_restore + && self.callbacks.on_persist_asset_locks_fn.is_some() + && self + .tracked_masternodes_callbacks + .persist_asset_lock_identity_recipient + .is_some() + && self + .tracked_masternodes_callbacks + .load_asset_lock_identity_recipient + .is_some() + { + capabilities = + capabilities.union(PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS); + } if self .tracked_masternodes_callbacks .persist_tracked_masternodes @@ -3057,6 +3129,35 @@ impl PlatformWalletPersistence for FFIPersister { shielded asset-lock funding is not persisted with its row" ); } + // The identity recipient is a third sidecar. The wallet records one + // only for a host that attests `ASSET_LOCK_IDENTITY_RECIPIENTS`, + // which needs this slot, so a recipient with no slot to take it + // fails the round, as a UUID does, rather than being dropped. + for entry in al_cs.asset_locks.values() { + let Some(identity) = entry.identity_recipient else { + continue; + }; + let Some(cb) = self + .tracked_masternodes_callbacks + .persist_asset_lock_identity_recipient + else { + outcome.record(1); + continue; + }; + let out_point = outpoint_to_bytes(&entry.out_point); + let identity = identity.to_buffer(); + let rc = unsafe { + cb( + self.callbacks.context, + wallet_id.as_ptr(), + out_point.as_ptr(), + identity.as_ptr(), + ) + }; + if rc != 0 { + outcome.record(rc); + } + } } // Send invitation changeset — DIP-13 sent-invitation records, one @@ -3881,6 +3982,17 @@ impl PlatformWalletPersistence for FFIPersister { &mut wallet_state.unused_asset_locks, )?; } + if let Some(cb) = self + .tracked_masternodes_callbacks + .load_asset_lock_identity_recipient + { + load_asset_lock_identity_recipients( + cb, + self.callbacks.context, + &entry.wallet_id, + &mut wallet_state.unused_asset_locks, + )?; + } if let (Some(load), Some(free)) = ( self.tracked_masternodes_callbacks .load_private_contact_scan_state, @@ -6680,11 +6792,57 @@ fn load_asset_lock_shielded_recipients( context: *mut c_void, wallet_id: &WalletId, locks: &mut BTreeMap>, +) -> Result<(), PersistenceError> { + load_asset_lock_recipient_sidecar::<{ platform_wallet::changeset::SHIELDED_RECIPIENT_SIZE }>( + callback, + context, + wallet_id, + locks, + "Loading asset-lock shielded recipient failed", + |lock, raw| lock.shielded_recipient = raw, + ) +} + +/// Rehydrate the identity-recipient sidecar after decoding the frozen legacy +/// rows. A failed read invalidates the whole load: a row that silently lost +/// its recipient would reload as an unassigned lock. +fn load_asset_lock_identity_recipients( + callback: LoadAssetLockIdentityRecipientFn, + context: *mut c_void, + wallet_id: &WalletId, + locks: &mut BTreeMap>, +) -> Result<(), PersistenceError> { + load_asset_lock_recipient_sidecar::<32>( + callback, + context, + wallet_id, + locks, + "Loading asset-lock identity recipient failed", + |lock, raw| lock.identity_recipient = raw.map(Identifier::from), + ) +} + +/// Ask the host for one `N`-byte recipient sidecar per restored lock and hand +/// each answer to `set`. The shielded and identity loaders share it; their +/// callback types have this same shape. +fn load_asset_lock_recipient_sidecar( + callback: unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_recipient: *mut u8, + ) -> i32, + context: *mut c_void, + wallet_id: &WalletId, + locks: &mut BTreeMap>, + failure: &str, + set: impl Fn(&mut platform_wallet::TrackedAssetLock, Option<[u8; N]>), ) -> Result<(), PersistenceError> { for lock in locks.values_mut().flat_map(|locks| locks.values_mut()) { let out_point = outpoint_to_bytes(&lock.out_point); let mut found = false; - let mut raw = [0u8; platform_wallet::changeset::SHIELDED_RECIPIENT_SIZE]; + let mut raw = [0u8; N]; let rc = unsafe { callback( context, @@ -6695,12 +6853,9 @@ fn load_asset_lock_shielded_recipients( ) }; if rc != 0 { - return Err(persist_callback_error( - rc, - "Loading asset-lock shielded recipient failed", - )); + return Err(persist_callback_error(rc, failure)); } - lock.shielded_recipient = found.then_some(raw); + set(lock, found.then_some(raw)); } Ok(()) } @@ -7062,6 +7217,7 @@ fn build_unused_asset_locks( amount: spec.amount_duffs, operation_id: None, shielded_recipient: None, + identity_recipient: None, status, proof, }; @@ -11436,6 +11592,7 @@ mod tests { proof: None, operation_id, shielded_recipient: None, + identity_recipient: None, }; let (entries, _storage) = build_asset_lock_entries(&[&entry]); let wallet = WalletRestoreEntryFFI { @@ -11560,6 +11717,7 @@ mod tests { proof: None, operation_id: None, shielded_recipient: Some(raw), + identity_recipient: None, }; let (entries, _storage) = build_asset_lock_entries(&[&entry]); let wallet = WalletRestoreEntryFFI { @@ -11660,6 +11818,152 @@ mod tests { } } + /// The identity-recipient sidecar round-trips next to the frozen row: a + /// host with both slots gets every recorded identity on store and hands + /// it back on load, and attests the bit only with both slots. A host + /// without the persist slot fails the round instead of dropping the + /// recipient, since the wallet records one only for an attesting host. + #[test] + fn should_roundtrip_identity_recipients_and_fail_a_round_without_the_slot() { + use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; + + let identity = Identifier::from([0x44u8; 32]); + unsafe extern "C" fn load_recipient( + context: *mut c_void, + _: *const u8, + _: *const u8, + found: *mut bool, + output: *mut u8, + ) -> i32 { + let stored = *(context as *const Option<[u8; 32]>); + *found = stored.is_some(); + if let Some(stored) = stored { + std::ptr::copy_nonoverlapping(stored.as_ptr(), output, 32); + } + 0 + } + let entry = platform_wallet::changeset::AssetLockEntry { + out_point: dashcore::OutPoint { + txid: dashcore::Txid::from_byte_array([5; 32]), + vout: 0, + }, + transaction: dashcore::Transaction { + version: 3, + lock_time: 0, + input: vec![], + output: vec![], + special_transaction_payload: None, + }, + account_index: 2, + funding_type: AssetLockFundingType::IdentityTopUpNotBound, + identity_index: 0, + amount_duffs: 1000, + status: platform_wallet::AssetLockStatus::Broadcast, + proof: None, + operation_id: None, + shielded_recipient: None, + identity_recipient: Some(identity), + }; + let (entries, _storage) = build_asset_lock_entries(&[&entry]); + let wallet = WalletRestoreEntryFFI { + tracked_asset_locks: entries.as_ptr(), + tracked_asset_locks_count: entries.len(), + ..Default::default() + }; + let mut restored = build_unused_asset_locks(&wallet).expect("valid persisted lock"); + assert_eq!( + restored[&2][&entry.out_point].identity_recipient, None, + "legacy ABI has no recipient field" + ); + for stored in [None, Some(identity.to_buffer())] { + load_asset_lock_identity_recipients( + load_recipient, + (&stored as *const Option<[u8; 32]>).cast_mut().cast(), + &[42; 32], + &mut restored, + ) + .expect("valid recipient sidecar"); + assert_eq!( + restored[&2][&entry.out_point].identity_recipient, + stored.map(Identifier::from) + ); + } + + let changeset = PlatformWalletChangeSet { + asset_locks: Some(platform_wallet::changeset::AssetLockChangeSet { + asset_locks: [(entry.out_point, entry.clone())].into(), + ..Default::default() + }), + ..Default::default() + }; + let callbacks = || PersistenceCallbacks { + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(noop_end), + on_persist_asset_locks_fn: Some(noop_asset_locks), + on_load_wallet_list_fn: Some(noop_load_wallets), + on_load_wallet_list_free_fn: Some(noop_free_wallets), + ..Default::default() + }; + let legacy = FFIPersister::new(callbacks()); + assert!(legacy.store([42; 32], changeset.clone()).is_err()); + assert!(!legacy + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS)); + + unsafe extern "C" fn persist_recipient( + context: *mut c_void, + wallet: *const u8, + _: *const u8, + recipient: *const u8, + ) -> i32 { + assert_eq!(slice::from_raw_parts(wallet, 32), &[42; 32]); + let seen = slice::from_raw_parts(recipient, 32); + *(context as *mut Option<[u8; 32]>) = Some(seen.try_into().unwrap()); + 0 + } + let mut seen: Option<[u8; 32]> = None; + let extensions = PersistenceExtensionCallbacks { + persist_asset_lock_identity_recipient: Some(persist_recipient), + load_asset_lock_identity_recipient: Some(load_recipient), + ..Default::default() + }; + let writer = FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: std::ptr::addr_of_mut!(seen).cast(), + ..callbacks() + }, + PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS, + extensions, + ); + assert!(writer + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS)); + writer + .store([42; 32], changeset) + .expect("recipient sidecar persisted with the base row"); + assert_eq!(seen, Some(identity.to_buffer())); + for incomplete in [ + PersistenceExtensionCallbacks { + persist_asset_lock_identity_recipient: None, + ..extensions + }, + PersistenceExtensionCallbacks { + load_asset_lock_identity_recipient: None, + ..extensions + }, + ] { + assert!( + !FFIPersister::new_with_persistence_capabilities_and_extensions( + callbacks(), + PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS, + incomplete, + ) + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS) + ); + } + } + #[test] fn should_require_explicit_operation_id_persistence_attestation() { unsafe extern "C" fn persist( @@ -12102,6 +12406,26 @@ mod tests { PersistenceCallbacksExtension, on_load_private_contact_scan_state_wallets_free_fn ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_asset_lock_identity_recipient_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_asset_lock_identity_recipient_fn + ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_asset_lock_identity_recipient_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_asset_lock_identity_recipient_fn + ) + std::mem::size_of::>(), std::mem::size_of::() ); assert_eq!( @@ -12168,6 +12492,10 @@ mod tests { PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS, PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS.bits() ); + assert_eq!( + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS, + PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS.bits() + ); assert_eq!( PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE, PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE.bits() @@ -14470,6 +14798,7 @@ mod tests { proof: None, operation_id: None, shielded_recipient: None, + identity_recipient: None, }; let out_point = entry.out_point; let host = Arc::new(Host { diff --git a/packages/rs-platform-wallet-storage/SCHEMA.md b/packages/rs-platform-wallet-storage/SCHEMA.md index 94485778a6c..768987fb84f 100644 --- a/packages/rs-platform-wallet-storage/SCHEMA.md +++ b/packages/rs-platform-wallet-storage/SCHEMA.md @@ -851,3 +851,4 @@ table-rebuild migration, as V004 does. | V018 | `V018__identity_hard_delete.rs` | Retires identity tombstoning. Adds `cascade_children_on_identity_delete` (brooms `identity_keys` / `contacts` / `ignored_senders` / `pending_contact_crypto` by the deleted identity id, covering the rows no live FK reaches) plus its access-path indexes `idx_contacts_owner`, `idx_ignored_senders_owner`, and `idx_pending_contact_crypto_owner`; purges every already-tombstoned identity and its dependents; drops `identities.tombstoned`. | | V019 | `V019__asset_lock_operation_id.rs` | Adds the nullable `asset_locks.operation_id BLOB` column (CHECK: NULL or exactly 16 bytes) that correlates a wallet-drain operation with its funding outpoint; the lifecycle blob is untouched. Adds the unique partial index `asset_locks_wallet_operation_id` on `(wallet_id, operation_id) WHERE operation_id IS NOT NULL` and the `asset_locks_operation_id_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `operation_id`. Purely additive; existing rows read back NULL. | | V020 | `V020__asset_lock_shielded_recipient.rs` | Adds the nullable `asset_locks.shielded_recipient BLOB` column (CHECK: NULL or exactly 43 bytes, the raw Orchard address) recording the recipient a shielded asset-lock funding was built to pay, so a resume after restart pays that recipient and refuses another; the lifecycle blob is untouched. Adds the `asset_locks_shielded_recipient_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `shielded_recipient`. Purely additive; existing rows read back NULL and keep accepting the resuming caller's recipient. | +| V021 | `V021__asset_lock_identity_recipient.rs` | Adds the nullable `asset_locks.identity_recipient BLOB` column (CHECK: NULL or exactly 32 bytes, the identity id) recording the identity an unbound identity top-up (`IdentityTopUpNotBound`) was built, or later assigned, to pay, so a resume after restart pays that identity and refuses another; the lifecycle blob is untouched. Adds the `asset_locks_identity_recipient_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `identity_recipient`. Purely additive; existing rows read back NULL, and an unbound top-up row without a recipient is unassigned until one is assigned. | diff --git a/packages/rs-platform-wallet-storage/migrations/V021__asset_lock_identity_recipient.rs b/packages/rs-platform-wallet-storage/migrations/V021__asset_lock_identity_recipient.rs new file mode 100644 index 00000000000..7ea8d3895da --- /dev/null +++ b/packages/rs-platform-wallet-storage/migrations/V021__asset_lock_identity_recipient.rs @@ -0,0 +1,11 @@ +//! The identity an unbound identity top-up was built (or later assigned) to +//! pay, so a resume after restart pays that identity and refuses another. +//! Legacy blobs stay byte-identical; old rows receive NULL. +pub fn migration() -> String { + "ALTER TABLE asset_locks ADD COLUMN identity_recipient BLOB \ + CHECK (identity_recipient IS NULL OR (typeof(identity_recipient) = 'blob' AND length(identity_recipient) = 32)); \ + CREATE TRIGGER asset_locks_identity_recipient_immutable \ + BEFORE UPDATE OF identity_recipient ON asset_locks \ + WHEN OLD.identity_recipient IS NOT NULL AND NEW.identity_recipient IS NOT OLD.identity_recipient \ + BEGIN SELECT RAISE(ABORT, 'asset lock identity recipient cannot change'); END;".to_owned() +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/persister.rs b/packages/rs-platform-wallet-storage/src/sqlite/persister.rs index fb4080cc63c..ace03b8f2e2 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/persister.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/persister.rs @@ -1322,6 +1322,7 @@ impl PlatformWalletPersistence for SqlitePersister { .union(PersistenceCapabilities::TRACKED_ASSET_LOCKS) .union(PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS) .union(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS) + .union(PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS) .union(PersistenceCapabilities::TRACKED_MASTERNODES) .union(PersistenceCapabilities::CORE_SWEEP_REMOVAL) .union(PersistenceCapabilities::DASHPAY_PAYMENTS); diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs index e0bb8032e06..618d6dbce3e 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs @@ -13,7 +13,7 @@ use rusqlite::{params, OptionalExtension, Transaction}; use serde::{Deserialize, Serialize}; -use dpp::prelude::AssetLockProof; +use dpp::prelude::{AssetLockProof, Identifier}; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use platform_wallet::changeset::{AssetLockChangeSet, SHIELDED_RECIPIENT_SIZE}; use platform_wallet::wallet::asset_lock::tracked::AssetLockStatus; @@ -63,6 +63,7 @@ impl_persistable_blob!(AssetLockEntryWire); struct AssetLockRecoveryRow { operation_id: Option>, shielded_recipient: Option>, + identity_recipient: Option>, lifecycle_blob: Vec, } @@ -123,6 +124,7 @@ impl AssetLockEntryWire { proof, operation_id: None, shielded_recipient: None, + identity_recipient: None, }) } } @@ -149,8 +151,8 @@ pub fn apply( // batches fold before reaching the store. let mut stmt = tx.prepare_cached( "INSERT INTO asset_locks \ - (wallet_id, outpoint, status, account_index, identity_index, amount_duffs, lifecycle_blob, operation_id, shielded_recipient) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) \ + (wallet_id, outpoint, status, account_index, identity_index, amount_duffs, lifecycle_blob, operation_id, shielded_recipient, identity_recipient) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) \ ON CONFLICT(wallet_id, outpoint) DO UPDATE SET \ status = excluded.status, \ account_index = excluded.account_index, \ @@ -158,22 +160,24 @@ pub fn apply( amount_duffs = excluded.amount_duffs, \ lifecycle_blob = excluded.lifecycle_blob, \ operation_id = COALESCE(excluded.operation_id, asset_locks.operation_id), \ - shielded_recipient = COALESCE(excluded.shielded_recipient, asset_locks.shielded_recipient) \ + shielded_recipient = COALESCE(excluded.shielded_recipient, asset_locks.shielded_recipient), \ + identity_recipient = COALESCE(excluded.identity_recipient, asset_locks.identity_recipient) \ WHERE asset_locks.status != 'consumed' OR excluded.status = 'consumed'", )?; for (op, entry) in &cs.asset_locks { let op_bytes = blob::encode_outpoint(op)?; let lifecycle_blob = blob::encode(&AssetLockEntryWire::from_entry(entry)?)?; let existing: Option = tx.query_row( - "SELECT operation_id, shielded_recipient, lifecycle_blob FROM asset_locks WHERE wallet_id = ?1 AND outpoint = ?2", + "SELECT operation_id, shielded_recipient, identity_recipient, lifecycle_blob FROM asset_locks WHERE wallet_id = ?1 AND outpoint = ?2", params![wallet_id.as_slice(), &op_bytes[..]], |row| Ok(AssetLockRecoveryRow { operation_id: row.get(0)?, shielded_recipient: row.get(1)?, - lifecycle_blob: row.get(2)?, + identity_recipient: row.get(2)?, + lifecycle_blob: row.get(3)?, }), ).optional()?; - // The operation UUID and the shielded recipient are immutable once + // The operation UUID and the recorded recipients are immutable once // stored. Reject the whole snapshot before any lifecycle or // sidecar write. if let (Some(incoming), Some(stored)) = ( @@ -201,6 +205,19 @@ pub fn apply( )); } } + let identity_recipient = entry.identity_recipient.map(|id| id.to_buffer()); + if let (Some(incoming), Some(stored)) = ( + identity_recipient.as_ref(), + existing + .as_ref() + .and_then(|row| row.identity_recipient.as_deref()), + ) { + if incoming.as_slice() != stored { + return Err(WalletStorageError::blob_decode( + "asset lock identity recipient cannot change", + )); + } + } // Both terminal variants project to SQL `consumed`, but the blob // retains stronger proof-gated completion and must never regress. if let Some(stored) = &existing { @@ -226,6 +243,9 @@ pub fn apply( shielded_recipient .as_ref() .map(|recipient| recipient.as_slice()), + identity_recipient + .as_ref() + .map(|recipient| recipient.as_slice()), ])?; } } @@ -308,6 +328,25 @@ fn status_str(s: &AssetLockStatus) -> &'static str { /// by `account_index`, inner-keyed by outpoint. pub type AssetLocksByAccount = BTreeMap>; +/// The nullable recovery columns read beside the frozen lifecycle blob. +struct RecoveryColumns { + operation_id: Option>, + shielded_recipient: Option>, + identity_recipient: Option>, +} + +impl RecoveryColumns { + /// Read columns 6..=8 of a `SELECT … operation_id, shielded_recipient, + /// identity_recipient` row. + fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(Self { + operation_id: row.get(6)?, + shielded_recipient: row.get(7)?, + identity_recipient: row.get(8)?, + }) + } +} + /// Decode one raw `(outpoint_bytes, account_index, lifecycle_blob, status)` /// tuple into the typed `(account_index, OutPoint, TrackedAssetLock)` /// triple that the reader functions consume. @@ -319,10 +358,14 @@ fn decode_row( account_index: i64, blob_bytes: &[u8], typed_status: &str, - operation_id: Option>, - shielded_recipient: Option>, + recovery: RecoveryColumns, ctx: &LoadCtx, ) -> Result<(u32, OutPoint, TrackedAssetLock), WalletStorageError> { + let RecoveryColumns { + operation_id, + shielded_recipient, + identity_recipient, + } = recovery; let outpoint = blob::decode_outpoint(op_bytes)?; let wire: AssetLockEntryWire = blob::decode(blob_bytes)?; let mut entry = wire.into_entry()?; @@ -342,6 +385,9 @@ fn decode_row( }) }) .transpose()?; + entry.identity_recipient = identity_recipient + .map(|bytes| super::id32("asset_locks.identity_recipient", &bytes).map(Identifier::from)) + .transpose()?; let account_index = crate::sqlite::util::safe_cast::i64_to_u32("asset_locks.account_index", account_index)?; // Typed-column vs blob cross-check: corruption that passes PRAGMA @@ -385,6 +431,7 @@ fn decode_row( proof: entry.proof, operation_id: entry.operation_id, shielded_recipient: entry.shielded_recipient, + identity_recipient: entry.identity_recipient, }; Ok((account_index, outpoint, tracked)) } @@ -400,7 +447,7 @@ pub fn load_state( ctx: &LoadCtx, ) -> Result { let mut stmt = conn.prepare( - "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_recipient \ + "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_recipient, identity_recipient \ FROM asset_locks WHERE wallet_id = ?1", )?; let mut rows = stmt.query(params![wallet_id.as_slice()])?; @@ -412,15 +459,13 @@ pub fn load_state( blob::check_size(row.get::<_, i64>(3)?)?; let blob_bytes: Vec = row.get(4)?; let status: String = row.get(5)?; - let operation_id: Option> = row.get(6)?; - let shielded_recipient: Option> = row.get(7)?; + let recovery = RecoveryColumns::from_row(row)?; let (acct, outpoint, tracked) = decode_row( &op_bytes, account_index, &blob_bytes, &status, - operation_id, - shielded_recipient, + recovery, ctx, )?; out.entry(acct).or_default().insert(outpoint, tracked); @@ -441,7 +486,7 @@ pub fn load_unconsumed( ctx: &LoadCtx, ) -> Result { let mut stmt = conn.prepare( - "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_recipient \ + "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_recipient, identity_recipient \ FROM asset_locks WHERE wallet_id = ?1 AND (status != 'consumed' OR operation_id IS NOT NULL)", )?; let mut rows = stmt.query(params![wallet_id.as_slice()])?; @@ -453,15 +498,13 @@ pub fn load_unconsumed( blob::check_size(row.get::<_, i64>(3)?)?; let blob_bytes: Vec = row.get(4)?; let status: String = row.get(5)?; - let operation_id: Option> = row.get(6)?; - let shielded_recipient: Option> = row.get(7)?; + let recovery = RecoveryColumns::from_row(row)?; let (acct, outpoint, tracked) = decode_row( &op_bytes, account_index, &blob_bytes, &status, - operation_id, - shielded_recipient, + recovery, ctx, )?; if tracked.status.is_consumed() && tracked.operation_id.is_none() { @@ -527,6 +570,7 @@ mod tests { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1000, status, proof, @@ -566,6 +610,7 @@ mod tests { proof: tracked.proof, operation_id: tracked.operation_id, shielded_recipient: tracked.shielded_recipient, + identity_recipient: tracked.identity_recipient, }) .expect("stored asset lock must load back") } @@ -757,6 +802,7 @@ mod tests { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1000, status: AssetLockStatus::Built, proof: None, diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs index 3c3a14eafa3..b91889eab3a 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs @@ -8,6 +8,7 @@ use crate::common; use common::{ensure_wallet_meta, fresh_persister, wid}; use dashcore::{OutPoint, Transaction, Txid}; +use dpp::prelude::Identifier; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use platform_wallet::changeset::{ AssetLockChangeSet, AssetLockEntry, PlatformWalletPersistence, ShieldedRecipientRaw, @@ -39,6 +40,7 @@ fn entry(op: OutPoint, status: AssetLockStatus) -> AssetLockEntry { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1000, status, proof: None, @@ -444,6 +446,110 @@ fn sqlite_advertises_asset_lock_shielded_recipients() { )); } +#[test] +fn should_preserve_identity_recipient_when_later_snapshot_lacks_it_and_reject_a_change() { + let (persister, _tmp, path) = fresh_persister(); + let w = wid(0xAC); + ensure_wallet_meta(&persister, &w); + let outpoint = op(0x37); + let recipient = Identifier::from([0x21; 32]); + let store = |persister: &platform_wallet_storage::SqlitePersister, row: AssetLockEntry| { + persister.store( + w, + platform_wallet::changeset::PlatformWalletChangeSet { + asset_locks: Some(AssetLockChangeSet { + asset_locks: [(outpoint, row)].into_iter().collect(), + ..Default::default() + }), + ..Default::default() + }, + ) + }; + let unbound = |status| AssetLockEntry { + funding_type: AssetLockFundingType::IdentityTopUpNotBound, + ..entry(outpoint, status) + }; + let mut recorded = unbound(AssetLockStatus::Built); + recorded.identity_recipient = Some(recipient); + store(&persister, recorded).unwrap(); + // A later snapshot without the recipient (a status advance) keeps it. + store(&persister, unbound(AssetLockStatus::Broadcast)).unwrap(); + // A snapshot naming another identity is refused before any write. + let mut redirected = unbound(AssetLockStatus::ChainLocked); + redirected.identity_recipient = Some(Identifier::from([0x22; 32])); + assert!(store(&persister, redirected).is_err()); + drop(persister); + + let persister = reopen(&path); + let conn = persister.lock_conn_for_test(); + let locks = + asset_locks::load_unconsumed(&conn, &w, &platform_wallet_storage::LoadCtx::strict()) + .unwrap(); + let restored = &locks[&0][&outpoint]; + assert_eq!(restored.identity_recipient, Some(recipient)); + assert_eq!(restored.status, AssetLockStatus::Broadcast); + // The column refuses any length but 32 and never changes once set. + assert!(conn + .execute( + "UPDATE asset_locks SET identity_recipient = ?1", + [vec![1_u8; 31]] + ) + .is_err()); + assert!(conn + .execute( + "UPDATE asset_locks SET identity_recipient = ?1", + [vec![0x23_u8; 32]] + ) + .is_err()); +} + +#[test] +fn should_fail_the_load_when_a_stored_identity_recipient_has_the_wrong_length() { + let (persister, _tmp, _) = fresh_persister(); + let w = wid(0xAD); + ensure_wallet_meta(&persister, &w); + let outpoint = op(0x38); + persister + .store( + w, + platform_wallet::changeset::PlatformWalletChangeSet { + asset_locks: Some(AssetLockChangeSet { + asset_locks: [(outpoint, entry(outpoint, AssetLockStatus::Built))] + .into_iter() + .collect(), + ..Default::default() + }), + ..Default::default() + }, + ) + .unwrap(); + let conn = persister.lock_conn_for_test(); + // The CHECK constraint stops this at the SQL layer; bypass it to prove + // the reader fails closed on its own rather than yielding a row with no + // recipient (which would read as an unassigned lock). + conn.execute_batch("PRAGMA ignore_check_constraints = ON") + .unwrap(); + conn.execute( + "UPDATE asset_locks SET identity_recipient = ?1", + [vec![0xff_u8; 31]], + ) + .unwrap(); + conn.execute_batch("PRAGMA ignore_check_constraints = OFF") + .unwrap(); + assert!( + asset_locks::load_unconsumed(&conn, &w, &platform_wallet_storage::LoadCtx::strict()) + .is_err() + ); +} + +#[test] +fn sqlite_advertises_asset_lock_identity_recipients() { + let (persister, _tmp, _) = fresh_persister(); + assert!(persister.persistence_capabilities().contains( + platform_wallet::changeset::PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS + )); +} + fn recipient_bytes(seed_byte: u8) -> ShieldedRecipientRaw { [seed_byte; SHIELDED_RECIPIENT_SIZE] } diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_blob_roundtrip_coverage.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_blob_roundtrip_coverage.rs index 538f310b37e..19066314285 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_blob_roundtrip_coverage.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_blob_roundtrip_coverage.rs @@ -53,6 +53,7 @@ fn entry(op: OutPoint, status: AssetLockStatus, proof: Option) - identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1000, status, proof, diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_load_reconstruction.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_load_reconstruction.rs index 9f45ae82a58..e6c7fca0179 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_load_reconstruction.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_load_reconstruction.rs @@ -1088,6 +1088,7 @@ fn tc_p4_005_load_asset_locks_bucketed() { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1000, status: AssetLockStatus::Built, proof: None, @@ -1394,6 +1395,7 @@ fn tc_p4_008c_asset_locks_corruption_is_hard_error() { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1000, status: AssetLockStatus::Built, proof: None, diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs index 58cc3c18f3b..4a97f10525e 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs @@ -407,6 +407,7 @@ fn tc010_asset_lock_roundtrip() { identity_index: 9, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 12_345, status: AssetLockStatus::Built, proof: None, @@ -474,6 +475,7 @@ fn tc010b_recovered_from_chain_lock_roundtrip() { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 500_000, status: AssetLockStatus::RecoveredFromChain, proof: Some(dpp::prelude::AssetLockProof::Chain(ChainAssetLockProof { @@ -546,6 +548,7 @@ fn tc010c_stale_recovery_snapshot_cannot_regress_consumed_row() { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1_000_000, status: status.clone(), proof: match status { diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_recovery_mode.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_recovery_mode.rs index b5b136ff238..f08b9bf330a 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_recovery_mode.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_recovery_mode.rs @@ -291,6 +291,7 @@ fn seed_asset_lock_status_drift( identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1_000, status: AssetLockStatus::Consumed, proof: None, diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs index f1c5755c448..5c68ef7d367 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs @@ -15,13 +15,13 @@ use platform_wallet_storage::sqlite::{migrations as mig, schema::versions::Domai /// Golden `(version, name)` fingerprint of the frozen migration set. Bump /// deliberately only when adding/removing/renaming a migration file. const EXPECTED_ID_FINGERPRINT: &str = - "b1e10a6494cc31d24fabe4852477b3b93a2a98a7f310681b132ca8d9adef7311"; + "b68823218de8f97c66083dbd213856c47100fcf11c02b9bf9bea1addecf01fc1"; /// Golden content-level fingerprint over every migration's rendered SQL. /// Bump it only when ADDING a migration file; a body change on an already /// applied migration is a defect, not a golden to refresh. const EXPECTED_SQL_FINGERPRINT: &str = - "4490b15ba9de27bf5b30a47e462dc3b71c061a47f738a5240cdc89b3abc4ff43"; + "6e90f3d9c1d57b4bbc74b940f43d81586b9429813b05e63a8469a62e6bc4f311"; /// The migrations merged `v4.2-dev` already ships. Refinery keys /// `refinery_schema_history` by version and validates an applied migration's diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_structural_hardening.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_structural_hardening.rs index 6671c463a72..925ccbceea2 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_structural_hardening.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_structural_hardening.rs @@ -378,6 +378,7 @@ fn asset_lock_typed_vs_blob_mismatch_rejected() { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1, status: AssetLockStatus::Built, proof: None, diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_version_bump.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_version_bump.rs index acf6835a3e9..73041514b6e 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_version_bump.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_version_bump.rs @@ -366,6 +366,7 @@ fn asset_lock_changeset() -> AssetLockChangeSet { identity_index: 0, operation_id: None, shielded_recipient: None, + identity_recipient: None, amount_duffs: 1, status: AssetLockStatus::Built, proof: None, diff --git a/packages/rs-platform-wallet/src/changeset/changeset.rs b/packages/rs-platform-wallet/src/changeset/changeset.rs index 23d416973a3..198fc734563 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -1584,6 +1584,24 @@ pub const SHIELDED_RECIPIENT_SIZE: usize = 43; /// converts it back into an address, and the resume check compares bytes. pub type ShieldedRecipientRaw = [u8; SHIELDED_RECIPIENT_SIZE]; +/// The recipient an asset lock is built to pay, recorded on its tracked row +/// before the lock is dispatched so a resume pays it rather than whatever the +/// resuming call names. +/// +/// Only two funding types record one. A shielded funding (Type 18) records its +/// Orchard address. An unbound identity top-up (`IdentityTopUpNotBound`) +/// records its identity: its credit output is the next address of the wallet's +/// unbound top-up account, so nothing on chain names the identity. A bound +/// top-up names its identity by the account's registration index and records +/// nothing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AssetLockRecipient { + /// The raw Orchard address a shielded funding pays. + Shielded(ShieldedRecipientRaw), + /// The identity an identity top-up pays. + Identity(Identifier), +} + /// A single asset lock entry in the changeset. /// /// Contains all fields needed to fully reconstruct a @@ -1629,19 +1647,26 @@ pub struct AssetLockEntry { ) )] pub shielded_recipient: Option, + /// The identity an unbound identity top-up (`IdentityTopUpNotBound`) was + /// built to pay, or was later assigned to pay; `None` for other funding + /// types and for an unbound lock nothing records a recipient for (one + /// rebuilt from the chain). Like `operation_id`, immutable once recorded. + #[cfg_attr(feature = "serde", serde(default))] + pub identity_recipient: Option, } impl AssetLockEntry { - /// Preserve the immutable operation association and shielded recipient + /// Preserve the immutable operation association and recorded recipients /// when folding or replaying a possibly stale snapshot. Returns false for /// a conflicting UUID or recipient: the caller must discard the whole /// snapshot so its lifecycle cannot be attached to a different operation - /// or redirect a pending shielded funding. + /// or redirect a pending funding. #[must_use = "a conflicting operation snapshot must not be applied"] pub(crate) fn preserve_recovery_metadata( &mut self, previous_operation_id: Option<[u8; 16]>, previous_shielded_recipient: Option, + previous_identity_recipient: Option, ) -> bool { if let Some(previous_id) = previous_operation_id { if self @@ -1663,6 +1688,16 @@ impl AssetLockEntry { } self.shielded_recipient = Some(previous_recipient); } + if let Some(previous_recipient) = previous_identity_recipient { + if self + .identity_recipient + .is_some_and(|incoming| incoming != previous_recipient) + { + tracing::warn!(out_point = %self.out_point, "Ignoring asset-lock snapshot with a conflicting identity recipient"); + return false; + } + self.identity_recipient = Some(previous_recipient); + } true } } @@ -1684,9 +1719,11 @@ impl Merge for AssetLockChangeSet { // racing snapshots immaterial. for (out_point, mut entry) in other.asset_locks { if let Some(existing) = self.asset_locks.get_mut(&out_point) { - if !entry - .preserve_recovery_metadata(existing.operation_id, existing.shielded_recipient) - { + if !entry.preserve_recovery_metadata( + existing.operation_id, + existing.shielded_recipient, + existing.identity_recipient, + ) { continue; } if existing.status == AssetLockStatus::DrainCompleted @@ -1696,6 +1733,7 @@ impl Merge for AssetLockChangeSet { // association or recipient carried by a delayed snapshot. existing.operation_id = entry.operation_id; existing.shielded_recipient = entry.shielded_recipient; + existing.identity_recipient = entry.identity_recipient; continue; } } @@ -2855,6 +2893,7 @@ mod tests { let entry_with = |status: AssetLockStatus| AssetLockEntry { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point: outpoint, transaction: Transaction { version: 3, @@ -2951,6 +2990,34 @@ mod tests { recorded.merge(redirected); assert_eq!(recorded.asset_locks, expected.asset_locks); + // The recorded identity recipient of an unbound top-up behaves the + // same: kept through a snapshot without one, a conflicting one vetoed. + let identity = Identifier::from([0x73u8; 32]); + let mut recorded = cs_with(AssetLockStatus::Broadcast); + recorded + .asset_locks + .get_mut(&outpoint) + .unwrap() + .identity_recipient = Some(identity); + recorded.merge(cs_with(AssetLockStatus::RecoveredFromChain)); + assert_eq!( + recorded.asset_locks[&outpoint].identity_recipient, + Some(identity) + ); + assert_eq!( + recorded.asset_locks[&outpoint].status, + AssetLockStatus::RecoveredFromChain + ); + let mut redirected = cs_with(AssetLockStatus::ChainLocked); + redirected + .asset_locks + .get_mut(&outpoint) + .unwrap() + .identity_recipient = Some(Identifier::from([0x74u8; 32])); + let expected = recorded.clone(); + recorded.merge(redirected); + assert_eq!(recorded.asset_locks, expected.asset_locks); + // Non-terminal transitions stay last-write-wins in both // directions (live advances overwrite RecoveredFromChain, and // enrichment overwrites Broadcast). @@ -3599,6 +3666,7 @@ mod tests { AssetLockEntry { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point: OutPoint::default(), transaction: Transaction { version: 3, diff --git a/packages/rs-platform-wallet/src/changeset/core_bridge.rs b/packages/rs-platform-wallet/src/changeset/core_bridge.rs index a0594b36402..918b41ee09e 100644 --- a/packages/rs-platform-wallet/src/changeset/core_bridge.rs +++ b/packages/rs-platform-wallet/src/changeset/core_bridge.rs @@ -7401,7 +7401,7 @@ mod tests { // A wallet whose identity-registration funding account has a // real address pool, plus an asset-lock tx whose credit output // pays into it (built by the production builder). - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -7419,6 +7419,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + Arc::clone(&generation), ); let (tx, _path) = asset_lock_manager .build_asset_lock_transaction( @@ -7525,7 +7526,7 @@ mod tests { use crate::wallet::asset_lock::manager::AssetLockManager; use crate::wallet::persister::WalletPersister; - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -7543,6 +7544,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + Arc::clone(&generation), ); let (tx, _path) = asset_lock_manager .build_asset_lock_transaction( @@ -7676,7 +7678,7 @@ mod tests { use crate::wallet::asset_lock::tracked::AssetLockStatus; use crate::wallet::persister::WalletPersister; - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -7694,6 +7696,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + Arc::clone(&generation), ); let (tx, _path) = asset_lock_manager .build_asset_lock_transaction( @@ -7802,7 +7805,7 @@ mod tests { use crate::wallet::asset_lock::tracked::AssetLockStatus; use crate::wallet::persister::WalletPersister; - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -7820,6 +7823,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + Arc::clone(&generation), ); let (tx, _path) = asset_lock_manager .build_asset_lock_transaction( @@ -7948,6 +7952,7 @@ mod tests { AssetLockEntry { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: dashcore::Transaction { version: 3, diff --git a/packages/rs-platform-wallet/src/changeset/mod.rs b/packages/rs-platform-wallet/src/changeset/mod.rs index 266d2d6e2c8..e7b512c542d 100644 --- a/packages/rs-platform-wallet/src/changeset/mod.rs +++ b/packages/rs-platform-wallet/src/changeset/mod.rs @@ -34,16 +34,16 @@ pub mod traits; pub(crate) use changeset::account_address_pool_entries; pub use changeset::{ upsert_pending_contact_crypto, AccountAddressPoolEntry, AccountRegistrationEntry, - AssetLockChangeSet, AssetLockEntry, ContactChangeSet, ContactRequestEntry, CoreChangeSet, - DpnsNameSaleStatus, DpnsNameStateChangeSet, DpnsNameStateEntry, HighestUsedIndexes, - IdentityChangeSet, IdentityEntry, IdentityKeyDerivationIndices, IdentityKeyEntry, - IdentityKeysChangeSet, InvitationChangeSet, InvitationEntry, InvitationStatus, - KeyDerivationBreadcrumb, KeyWithBreadcrumb, PendingContactCrypto, PendingContactCryptoKey, - PendingContactCryptoKind, PendingContactCryptoOp, PlatformAddressBalanceEntry, - PlatformAddressChangeSet, PlatformWalletChangeSet, PrivateContactRequestsPosition, - ProviderKeyAccountEntry, ProviderKeyExtendedPubKey, ProviderPlatformNodePubKey, - ReceivedContactRequestKey, SentContactRequestKey, ShieldedRecipientRaw, TokenBalanceChangeSet, - WalletMetadataEntry, SHIELDED_RECIPIENT_SIZE, + AssetLockChangeSet, AssetLockEntry, AssetLockRecipient, ContactChangeSet, ContactRequestEntry, + CoreChangeSet, DpnsNameSaleStatus, DpnsNameStateChangeSet, DpnsNameStateEntry, + HighestUsedIndexes, IdentityChangeSet, IdentityEntry, IdentityKeyDerivationIndices, + IdentityKeyEntry, IdentityKeysChangeSet, InvitationChangeSet, InvitationEntry, + InvitationStatus, KeyDerivationBreadcrumb, KeyWithBreadcrumb, PendingContactCrypto, + PendingContactCryptoKey, PendingContactCryptoKind, PendingContactCryptoOp, + PlatformAddressBalanceEntry, PlatformAddressChangeSet, PlatformWalletChangeSet, + PrivateContactRequestsPosition, ProviderKeyAccountEntry, ProviderKeyExtendedPubKey, + ProviderPlatformNodePubKey, ReceivedContactRequestKey, SentContactRequestKey, + ShieldedRecipientRaw, TokenBalanceChangeSet, WalletMetadataEntry, SHIELDED_RECIPIENT_SIZE, }; pub use client_start_state::ClientStartState; pub use client_wallet_start_state::ClientWalletStartState; diff --git a/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs b/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs index 55c549c015b..b8a2bd7578c 100644 --- a/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs +++ b/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs @@ -150,13 +150,30 @@ impl PersistenceCapabilities { /// is marked. pub const PRIVATE_CONTACT_REQUEST_SCAN_STATE: Self = Self(1 << 15); + /// The identity an unbound identity top-up (`IdentityTopUpNotBound`) was + /// built to pay survives store/load with its row, so a resume after + /// restart pays that identity and refuses another. Required, unlike + /// [`Self::ASSET_LOCK_SHIELDED_RECIPIENTS`]: the recipient is not on chain + /// and an unbound lock without one cannot be resumed until a recipient is + /// assigned, so the wallet does not build an unbound top-up lock for a + /// backend that would lose it on restart. + pub const ASSET_LOCK_IDENTITY_RECIPIENTS: Self = Self(1 << 17); + /// Index of the highest bit declared above. It lives here, beside the /// constants, so adding a bit and bumping this is one edit in one place /// — and `every_declared_bit_has_a_stable_name` walks up to it, so a new /// bit that never reaches `KNOWN` fails a test instead of gating /// behaviour invisibly. The same test asserts nothing above it is named, /// which is what catches a bit added without bumping this. - const HIGHEST_DECLARED_BIT: u32 = 15; + const HIGHEST_DECLARED_BIT: u32 = 17; + + /// Bits claimed by an open pull request on another branch, so they are + /// not reused here and are skipped by `every_declared_bit_has_a_stable_name` + /// until that change merges forward and names them. Bit 16 is + /// `OUTPOINT_LOCKS` (dashpay/platform#5890, against `v5.1-dev`); remove it + /// from this list when that constant arrives. + #[cfg(test)] + const RESERVED_BITS: &'static [u32] = &[16]; /// Capabilities required before exporting and funding an invitation voucher. pub const INVITATION_CREATION: Self = Self( @@ -278,6 +295,10 @@ impl PersistenceCapabilities { PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE, "private_contact_request_scan_state", ), + ( + PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS, + "asset_lock_identity_recipients", + ), ]; KNOWN @@ -295,7 +316,7 @@ impl PersistenceCapabilities { /// failure the test exists to catch. Written as a module-level `const _` so /// it is evaluated in every build, test or not. const _: () = assert!( - PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE.bits() + PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS.bits() == 1u64 << PersistenceCapabilities::HIGHEST_DECLARED_BIT, "HIGHEST_DECLARED_BIT must name the highest declared capability bit" ); @@ -335,6 +356,10 @@ mod tests { PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE.bits(), 0x8000 ); + assert_eq!( + PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS.bits(), + 0x20000 + ); assert_eq!(PersistenceCapabilities::WALLET_DRAIN.bits(), 0x2285); assert_eq!( PersistenceCapabilities::ASSET_LOCK_RECONCILIATION.bits(), @@ -368,6 +393,15 @@ mod tests { // every `names()`-based diagnostic — exactly what this test exists // to prevent. Walking the whole width cannot go stale. for shift in 0..=PersistenceCapabilities::HIGHEST_DECLARED_BIT { + if PersistenceCapabilities::RESERVED_BITS.contains(&shift) { + assert!( + PersistenceCapabilities::from_bits_retain(1u64 << shift) + .names() + .is_empty(), + "bit 1 << {shift} is named, so it is no longer only reserved" + ); + continue; + } let bit = PersistenceCapabilities::from_bits_retain(1u64 << shift); assert_eq!( bit.names().len(), diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..cb57634b0f6 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -675,6 +675,42 @@ pub enum PlatformWalletError { requested: crate::changeset::ShieldedRecipientRaw, }, + /// An unbound identity top-up lock is being resumed (or assigned) to a + /// different identity than the one its tracked row recorded. The recorded + /// identity is the one the user confirmed; nothing was submitted or paid. + /// Resume with the recorded identity instead. The FFI reports it with the + /// same code as [`Self::AssetLockRecipientMismatch`]. + #[error( + "Asset lock {out_point} was built to top up identity {recorded} and cannot be resumed to {requested}" + )] + AssetLockIdentityRecipientMismatch { + out_point: dashcore::OutPoint, + recorded: Identifier, + requested: Identifier, + }, + + /// An unbound identity top-up lock records no recipient (it was rebuilt + /// from the chain, for example after a restore from the seed, and its + /// credit output names no identity), so no resume pays it: it may have + /// been meant for someone else's identity. Nothing was submitted or paid. + /// The funds stay recoverable: assign the lock a recipient the user + /// chooses, then resume it. + #[error("Asset lock {0} records no identity to top up; assign a recipient before resuming it")] + AssetLockRecipientUnknown(dashcore::OutPoint), + + /// A bound identity top-up lock pays the wallet's identity at its + /// registration index, but the wallet holds no identity there yet (for + /// example, identities are still being discovered after a restore). + /// Nothing was submitted or paid; resume after the identity is loaded. + #[error( + "Asset lock {out_point} tops up the wallet's identity at index {identity_index}, \ + which this wallet does not hold yet" + )] + AssetLockIdentityNotLoaded { + out_point: dashcore::OutPoint, + identity_index: u32, + }, + #[error("SDK error: {0}")] Sdk(#[from] dash_sdk::Error), diff --git a/packages/rs-platform-wallet/src/manager/accessors.rs b/packages/rs-platform-wallet/src/manager/accessors.rs index b1389f98fe2..20d2e047c79 100644 --- a/packages/rs-platform-wallet/src/manager/accessors.rs +++ b/packages/rs-platform-wallet/src/manager/accessors.rs @@ -158,6 +158,13 @@ pub struct TrackedAssetLockSnapshot { pub registration_index: u32, pub instant_lock_present: bool, pub chain_lock_height: u32, + /// The identity an unbound identity top-up (lock type 2) pays; a resume + /// pays it and refuses any other (`TrackedAssetLock::identity_recipient`). + pub identity_recipient: Option, + /// An unbound top-up that records no identity, not consumed: no resume + /// pays it until the user assigns a recipient + /// (`TrackedAssetLock::is_unassigned_identity_top_up`). + pub identity_recipient_unassigned: bool, } /// Snapshot of the per-account metadata for a single account. @@ -1061,6 +1068,8 @@ impl PlatformWalletManager

{ registration_index: lock.identity_index, instant_lock_present, chain_lock_height, + identity_recipient: lock.identity_recipient, + identity_recipient_unassigned: lock.is_unassigned_identity_top_up(), } }) .collect() diff --git a/packages/rs-platform-wallet/src/test_support.rs b/packages/rs-platform-wallet/src/test_support.rs index edcf03a0194..557835ca738 100644 --- a/packages/rs-platform-wallet/src/test_support.rs +++ b/packages/rs-platform-wallet/src/test_support.rs @@ -55,6 +55,24 @@ use crate::wallet::identity::IdentityManager; use crate::wallet::platform_wallet::PlatformWallet; use crate::wallet::platform_wallet::{PlatformWalletInfo, WalletId}; +/// The live generation of `wallet_id` in `wallet_manager`, for a test that +/// builds an `AssetLockManager` over a wallet it registered itself: the +/// manager refuses to build on any other generation. +#[cfg(test)] +pub(crate) fn wallet_generation( + wallet_manager: &Arc>>, + wallet_id: &WalletId, +) -> Arc { + let wm = wallet_manager + .try_read() + .expect("fixture wallet manager is not locked"); + Arc::clone( + &wm.get_wallet_info(wallet_id) + .expect("fixture wallet is registered") + .generation, + ) +} + /// Broadcaster whose first call fails with a definitive pre-send rejection /// and which succeeds afterwards, to model a transient broadcast error /// followed by a user retry. @@ -933,17 +951,34 @@ pub(crate) async fn platform_wallet_in( wallet_manager: Arc>>, wallet_id: WalletId, ) -> PlatformWallet { - let (network, generation) = { + let network = { let manager = wallet_manager.read().await; - let (wallet, info) = manager + let (wallet, _) = manager .get_wallet_and_info(&wallet_id) .expect("wallet present"); - (wallet.network, Arc::clone(&info.generation)) + wallet.network }; let sdk = SdkBuilder::new_mock() .with_network(network) .build() .expect("mock sdk"); + platform_wallet_with_sdk(wallet_manager, wallet_id, sdk).await +} + +/// [`platform_wallet_in`] over a caller-built (for example, mock-primed) SDK. +#[cfg(test)] +pub(crate) async fn platform_wallet_with_sdk( + wallet_manager: Arc>>, + wallet_id: WalletId, + sdk: dash_sdk::Sdk, +) -> PlatformWallet { + let generation = { + let manager = wallet_manager.read().await; + let (_, info) = manager + .get_wallet_and_info(&wallet_id) + .expect("wallet present"); + Arc::clone(&info.generation) + }; let spv = Arc::new(SpvRuntime::new( Arc::clone(&wallet_manager), Arc::new(PlatformEventManager::new(Vec::new())), diff --git a/packages/rs-platform-wallet/src/wallet/apply.rs b/packages/rs-platform-wallet/src/wallet/apply.rs index 81512cad78a..3fb112daa7e 100644 --- a/packages/rs-platform-wallet/src/wallet/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/apply.rs @@ -384,6 +384,7 @@ impl PlatformWalletInfo { if !entry.preserve_recovery_metadata( existing.operation_id, existing.shielded_recipient, + existing.identity_recipient, ) { continue; } @@ -392,6 +393,7 @@ impl PlatformWalletInfo { { existing.operation_id = entry.operation_id; existing.shielded_recipient = entry.shielded_recipient; + existing.identity_recipient = entry.identity_recipient; continue; } } @@ -408,6 +410,7 @@ impl PlatformWalletInfo { status: entry.status, proof: entry.proof, shielded_recipient: entry.shielded_recipient, + identity_recipient: entry.identity_recipient, }, ); } @@ -777,6 +780,7 @@ mod tests { AssetLockEntry { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: dashcore::Transaction { version: 3, @@ -855,6 +859,7 @@ mod tests { status, proof: None, shielded_recipient: None, + identity_recipient: None, } } @@ -932,6 +937,34 @@ mod tests { assert_eq!(restored.status, AssetLockStatus::RecoveredFromChain); } + #[test] + fn should_preserve_the_identity_recipient_when_applying_stale_snapshots() { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + let recipient = dpp::prelude::Identifier::from([0x83u8; 32]); + let mut recorded = recovery_asset_lock(AssetLockStatus::Broadcast, None); + recorded.identity_recipient = Some(recipient); + apply_recovery_asset_lock(&mut info, &mut wallet, recorded); + + // A stale snapshot without the recipient keeps it. + apply_recovery_asset_lock( + &mut info, + &mut wallet, + recovery_asset_lock(AssetLockStatus::RecoveredFromChain, None), + ); + let restored = &info.tracked_asset_locks[&OutPoint::default()]; + assert_eq!(restored.identity_recipient, Some(recipient)); + assert_eq!(restored.status, AssetLockStatus::RecoveredFromChain); + + // A snapshot naming another identity is dropped whole. + let mut redirected = recovery_asset_lock(AssetLockStatus::ChainLocked, None); + redirected.identity_recipient = Some(dpp::prelude::Identifier::from([0x84u8; 32])); + apply_recovery_asset_lock(&mut info, &mut wallet, redirected); + let restored = &info.tracked_asset_locks[&OutPoint::default()]; + assert_eq!(restored.identity_recipient, Some(recipient)); + assert_eq!(restored.status, AssetLockStatus::RecoveredFromChain); + } + #[test] fn should_keep_consumed_asset_locks_terminal_when_applying_stale_snapshots() { let mut wallet = build_test_wallet(); diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs index 57a6ae3b46a..6e48403cae1 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs @@ -4,11 +4,13 @@ //! addresses, and the unified `create_funded_asset_lock_proof` entry point. use crate::broadcaster::TransactionBroadcaster; +use std::sync::Arc; use std::time::Duration; -use crate::changeset::ShieldedRecipientRaw; +use crate::changeset::{AssetLockRecipient, ShieldedRecipientRaw}; use dashcore::Address as DashAddress; use dashcore::{OutPoint, Transaction, TxOut}; +use dpp::prelude::Identifier; use key_wallet::account::AccountType; use key_wallet::bip32::DerivationPath; use key_wallet::managed_account::address_pool::AddressState; @@ -26,7 +28,7 @@ use key_wallet::wallet::Wallet; use crate::changeset::{ AccountAddressPoolEntry, AccountRegistrationEntry, AssetLockChangeSet, PersistenceCapabilities, - PlatformWalletChangeSet, + PersistenceError, PlatformWalletChangeSet, }; use crate::error::PlatformWalletError; use crate::wallet::core::InBroadcastPin; @@ -203,6 +205,17 @@ impl AssetLockManager { ), PlatformWalletError, > { + // An unbound top-up lock pays only the identity its tracked row + // records, and this form tracks nothing: the lock would surface + // later, rebuilt from the chain, with no recipient. The funded + // pipeline builds those, recording the recipient first. + if funding_type == AssetLockFundingType::IdentityTopUpNotBound { + return Err(PlatformWalletError::InvalidParameter( + "an unbound identity top-up lock must record its recipient; build it through \ + the funded top-up, not the build-only API" + .to_string(), + )); + } let (transaction, path, token, accounts, pin, _funding_pools) = self .build_asset_lock_transaction_fenced( amount, @@ -280,6 +293,21 @@ impl AssetLockManager { .get_wallet_mut_and_info_mut(&self.wallet_id) .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id)))?; + // Only on the generation this manager was created for. A caller can + // await (an identity lookup, a quote) between taking its handle and + // building, and the wallet can be removed and re-created under the + // same id meanwhile: the info found here would be the replacement's, + // and the pin below would be created on its generation, so the + // pre-broadcast generation check would pass and the stale handle would + // spend the replacement's funds. Checked before anything is derived, + // reserved or signed, under the write guard the pin is created under, + // so the generation cannot change in between. + if !Arc::ptr_eq(&info.generation, &self.generation) { + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id, + ))); + } + // 0. For a per-index identity top-up, lazily derive + insert the // `IdentityTopUp { registration_index }` account (both the // xpub-bearing `Wallet.accounts` side and the managed @@ -869,7 +897,7 @@ impl AssetLockManager { fn persist_asset_lock_account_pools( &self, entries: Vec, - ) -> Result<(), crate::changeset::PersistenceError> { + ) -> Result<(), PersistenceError> { if entries.is_empty() { return Ok(()); } @@ -947,7 +975,7 @@ impl AssetLockManager { account_index: u32, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -957,7 +985,7 @@ impl AssetLockManager { account_index, funding_type, identity_index, - shielded_recipient, + recipient, signer, on_built, ) @@ -1001,7 +1029,7 @@ impl AssetLockManager { funding_account: AssetLockFundingAccount, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -1011,7 +1039,7 @@ impl AssetLockManager { funding_account.account_index(), funding_type, identity_index, - shielded_recipient, + recipient, signer, on_built, ) @@ -1033,7 +1061,7 @@ impl AssetLockManager { source_index: u32, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -1044,7 +1072,7 @@ impl AssetLockManager { source_index, funding_type, identity_index, - shielded_recipient, + recipient, signer, None, on_built, @@ -1122,7 +1150,7 @@ impl AssetLockManager { minimum_lock_duffs: Option, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + recipient: Option, signer: &S, operation: &AssetLockOperationContext, on_built: Option<&AssetLockBuiltObserver<'_>>, @@ -1135,7 +1163,7 @@ impl AssetLockManager { account_index, funding_type, identity_index, - shielded_recipient, + recipient, signer, Some(operation), on_built, @@ -1199,11 +1227,68 @@ impl AssetLockManager { in_broadcast_pin.settle_released(); } + /// Stores the removal of an unsent lock's row and makes it durable, before + /// the caller releases the lock's inputs: a removal that is lost would + /// bring the `Built` row back after a restart, resumable to its + /// recipient, while the released inputs fund the user's next attempt, and + /// the recipient would be paid twice. + /// + /// A failed flush is tolerated only on a backend whose store commits + /// inline + /// ([`store_commits_inline`](crate::changeset::PlatformWalletPersistence::store_commits_inline)): + /// the removal was durable when `store` returned and the flush is only a + /// later notification, so failing on it would strand inputs that no row + /// can recover and no observed spend can clear. On a buffered backend it + /// is an error: the removal may still be only buffered while another + /// flush already committed the row. + fn store_lock_removal_durably( + &self, + removal: AssetLockChangeSet, + ) -> Result<(), PersistenceError> { + let removed: Vec = removal.removed.iter().copied().collect(); + self.persister.store(PlatformWalletChangeSet { + asset_locks: Some(removal), + ..Default::default() + })?; + match self.persister.flush() { + Err(error) if self.persister.store_commits_inline() => { + tracing::warn!( + ?removed, + %error, + "unsent asset lock's row removed inline; flush notification failed" + ); + Ok(()) + } + other => other, + } + } + + /// An unbound identity top-up lock is built only for a backend that keeps + /// its recipient across a restart + /// ([`PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS`]). The + /// recipient is not on chain, so a backend that loses it would reload the + /// lock unassigned and nothing could resume it until the user assigned it + /// a recipient by hand. Checked before anything is built or reserved. + pub(crate) fn require_identity_recipient_persistence(&self) -> Result<(), PlatformWalletError> { + let capabilities = self.persister.persistence_capabilities(); + let required = PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS; + if capabilities.contains(required) { + Ok(()) + } else { + Err(PlatformWalletError::Persistence(format!( + "an unbound identity top-up requires persistence capabilities {:?}", + capabilities.missing(required).names() + ))) + } + } + /// The build → persist → track → broadcast pipeline every funded lock - /// goes through. `shielded_recipient` is the Orchard address a shielded - /// funding (Type 18) will pay; it is recorded on the row created here, - /// so it is exactly as durable before dispatch as `operation_id`: flushed - /// before the broadcast for a drain, queued before it otherwise. + /// goes through. `recipient` is who the lock will pay. For a shielded + /// funding (Type 18, the Orchard address) and an unbound identity top-up + /// (the identity) it is recorded on the row created here (see + /// [`recorded_recipients`]), so it is exactly as durable before dispatch + /// as `operation_id`: flushed before the broadcast for a drain, and for a + /// recipient the backend can record; queued before it otherwise. #[allow(clippy::too_many_arguments)] async fn broadcast_funded_asset_lock_tracked( &self, @@ -1212,7 +1297,7 @@ impl AssetLockManager { source_index: u32, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + recipient: Option, signer: &S, operation: Option<&AssetLockOperationContext>, on_built: Option<&AssetLockBuiltObserver<'_>>, @@ -1220,6 +1305,11 @@ impl AssetLockManager { if operation.is_some() { self.require_wallet_drain_persistence()?; } + let (shielded_recipient, identity_recipient) = + recorded_recipients(funding_type, recipient)?; + if identity_recipient.is_some() { + self.require_identity_recipient_persistence()?; + } // Serialize build→persist so a concurrent build cannot interleave its // pool snapshot with ours. The snapshot is collected under the build's // wallet-manager guard; without this serialization, build A's snapshot @@ -1445,12 +1535,15 @@ impl AssetLockManager { // Only where the backend can record a recipient at all: a host without // the capability keeps the best-effort row every other funding has. + // An identity recipient always: the backend's capability was required + // before the build. let recipient_must_be_durable = operation.is_none() - && shielded_recipient.is_some() - && self - .persister - .persistence_capabilities() - .contains(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS); + && (identity_recipient.is_some() + || (shielded_recipient.is_some() + && self + .persister + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS))); let tracked = TrackedAssetLock { operation_id: operation.map(|context| context.operation_id), out_point, @@ -1462,6 +1555,7 @@ impl AssetLockManager { status: AssetLockStatus::Built, proof: None, shielded_recipient, + identity_recipient, }; if let Some(operation) = operation { operation.retain_checkpoint(tracked.clone()); @@ -1490,7 +1584,8 @@ impl AssetLockManager { "drain asset lock was not made durable before dispatch: {error}" )) })?; - self.track_asset_lock(tracked).await; + self.track_asset_lock(tracked, in_broadcast_pin.generation()) + .await; operation.clear_checkpoint(); } else if recipient_must_be_durable { // The recipient exists nowhere but this row: a lock recovered from @@ -1511,19 +1606,49 @@ impl AssetLockManager { }) .and_then(|()| self.persister.flush()); if let Err(error) = durable { - // The row may be buffered (a backend that restores a failed - // flush to its buffer) or committed (a store that succeeded - // before a failed flush), and a later flush or a restart would - // then surface a resumable row for inputs released below. Its - // removal is queued behind it — stores apply removals after - // upserts — so the abandoned row does not outlive this call - // unless the backend refuses that write too. The funding index - // stays consumed, as for the pool gate above. - self.queue_asset_lock_changeset(AssetLockChangeSet { + // The row may survive the failure: a failed flush may leave it + // buffered (a backend that restores a failed flush to its + // buffer) or committed (a store that succeeded before it), and + // a refused store may still have written it (a host without + // atomic changesets can write the row and fail on its recipient + // sidecar). A later flush or a restart would then surface a + // resumable row. Its removal is stored behind it — stores apply + // removals after upserts, and a buffered removal commits with + // the row it cancels — and made durable before the inputs are + // released: on a buffered backend another flush may already + // have committed the row, and a removal left only buffered + // would be lost with a crash. If the removal is refused or + // cannot be made durable, the row may outlive this call: + // releasing its inputs would let the user's retry be funded + // while a restart re-broadcasts the abandoned lock and pays + // the recipient a second time. The reservation and the + // in-broadcast fence then stay held, as for an uncertain + // removal after a rejected broadcast. The funding index stays + // consumed, as for the pool gate above. + let removal = self.store_lock_removal_durably(AssetLockChangeSet { removed: [out_point].into(), ..Default::default() }); drop(build_persist_guard); + let kind = if identity_recipient.is_some() { + "identity" + } else { + "shielded" + }; + if let Err(removal_error) = removal { + tracing::warn!( + %out_point, + %error, + %removal_error, + "abandoned asset lock's row may survive; keeping its inputs reserved" + ); + in_broadcast_pin.settle_pending_spend(); + return Err(PlatformWalletError::Persistence(format!( + "{kind} recipient was not made durable before dispatch, and the \ + abandoned row's removal was not made durable ({removal_error}), so \ + its inputs stay reserved: {error}" + ))); + } self.abandon_unsent_build( in_broadcast_pin, &funding_accounts, @@ -1532,12 +1657,15 @@ impl AssetLockManager { ) .await; return Err(PlatformWalletError::Persistence(format!( - "shielded recipient was not made durable before dispatch: {error}" + "{kind} recipient was not made durable before dispatch: {error}" ))); } - self.track_asset_lock(tracked).await; + self.track_asset_lock(tracked, in_broadcast_pin.generation()) + .await; } else { - let cs_built = self.track_asset_lock(tracked).await; + let cs_built = self + .track_asset_lock(tracked, in_broadcast_pin.generation()) + .await; // Hand the outpoint to the caller before the row is persisted, so a // caller that watches persisted rows never sees this lock unowned. // Nothing is awaited between here and the queueing below, so once @@ -1583,7 +1711,102 @@ impl AssetLockManager { // pending-spend fence everywhere else, until the wallet observes the // spend. A cancellation or unwind inside `broadcast` reaches no arm // at all and settles as pending through `InBroadcastPin::drop`. + // + // The send runs under the build generation's lifecycle gate, after + // checking that generation is still the wallet's: a removal can + // otherwise complete while the build or its durability gate is + // awaiting, discarding the reservation, and a stale handle would then + // push the removed wallet's transaction onto the network beside + // whatever the wallet (or one re-created under its id) builds from + // the same inputs. A removed generation sends nothing. The gate is + // taken holding no manager lock, as teardown takes it. + let lifecycle = in_broadcast_pin.generation().payment_guard().await; + let (is_current, may_still_send) = { + // The write guard makes the claim check atomic against a resume + // claiming dispatch under its read guard, as in + // `untrack_asset_lock`. + let wm = self.wallet_manager.write().await; + match wm.get_wallet_info(&self.wallet_id) { + Some(info) if in_broadcast_pin.is_on(&info.generation) => (true, false), + // Another party may still send this lock: a wallet re-created + // under this id that restored the row from the store (it can + // resume it), or a resume that snapshotted the row before the + // removal and claimed its dispatch (it sends without + // re-checking the generation). + Some(info) => ( + false, + info.tracked_asset_locks.contains_key(&out_point) + || self.resume_cleanup_excluded(&out_point), + ), + None => (false, self.resume_cleanup_excluded(&out_point)), + } + }; + if !is_current { + // This generation's teardown has completed; there is nothing left + // for its gate to exclude. + drop(lifecycle); + // Nothing was sent: a definitive pre-send abort, like a refused + // durability gate. A row left in the store would come back after a + // restart as a resumable `Built` lock while the caller's retry + // funds another from released inputs, paying the recipient twice, + // so the row's removal is stored (and, for a row stored durably + // above, flushed) before the inputs are released. Only the store + // and the pin are touched: the removed generation's tracked row + // and reservation went with it, and the wallet now under this id + // is another generation whose state this build does not own. + let durable_row = operation.is_some() || recipient_must_be_durable; + if may_still_send { + // The row and its inputs stay, as for a rejected broadcast + // whose cleanup a resume excludes, and the outcome is unknown + // rather than a removal: a caller that rebuilt from other + // inputs could pay the recipient twice. + in_broadcast_pin.settle_pending_spend(); + return Err(PlatformWalletError::TransactionBroadcastUnconfirmed( + format!( + "asset lock {out_point} was not sent by this call: wallet {} was \ + removed before the send, but the lock may still be sent by a resume \ + or by the wallet now under that id, so its row and inputs stay", + hex::encode(self.wallet_id) + ), + )); + } else if durable_row { + let removal = self.store_lock_removal_durably(AssetLockChangeSet { + removed: [out_point].into(), + ..Default::default() + }); + if let Err(error) = removal { + // The row may outlive this call: keep its inputs fenced, as + // for a refused removal above. + tracing::warn!( + %out_point, + %error, + "wallet removed before send and the lock's row may survive; keeping its inputs fenced" + ); + in_broadcast_pin.settle_pending_spend(); + return Err(PlatformWalletError::Persistence(format!( + "wallet {} was removed before the asset lock was sent, and the unsent \ + lock's removal was not made durable, so its inputs stay fenced: {error}", + hex::encode(self.wallet_id) + ))); + } + if let Some(operation) = operation { + operation.set(AssetLockOperationState::NotSent, None); + } + in_broadcast_pin.settle_released(); + } else { + // A best-effort row is removed best-effort, as it was stored. + self.queue_asset_lock_changeset(AssetLockChangeSet { + removed: [out_point].into(), + ..Default::default() + }); + in_broadcast_pin.settle_released(); + } + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id, + ))); + } let broadcast_outcome = self.broadcaster.broadcast(&tx).await; + drop(lifecycle); if let Err(e) = broadcast_outcome { if matches!(e, crate::broadcaster::BroadcastError::Rejected { .. }) { // The rejection alone does NOT establish the released verdict @@ -1605,26 +1828,32 @@ impl AssetLockManager { // still-tracked row would be resumable while its inputs are // re-spendable. let removed_built_row = cs_untrack.removed.contains(&out_point); - if operation.is_some() && removed_built_row { - if let Err(error) = self.persister.store(PlatformWalletChangeSet { - asset_locks: Some(cs_untrack), - ..Default::default() - }) { + // A row stored durably before the broadcast (a drain, or a lock + // recording its recipient) is removed durably too. Otherwise a + // lost removal would bring the `Built` row back after a + // restart, resumable to its recipient, while the inputs + // released below fund the user's next attempt: the same + // recipient could then be paid twice. + if (operation.is_some() || recipient_must_be_durable) && removed_built_row { + let kind = if operation.is_some() { + "drain" + } else { + "recipient-carrying" + }; + if let Err(error) = self.store_lock_removal_durably(cs_untrack) { // The durable removal is unknown. Keep the context // and input fence pending, but do NOT re-expose the row: // the removal may have committed, and a generic resume // must never dispatch a row with uncertain durability. + // A failed flush lands here only on a buffered backend, + // which may not have committed the removal; on one + // that commits each store inline the removal is + // already durable, and a failed notification must not + // strand the context or the inputs. return Err(PlatformWalletError::Persistence(format!( - "could not durably remove rejected drain asset lock: {error}" + "could not durably remove rejected {kind} asset lock: {error}" ))); } - // Drains run on inline-committing backends only (see - // `require_wallet_drain_persistence`), so the removal is - // already durable: a failed host notification must not - // strand its context or inputs. - if let Err(error) = self.persister.flush() { - tracing::warn!(%out_point, %error, "rejected drain removed inline; flush notification failed"); - } } else { self.queue_asset_lock_changeset(cs_untrack); } @@ -1769,6 +1998,43 @@ impl AssetLockManager { } } +/// The recipients the tracked row of a new lock records, as +/// `(shielded_recipient, identity_recipient)`. +/// +/// - A shielded funding records its Orchard address when it has one. +/// - An unbound identity top-up must name the identity it pays: its credit +/// output is the next address of the wallet's unbound top-up account, so +/// nothing on chain names the identity, and a lock built without a record +/// could later be resumed into whichever identity a recovery passes. +/// - A bound top-up may name its identity, but records nothing: the account's +/// registration index already names it. +/// - Every other pairing of a funding type and a recipient is refused, so a +/// recipient is never silently dropped. +fn recorded_recipients( + funding_type: AssetLockFundingType, + recipient: Option, +) -> Result<(Option, Option), PlatformWalletError> { + match (funding_type, recipient) { + ( + AssetLockFundingType::AssetLockShieldedAddressTopUp, + Some(AssetLockRecipient::Shielded(raw)), + ) => Ok((Some(raw), None)), + (AssetLockFundingType::IdentityTopUpNotBound, Some(AssetLockRecipient::Identity(id))) => { + Ok((None, Some(id))) + } + (AssetLockFundingType::IdentityTopUpNotBound, _) => { + Err(PlatformWalletError::InvalidParameter( + "an unbound identity top-up lock must name the identity it pays".into(), + )) + } + (AssetLockFundingType::IdentityTopUp, Some(AssetLockRecipient::Identity(_))) + | (_, None) => Ok((None, None)), + (funding_type, Some(recipient)) => Err(PlatformWalletError::InvalidParameter(format!( + "a {funding_type:?} asset lock cannot record recipient {recipient:?}" + ))), + } +} + /// Map a key-wallet [`AssetLockError`] to a [`PlatformWalletError`], promoting /// every coin-selection shortfall shape to the typed /// [`PlatformWalletError::AssetLockInsufficientFunds`] so callers get one @@ -1873,6 +2139,7 @@ mod tests { use crate::wallet::asset_lock::tracked::AssetLockStatus; use crate::wallet::asset_lock::tracked::TrackedAssetLock; use crate::wallet::asset_lock::AssetLockFunding; + use crate::wallet::core::WalletGeneration; use crate::wallet::persister::WalletPersister; use crate::wallet::platform_wallet::PlatformWalletInfo; use crate::wallet::platform_wallet::WalletId; @@ -1973,6 +2240,7 @@ mod tests { committed_stores: std::sync::atomic::AtomicUsize, fail_lock_store: std::sync::atomic::AtomicBool, failed_lock_stores: Mutex>, + records_identity_recipients: bool, } impl CapturingPersistence { @@ -2021,7 +2289,14 @@ mod tests { } fn persistence_capabilities(&self) -> crate::changeset::PersistenceCapabilities { - crate::changeset::PersistenceCapabilities::WALLET_DRAIN + let capabilities = crate::changeset::PersistenceCapabilities::WALLET_DRAIN; + if self.records_identity_recipients { + capabilities.union( + crate::changeset::PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS, + ) + } else { + capabilities + } } fn store( @@ -2135,6 +2410,7 @@ mod tests { status: entry.status.clone(), proof: entry.proof.clone(), shielded_recipient: entry.shielded_recipient, + identity_recipient: entry.identity_recipient, }, ); } @@ -2334,7 +2610,7 @@ mod tests { Arc, ) { let persistence = Arc::new(CapturingPersistence::default()); - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = crate::test_support::funded_coinjoin_wallet_manager().await; let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); @@ -2348,6 +2624,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + Arc::clone(&generation), )); (manager, signer, persistence) @@ -2380,165 +2657,1109 @@ mod tests { None, ) .await; - let err = result.expect_err("undersized drain must be refused"); + let err = result.expect_err("undersized drain must be refused"); + assert!( + err.to_string().contains("below the required minimum"), + "unexpected error for undersized drain: {err}" + ); + assert_eq!( + broadcaster.calls(), + 0, + "an abandoned drain must never reach the broadcaster" + ); + { + let wm = manager.wallet_manager.read().await; + let (_, info) = wm + .get_wallet_and_info(&manager.wallet_id) + .expect("wallet still present"); + assert!( + info.tracked_asset_locks.is_empty(), + "an abandoned drain must not leave a tracked row, got {:?}", + info.tracked_asset_locks + ); + } + assert!( + persistence.removed_outpoints().is_empty(), + "nothing was tracked, so nothing should be queued for removal" + ); + + // The reservation was released through the owner token: a follow-up + // drain over the same single-UTXO CoinJoin account must be able to + // select the inputs immediately and broadcast. + manager + .broadcast_funded_asset_lock_with_funding( + super::AssetLockBuildAmount::DrainAll { + minimum_lock_duffs: Some(1), + }, + &[AccountTypePreference::CoinJoin], + 0, + AssetLockFundingType::AssetLockShieldedAddressTopUp, + 0, + &signer, + None, + ) + .await + .expect("follow-up drain must reselect the released inputs"); + assert_eq!( + broadcaster.calls(), + 1, + "the follow-up drain should broadcast exactly once" + ); + } + + /// The built-lock observer sees the new outpoint exactly once, once the + /// lock is tracked but before its row is stored or anything has reached + /// the broadcaster, and the outpoint it sees is the one the build returns. + #[tokio::test] + async fn should_report_the_built_outpoint_before_persisting_or_broadcast() { + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let (manager, signer, persistence) = + coinjoin_funded_asset_lock_manager(Arc::clone(&broadcaster)).await; + let seen = Mutex::new(Vec::new()); + let observer = |out_point: OutPoint| { + let tracked = manager + .wallet_manager + .try_read() + .expect("the build holds no wallet-manager lock while observing") + .get_wallet_and_info(&manager.wallet_id) + .is_some_and(|(_, info)| info.tracked_asset_locks.contains_key(&out_point)); + let stored = persistence.stored_outpoints().contains(&out_point); + seen.lock() + .unwrap() + .push((out_point, tracked, stored, broadcaster.calls())); + }; + + let (_, out_point) = manager + .broadcast_funded_asset_lock_with_funding( + super::AssetLockBuildAmount::DrainAll { + minimum_lock_duffs: Some(1), + }, + &[AccountTypePreference::CoinJoin], + 0, + AssetLockFundingType::AssetLockShieldedAddressTopUp, + 0, + &signer, + Some(&observer), + ) + .await + .expect("drain must broadcast"); + + assert_eq!( + seen.into_inner().unwrap(), + vec![(out_point, true, false, 0)] + ); + assert_eq!(broadcaster.calls(), 1); + assert!(persistence.stored_outpoints().contains(&out_point)); + } + + /// The transaction of the asset-lock row `persistence` stored at + /// `out_point`. + fn stored_lock_transaction( + persistence: &CapturingPersistence, + out_point: &OutPoint, + ) -> Transaction { + persistence + .stored + .lock() + .unwrap() + .iter() + .filter_map(|cs| cs.asset_locks.as_ref()) + .find_map(|locks| locks.asset_locks.get(out_point)) + .expect("the lock's row was stored") + .transaction + .clone() + } + + /// A wallet removed or re-created under its id after the lock was built + /// sends nothing: the stale build's transaction never reaches the + /// broadcaster. Nothing was sent, so the row's removal is stored, the + /// inputs' fence comes down and the build reports the removal, unless + /// someone may still send the lock: the wallet now under the id tracks the + /// row itself (it may resume it), or a resume claimed the row's dispatch + /// before the removal. Then the row stays, its inputs stay fenced and the + /// outcome is reported as unknown, so the caller does not rebuild. + #[tokio::test] + async fn should_not_broadcast_a_lock_built_on_a_wallet_since_replaced() { + for (replacement_tracks_row, resume_claimed) in + [(false, false), (true, false), (false, true)] + { + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let (manager, signer, persistence) = + coinjoin_funded_asset_lock_manager(Arc::clone(&broadcaster)).await; + let built_on = Mutex::new(None); + let claim = Mutex::new(None); + // Stands in for a removal and re-creation landing while the build + // awaits: the wallet id now names a different generation, and the + // removed generation's tracked row went with it unless the + // replacement restored it from the store. + let observer = |out_point: OutPoint| { + if resume_claimed { + *claim.lock().unwrap() = Some(manager.claim_resume_dispatch(out_point)); + } + let mut wm = manager + .wallet_manager + .try_write() + .expect("the build holds no wallet-manager lock while observing"); + let info = wm + .get_wallet_info_mut(&manager.wallet_id) + .expect("wallet info"); + if !replacement_tracks_row { + info.tracked_asset_locks.remove(&out_point); + } + let old = + std::mem::replace(&mut info.generation, Arc::new(WalletGeneration::new())); + *built_on.lock().unwrap() = Some((out_point, old)); + }; + + let result = manager + .broadcast_funded_asset_lock_with_funding( + super::AssetLockBuildAmount::DrainAll { + minimum_lock_duffs: Some(1), + }, + &[AccountTypePreference::CoinJoin], + 0, + AssetLockFundingType::AssetLockShieldedAddressTopUp, + 0, + &signer, + Some(&observer), + ) + .await; + + let may_still_send = replacement_tracks_row || resume_claimed; + if may_still_send { + assert!( + matches!( + result, + Err(PlatformWalletError::TransactionBroadcastUnconfirmed(_)) + ), + "{result:?}" + ); + } else { + assert!( + matches!(result, Err(PlatformWalletError::WalletRemovedBeforeSend(_))), + "{result:?}" + ); + } + assert_eq!(broadcaster.calls(), 0); + drop(claim); + let (out_point, built_on) = built_on.into_inner().unwrap().expect("observed"); + let tx = stored_lock_transaction(&persistence, &out_point); + if may_still_send { + assert!(persistence.removed_outpoints().is_empty()); + assert!(built_on.in_broadcast_conflict(&tx).is_some()); + } else { + assert_eq!(persistence.removed_outpoints(), vec![out_point]); + assert_eq!(built_on.in_broadcast_conflict(&tx), None); + } + } + } + + /// A lock that records its identity recipient was stored durably before + /// the wallet was replaced: the removal is stored and flushed, the + /// replacement is not handed the row, and only then is the fence + /// released. When the store refuses the removal the row may survive, so + /// the inputs stay fenced and the error says so. + #[tokio::test] + async fn should_durably_remove_a_recipient_lock_built_on_a_wallet_since_replaced() { + use crate::changeset::AssetLockRecipient; + + let identity = dpp::prelude::Identifier::from([0x58; 32]); + for fail_remove_store in [false, true] { + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + fail_remove_store, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + let built_on = Mutex::new(None); + // Runs before the row is stored and tracked, so the build's own + // tracking finds the replacement. + let observer = |out_point: OutPoint| { + let mut wm = manager + .wallet_manager + .try_write() + .expect("the build holds no wallet-manager lock while observing"); + let info = wm + .get_wallet_info_mut(&manager.wallet_id) + .expect("wallet info"); + let old = + std::mem::replace(&mut info.generation, Arc::new(WalletGeneration::new())); + *built_on.lock().unwrap() = Some((out_point, old)); + }; + + let result = manager + .broadcast_funded_asset_lock_tracked( + super::AssetLockBuildAmount::Exact(1_000_000), + &ASSET_LOCK_FUNDING_SOURCES, + 0, + AssetLockFundingType::IdentityTopUpNotBound, + 0, + Some(AssetLockRecipient::Identity(identity)), + &signer, + None, + Some(&observer), + ) + .await; + + assert_eq!(broadcaster.calls(), 0); + assert!( + manager.list_tracked_locks().await.is_empty(), + "the replacement must not be handed a lock it never built" + ); + let (out_point, built_on) = built_on.into_inner().unwrap().expect("observed"); + let tx = stored_lock_transaction(&persistence, &out_point); + if fail_remove_store { + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("stay fenced")), + "{result:?}" + ); + assert!(built_on.in_broadcast_conflict(&tx).is_some()); + } else { + assert!( + matches!(result, Err(PlatformWalletError::WalletRemovedBeforeSend(_))), + "{result:?}" + ); + assert_eq!(persistence.removed_outpoints(), vec![out_point]); + assert_eq!( + persistence + .committed_stores + .load(std::sync::atomic::Ordering::SeqCst), + persistence.stored.lock().unwrap().len(), + "the removal was flushed, not left queued" + ); + assert_eq!(built_on.in_broadcast_conflict(&tx), None); + } + } + } + + /// A handle whose wallet was removed and re-created under the same id + /// while it awaited (an identity lookup before a top-up) builds nothing on + /// the replacement: the build is refused as a removal before anything is + /// derived, reserved, signed or stored, and nothing reaches the + /// broadcaster. Once the handle's generation is current again the same + /// single input funds a lock, so the refusal reserved nothing. + #[tokio::test] + async fn should_refuse_to_build_on_a_wallet_since_replaced() { + use crate::changeset::AssetLockRecipient; + + let identity = dpp::prelude::Identifier::from([0x5d; 32]); + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + let replaced = { + let mut wm = manager.wallet_manager.write().await; + let info = wm.get_wallet_info_mut(&manager.wallet_id).unwrap(); + std::mem::replace(&mut info.generation, Arc::new(WalletGeneration::new())) + }; + + let result = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(identity)), + ) + .await; + + assert!( + matches!(result, Err(PlatformWalletError::WalletRemovedBeforeSend(_))), + "{result:?}" + ); + assert_eq!(broadcaster.calls(), 0); + assert!(persistence.stored.lock().unwrap().is_empty()); + assert!(manager.list_tracked_locks().await.is_empty()); + + manager + .wallet_manager + .write() + .await + .get_wallet_info_mut(&manager.wallet_id) + .unwrap() + .generation = replaced; + fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(identity)), + ) + .await + .expect("the refused build reserved nothing"); + assert_eq!(broadcaster.calls(), 1); + } + + /// A lock whose broadcast ends without a verdict was reported to the + /// observer, and its row stays tracked and stored, so the caller can + /// resume it by the outpoint it was given. + #[tokio::test] + async fn should_keep_a_reported_lock_whose_broadcast_may_have_been_sent() { + let (manager, signer, persistence) = + coinjoin_funded_asset_lock_manager(Arc::new(AlwaysMaybeSentBroadcaster)).await; + let seen = Mutex::new(Vec::new()); + let observer = |out_point: OutPoint| seen.lock().unwrap().push(out_point); + + manager + .broadcast_funded_asset_lock_with_funding( + super::AssetLockBuildAmount::DrainAll { + minimum_lock_duffs: Some(1), + }, + &[AccountTypePreference::CoinJoin], + 0, + AssetLockFundingType::AssetLockShieldedAddressTopUp, + 0, + &signer, + Some(&observer), + ) + .await + .expect_err("an unconfirmed broadcast must fail the call"); + + let seen = seen.into_inner().unwrap(); + assert_eq!(seen.len(), 1); + assert!(persistence.removed_outpoints().is_empty()); + assert!(persistence.stored_outpoints().contains(&seen[0])); + let wm = manager.wallet_manager.read().await; + let (_, info) = wm + .get_wallet_and_info(&manager.wallet_id) + .expect("wallet still present"); + assert!(info.tracked_asset_locks.contains_key(&seen[0])); + } + + /// A lock whose broadcast is rejected was still reported to the observer, + /// which ran before the broadcast; the call then returns the rejection and + /// the lock's row is removed again. + #[tokio::test] + async fn should_report_a_lock_whose_broadcast_is_then_rejected() { + let (manager, signer, persistence) = + coinjoin_funded_asset_lock_manager(Arc::new(AlwaysRejectedBroadcaster)).await; + let seen = Mutex::new(Vec::new()); + let observer = |out_point: OutPoint| seen.lock().unwrap().push(out_point); + + manager + .broadcast_funded_asset_lock_with_funding( + super::AssetLockBuildAmount::DrainAll { + minimum_lock_duffs: Some(1), + }, + &[AccountTypePreference::CoinJoin], + 0, + AssetLockFundingType::AssetLockShieldedAddressTopUp, + 0, + &signer, + Some(&observer), + ) + .await + .expect_err("a rejected broadcast must fail the call"); + + let seen = seen.into_inner().unwrap(); + assert_eq!(seen.len(), 1); + assert_eq!(persistence.removed_outpoints(), seen); + } + + /// Builds, tracks and broadcasts one unbound identity top-up lock from the + /// wallet balance, paying `recipient`, without waiting for its proof. + async fn fund_unbound_top_up( + manager: &AssetLockManager, + signer: &WalletSigner, + recipient: Option, + ) -> Result<(DerivationPath, OutPoint), PlatformWalletError> { + manager + .broadcast_funded_asset_lock_tracked( + super::AssetLockBuildAmount::Exact(1_000_000), + &ASSET_LOCK_FUNDING_SOURCES, + 0, + AssetLockFundingType::IdentityTopUpNotBound, + 0, + recipient, + signer, + None, + None, + ) + .await + } + + /// An unbound identity top-up lock is refused before anything is built + /// when it names no identity, names something else, or the backend + /// cannot keep its recipient across a restart: nothing is stored and + /// nothing reaches the broadcaster. + #[tokio::test] + async fn should_refuse_an_unbound_top_up_lock_that_could_not_keep_its_recipient() { + use crate::changeset::AssetLockRecipient; + + let identity = AssetLockRecipient::Identity(dpp::prelude::Identifier::from([0x41; 32])); + for (recipient, records) in [ + (None, true), + (Some(AssetLockRecipient::Shielded([0x42; 43])), true), + (Some(identity), false), + ] { + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: records, + commits_inline: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + + let error = fund_unbound_top_up(&manager, &signer, recipient) + .await + .expect_err("the lock must be refused"); + + if records { + assert!( + matches!(error, PlatformWalletError::InvalidParameter(_)), + "{recipient:?}: {error}" + ); + } else { + assert!( + matches!(&error, PlatformWalletError::Persistence(message) + if message.contains("asset_lock_identity_recipients")), + "{error}" + ); + } + assert!( + persistence.stored.lock().unwrap().is_empty(), + "{recipient:?}" + ); + assert_eq!(broadcaster.calls(), 0, "{recipient:?}"); + } + } + + /// The identity an unbound top-up lock pays is on its row, flushed, + /// before the lock is broadcast; a row that cannot be made durable stops + /// the funding before the broadcaster and leaves the lock untracked. + #[tokio::test] + async fn should_record_the_identity_recipient_with_the_lock_before_dispatch() { + use crate::changeset::AssetLockRecipient; + + let identity = dpp::prelude::Identifier::from([0x43; 32]); + for fail_flush in [false, true] { + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + fail_flush, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + + let result = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(identity)), + ) + .await; + + let stored: Vec<_> = persistence + .stored + .lock() + .unwrap() + .iter() + .filter_map(|cs| cs.asset_locks.as_ref()) + .flat_map(|locks| locks.asset_locks.values().cloned()) + .collect(); + let first = stored.first().expect("the lock's row was stored"); + assert_eq!( + first.funding_type, + AssetLockFundingType::IdentityTopUpNotBound + ); + assert_eq!(first.identity_recipient, Some(identity)); + assert_eq!(first.status, AssetLockStatus::Built); + if fail_flush { + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("identity recipient was not made durable")), + "{:?}", + result.as_ref().err() + ); + assert_eq!(broadcaster.calls(), 0); + assert!(manager.list_tracked_locks().await.is_empty()); + } else { + assert_eq!(broadcaster.calls(), 1); + assert!( + persistence + .flushes + .load(std::sync::atomic::Ordering::SeqCst) + >= 1 + ); + let tracked = manager.list_tracked_locks().await; + assert_eq!(tracked.len(), 1); + assert_eq!(tracked[0].identity_recipient, Some(identity)); + } + } + } + + /// A lock row whose store or flush failed before the broadcast has its + /// removal stored behind it before the inputs are released, so a later + /// flush commits both and the abandoned lock never comes back. On this + /// inline-committing backend the stored removal is durable even when its + /// own flush notification fails. When the + /// store refuses that removal, the row may survive a restart and be + /// re-broadcast after the user's retry, so the inputs stay reserved and + /// the error says so. + #[tokio::test] + async fn should_durably_remove_a_lock_row_that_was_not_made_durable() { + use crate::changeset::AssetLockRecipient; + + let identity = dpp::prelude::Identifier::from([0x57; 32]); + let fund = |persistence: Arc| async move { + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + let result = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(identity)), + ) + .await; + assert_eq!(broadcaster.calls(), 0); + assert!(manager.list_tracked_locks().await.is_empty()); + result.map(|_| ()) + }; + let persistence = || CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }; + + // The row's flush fails: its removal is stored behind it, and the + // inputs are released. + let row_flush_fails = Arc::new(CapturingPersistence { + fail_flush: true, + ..persistence() + }); + let result = fund(Arc::clone(&row_flush_fails)).await; + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("identity recipient was not made durable") + && !message.contains("stay reserved")), + "{result:?}" + ); + assert_eq!(row_flush_fails.removed_outpoints().len(), 1); + + // The store also refuses the removal: the inputs stay reserved. + let result = fund(Arc::new(CapturingPersistence { + fail_flush: true, + fail_remove_store: true, + ..persistence() + })) + .await; + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("stay reserved")), + "{result:?}" + ); + + // The store refuses the row itself, which a host without atomic + // changesets may still have written in part: it is removed the same + // way, and the inputs are released only once that removal is stored. + let row_store_fails = Arc::new(persistence()); + row_store_fails + .fail_lock_store + .store(true, std::sync::atomic::Ordering::SeqCst); + let result = fund(Arc::clone(&row_store_fails)).await; + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if !message.contains("stay reserved")), + "{result:?}" + ); + assert_eq!(row_store_fails.removed_outpoints().len(), 1); + + let both_refused = Arc::new(CapturingPersistence { + fail_remove_store: true, + ..persistence() + }); + both_refused + .fail_lock_store + .store(true, std::sync::atomic::Ordering::SeqCst); + let result = fund(both_refused).await; + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("stay reserved")), + "{result:?}" + ); + } + + /// On a buffered backend, an abandoned row's removal is released only once + /// flushed: another flush may already have committed the row, and a + /// removal left only buffered would be lost with a crash, bringing the + /// lock back resumable while the released inputs funded the retry. When + /// that flush fails the inputs stay reserved and fenced, and the error + /// says so. Nothing reaches the broadcaster either way. + #[tokio::test] + async fn should_keep_inputs_reserved_when_an_abandoned_row_removal_cannot_be_flushed() { + use crate::changeset::AssetLockRecipient; + + let identity = dpp::prelude::Identifier::from([0x5c; 32]); + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: false, + fail_flush: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + + let result = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(identity)), + ) + .await; + + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("identity recipient was not made durable") + && message.contains("stay reserved")), + "{result:?}" + ); + assert_eq!(broadcaster.calls(), 0); + assert!(manager.list_tracked_locks().await.is_empty()); + let removed = persistence.removed_outpoints(); + assert_eq!( + removed.len(), + 1, + "the removal is still stored behind the row" + ); + let tx = stored_lock_transaction(&persistence, &removed[0]); + assert!( + manager.generation.in_broadcast_conflict(&tx).is_some(), + "the inputs stay fenced" + ); + } + + /// Assigns `identity` to the lock at `out_point` through a handle on the + /// wallet's current generation. + async fn assign_on_current_generation( + manager: &AssetLockManager, + out_point: &OutPoint, + identity: dpp::prelude::Identifier, + ) -> Result<(), PlatformWalletError> { + let generation = Arc::clone( + &manager + .wallet_manager + .read() + .await + .get_wallet_info(&manager.wallet_id) + .expect("wallet info") + .generation, + ); + manager + .assign_identity_top_up_recipient(out_point, identity, &generation) + .await + } + + /// An unbound top-up lock that records no recipient (as one rebuilt from + /// the chain does) is unassigned; assigning it an identity records it and + /// stores it. Assigning the same identity again stores it again, another + /// identity is refused, and so is any assignment on a backend that cannot + /// keep it. + #[tokio::test] + async fn should_assign_an_unassigned_unbound_top_up_lock_once() { + use crate::changeset::AssetLockRecipient; + + let built_for = dpp::prelude::Identifier::from([0x51; 32]); + let assigned = dpp::prelude::Identifier::from([0x52; 32]); + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + let (_, out_point) = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(built_for)), + ) + .await + .expect("an unbound top-up lock builds and broadcasts"); + // Forget the recipient, as a lock rebuilt from the chain has none. + { + let mut wm = manager.wallet_manager.write().await; + let lock = wm + .get_wallet_info_mut(&manager.wallet_id) + .unwrap() + .tracked_asset_locks + .get_mut(&out_point) + .unwrap(); + lock.identity_recipient = None; + assert!(lock.is_unassigned_identity_top_up()); + } + let stores_before = persistence.stored.lock().unwrap().len(); + + assign_on_current_generation(&manager, &out_point, assigned) + .await + .expect("an unassigned lock takes the identity the user chose"); + + let tracked = manager.list_tracked_locks().await; + assert_eq!(tracked[0].identity_recipient, Some(assigned)); + assert!(!tracked[0].is_unassigned_identity_top_up()); + { + let stored = persistence.stored.lock().unwrap(); + assert_eq!(stored.len(), stores_before + 1); + let row = &stored[stores_before] + .asset_locks + .as_ref() + .unwrap() + .asset_locks[&out_point]; + assert_eq!(row.identity_recipient, Some(assigned)); + } + + assign_on_current_generation(&manager, &out_point, assigned) + .await + .expect("assigning the recorded identity again succeeds"); + assert_eq!(persistence.stored.lock().unwrap().len(), stores_before + 2); + assert!(matches!( + assign_on_current_generation(&manager, &out_point, built_for) + .await, + Err(PlatformWalletError::AssetLockIdentityRecipientMismatch { + recorded, + requested, + .. + }) if recorded == assigned && requested == built_for + )); + assert!(matches!( + assign_on_current_generation(&manager, &OutPoint::null(), assigned).await, + Err(PlatformWalletError::AssetLockNotTracked(_)) + )); + } + + /// A handle taken before its wallet was removed or re-created under its + /// id assigns nothing on the wallet now under that id: the assignment is + /// refused as a removal, and nothing is recorded or stored. + #[tokio::test] + async fn should_refuse_to_assign_a_recipient_on_a_wallet_since_replaced() { + use crate::changeset::AssetLockRecipient; + + let built_for = dpp::prelude::Identifier::from([0x59; 32]); + let assigned = dpp::prelude::Identifier::from([0x5a; 32]); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::new(CountingOkBroadcaster::default()), + Arc::clone(&persistence), + ) + .await; + let (_, out_point) = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(built_for)), + ) + .await + .expect("an unbound top-up lock builds and broadcasts"); + // The stale handle's generation; the wallet id now names another one, + // which tracks the same lock unassigned (as one restored from the + // store without its recipient would). + let stale = { + let mut wm = manager.wallet_manager.write().await; + let info = wm.get_wallet_info_mut(&manager.wallet_id).unwrap(); + info.tracked_asset_locks + .get_mut(&out_point) + .unwrap() + .identity_recipient = None; + std::mem::replace(&mut info.generation, Arc::new(WalletGeneration::new())) + }; + let stores_before = persistence.stored.lock().unwrap().len(); + + let result = manager + .assign_identity_top_up_recipient(&out_point, assigned, &stale) + .await; + assert!( - err.to_string().contains("below the required minimum"), - "unexpected error for undersized drain: {err}" + matches!(result, Err(PlatformWalletError::WalletRemovedBeforeSend(_))), + "{result:?}" ); assert_eq!( - broadcaster.calls(), - 0, - "an abandoned drain must never reach the broadcaster" - ); - { - let wm = manager.wallet_manager.read().await; - let (_, info) = wm - .get_wallet_and_info(&manager.wallet_id) - .expect("wallet still present"); - assert!( - info.tracked_asset_locks.is_empty(), - "an abandoned drain must not leave a tracked row, got {:?}", - info.tracked_asset_locks - ); - } - assert!( - persistence.removed_outpoints().is_empty(), - "nothing was tracked, so nothing should be queued for removal" + manager.list_tracked_locks().await[0].identity_recipient, + None ); + assert_eq!(persistence.stored.lock().unwrap().len(), stores_before); + } - // The reservation was released through the owner token: a follow-up - // drain over the same single-UTXO CoinJoin account must be able to - // select the inputs immediately and broadcast. - manager - .broadcast_funded_asset_lock_with_funding( - super::AssetLockBuildAmount::DrainAll { - minimum_lock_duffs: Some(1), - }, - &[AccountTypePreference::CoinJoin], - 0, - AssetLockFundingType::AssetLockShieldedAddressTopUp, - 0, + /// A lock recording its recipient was stored durably before the + /// broadcast, so a definite rejection removes its row durably too: a + /// removal left queued could be lost, and the `Built` row would come back + /// after a restart, resumable to the same recipient while its inputs fund + /// the user's next attempt. A removal a buffered backend cannot flush is + /// reported, not swallowed. + #[tokio::test] + async fn should_durably_remove_a_rejected_lock_that_records_its_recipient() { + use crate::changeset::AssetLockRecipient; + + let identity = dpp::prelude::Identifier::from([0x56; 32]); + let fund = |persistence: Arc| async move { + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::new(AlwaysRejectedBroadcaster), + Arc::clone(&persistence), + ) + .await; + fund_unbound_top_up( + &manager, &signer, - None, + Some(AssetLockRecipient::Identity(identity)), ) .await - .expect("follow-up drain must reselect the released inputs"); + .map(|_| ()) + }; + + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }); + let result = fund(Arc::clone(&persistence)).await; + assert!( + !matches!(result, Ok(()) | Err(PlatformWalletError::Persistence(_))), + "{result:?}" + ); + assert_eq!(persistence.removed_outpoints().len(), 1); assert_eq!( - broadcaster.calls(), - 1, - "the follow-up drain should broadcast exactly once" + persistence + .committed_stores + .load(std::sync::atomic::Ordering::SeqCst), + persistence.stored.lock().unwrap().len(), + "the removal was flushed, not left queued" + ); + let flushes = persistence + .flushes + .load(std::sync::atomic::Ordering::SeqCst); + + // A buffered backend whose flush fails may not have committed the + // removal. + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: false, + fail_on_flush: Some(flushes), + ..Default::default() + }); + let result = fund(Arc::clone(&persistence)).await; + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("could not durably remove rejected")), + "{result:?}" ); } - /// The built-lock observer sees the new outpoint exactly once, once the - /// lock is tracked but before its row is stored or anything has reached - /// the broadcaster, and the outpoint it sees is the one the build returns. + /// On a backend whose store commits inline, a rejected lock's removal is + /// durable once stored: a failed flush notification after it must not + /// keep the inputs fenced, since the row is gone and no observed spend + /// could ever clear the fence. The call reports the rejection, and the + /// inputs are free for the next attempt. #[tokio::test] - async fn should_report_the_built_outpoint_before_persisting_or_broadcast() { - let broadcaster = Arc::new(CountingOkBroadcaster::default()); - let (manager, signer, persistence) = - coinjoin_funded_asset_lock_manager(Arc::clone(&broadcaster)).await; - let seen = Mutex::new(Vec::new()); - let observer = |out_point: OutPoint| { - let tracked = manager - .wallet_manager - .try_read() - .expect("the build holds no wallet-manager lock while observing") - .get_wallet_and_info(&manager.wallet_id) - .is_some_and(|(_, info)| info.tracked_asset_locks.contains_key(&out_point)); - let stored = persistence.stored_outpoints().contains(&out_point); - seen.lock() - .unwrap() - .push((out_point, tracked, stored, broadcaster.calls())); - }; + async fn should_release_a_rejected_lock_removed_inline_despite_a_failed_flush() { + use crate::changeset::AssetLockRecipient; - let (_, out_point) = manager - .broadcast_funded_asset_lock_with_funding( - super::AssetLockBuildAmount::DrainAll { - minimum_lock_duffs: Some(1), - }, - &[AccountTypePreference::CoinJoin], - 0, - AssetLockFundingType::AssetLockShieldedAddressTopUp, - 0, - &signer, - Some(&observer), - ) - .await - .expect("drain must broadcast"); + let identity = dpp::prelude::Identifier::from([0x5b; 32]); + // The row's flush is the first; the removal's is the second. + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + fail_on_flush: Some(2), + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::new(AlwaysRejectedBroadcaster), + Arc::clone(&persistence), + ) + .await; + + let result = fund_unbound_top_up( + &manager, + &signer, + Some(AssetLockRecipient::Identity(identity)), + ) + .await; + assert!( + matches!(&result, Err(PlatformWalletError::TransactionBroadcast(_))), + "{result:?}" + ); assert_eq!( - seen.into_inner().unwrap(), - vec![(out_point, true, false, 0)] + persistence + .flushes + .load(std::sync::atomic::Ordering::SeqCst), + 2, + "the removal's flush was attempted and failed" ); - assert_eq!(broadcaster.calls(), 1); - assert!(persistence.stored_outpoints().contains(&out_point)); + let removed = persistence.removed_outpoints(); + assert_eq!(removed.len(), 1); + let tx = stored_lock_transaction(&persistence, &removed[0]); + assert_eq!(manager.generation.in_broadcast_conflict(&tx), None); + assert!(manager.list_tracked_locks().await.is_empty()); } - /// A lock whose broadcast ends without a verdict was reported to the - /// observer, and its row stays tracked and stored, so the caller can - /// resume it by the outpoint it was given. + /// The build-only API tracks nothing, so it builds no unbound top-up + /// lock: one would later be rebuilt from the chain with no recipient. #[tokio::test] - async fn should_keep_a_reported_lock_whose_broadcast_may_have_been_sent() { - let (manager, signer, persistence) = - coinjoin_funded_asset_lock_manager(Arc::new(AlwaysMaybeSentBroadcaster)).await; - let seen = Mutex::new(Vec::new()); - let observer = |out_point: OutPoint| seen.lock().unwrap().push(out_point); - - manager - .broadcast_funded_asset_lock_with_funding( - super::AssetLockBuildAmount::DrainAll { - minimum_lock_duffs: Some(1), - }, - &[AccountTypePreference::CoinJoin], + async fn should_refuse_an_unbound_top_up_lock_from_the_build_only_api() { + let (manager, signer, _persistence) = + funded_asset_lock_manager(Arc::new(CountingOkBroadcaster::default())).await; + let result = manager + .build_asset_lock_transaction( + 1_000_000, 0, - AssetLockFundingType::AssetLockShieldedAddressTopUp, + AssetLockFundingType::IdentityTopUpNotBound, 0, &signer, - Some(&observer), ) - .await - .expect_err("an unconfirmed broadcast must fail the call"); - - let seen = seen.into_inner().unwrap(); - assert_eq!(seen.len(), 1); - assert!(persistence.removed_outpoints().is_empty()); - assert!(persistence.stored_outpoints().contains(&seen[0])); - let wm = manager.wallet_manager.read().await; - let (_, info) = wm - .get_wallet_and_info(&manager.wallet_id) - .expect("wallet still present"); - assert!(info.tracked_asset_locks.contains_key(&seen[0])); + .await; + assert!( + matches!(result, Err(PlatformWalletError::InvalidParameter(_))), + "{result:?}" + ); } - /// A lock whose broadcast is rejected was still reported to the observer, - /// which ran before the broadcast; the call then returns the rejection and - /// the lock's row is removed again. + /// An assignment whose store fails still holds in memory, so a second + /// assignment cannot pick another identity than the one a later flush of + /// the queued row would write; assigning the same identity again retries + /// the store and makes it durable. #[tokio::test] - async fn should_report_a_lock_whose_broadcast_is_then_rejected() { - let (manager, signer, persistence) = - coinjoin_funded_asset_lock_manager(Arc::new(AlwaysRejectedBroadcaster)).await; - let seen = Mutex::new(Vec::new()); - let observer = |out_point: OutPoint| seen.lock().unwrap().push(out_point); + async fn should_keep_a_failed_assignment_so_no_other_identity_can_replace_it() { + use crate::changeset::AssetLockRecipient; - manager - .broadcast_funded_asset_lock_with_funding( - super::AssetLockBuildAmount::DrainAll { - minimum_lock_duffs: Some(1), - }, - &[AccountTypePreference::CoinJoin], + let first = dpp::prelude::Identifier::from([0x54; 32]); + let second = dpp::prelude::Identifier::from([0x55; 32]); + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + let (_, out_point) = + fund_unbound_top_up(&manager, &signer, Some(AssetLockRecipient::Identity(first))) + .await + .expect("an unbound top-up lock builds and broadcasts"); + { + let mut wm = manager.wallet_manager.write().await; + wm.get_wallet_info_mut(&manager.wallet_id) + .unwrap() + .tracked_asset_locks + .get_mut(&out_point) + .unwrap() + .identity_recipient = None; + } + + persistence + .fail_lock_store + .store(true, std::sync::atomic::Ordering::SeqCst); + assert!(matches!( + assign_on_current_generation(&manager, &out_point, first).await, + Err(PlatformWalletError::Persistence(_)) + )); + assert_eq!( + manager.list_tracked_locks().await[0].identity_recipient, + Some(first), + "the failed assignment holds for this session" + ); + assert!(matches!( + assign_on_current_generation(&manager, &out_point, second).await, + Err(PlatformWalletError::AssetLockIdentityRecipientMismatch { + recorded, + requested, + .. + }) if recorded == first && requested == second + )); + + persistence + .fail_lock_store + .store(false, std::sync::atomic::Ordering::SeqCst); + let stores_before = persistence.stored.lock().unwrap().len(); + assign_on_current_generation(&manager, &out_point, first) + .await + .expect("assigning the same identity again retries the store"); + let stored = persistence.stored.lock().unwrap(); + assert_eq!(stored.len(), stores_before + 1); + assert_eq!( + stored[stores_before] + .asset_locks + .as_ref() + .unwrap() + .asset_locks[&out_point] + .identity_recipient, + Some(first) + ); + } + + /// Only an unbound top-up lock takes an assigned recipient, and only on a + /// backend that keeps it. + #[tokio::test] + async fn should_refuse_to_assign_a_recipient_a_lock_cannot_keep() { + let identity = dpp::prelude::Identifier::from([0x53; 32]); + let broadcaster = Arc::new(CountingOkBroadcaster::default()); + let persistence = Arc::new(CapturingPersistence { + records_identity_recipients: true, + commits_inline: true, + ..Default::default() + }); + let (manager, signer) = funded_asset_lock_manager_with_persistence( + Arc::clone(&broadcaster), + Arc::clone(&persistence), + ) + .await; + let (_, out_point) = manager + .broadcast_funded_asset_lock_tracked( + super::AssetLockBuildAmount::Exact(1_000_000), + &ASSET_LOCK_FUNDING_SOURCES, 0, - AssetLockFundingType::AssetLockShieldedAddressTopUp, + AssetLockFundingType::AssetLockAddressTopUp, 0, + None, &signer, - Some(&observer), + None, + None, ) .await - .expect_err("a rejected broadcast must fail the call"); + .expect("an address top-up lock builds and broadcasts"); + assert!(matches!( + assign_on_current_generation(&manager, &out_point, identity).await, + Err(PlatformWalletError::AssetLockFundingMismatch { .. }) + )); - let seen = seen.into_inner().unwrap(); - assert_eq!(seen.len(), 1); - assert_eq!(persistence.removed_outpoints(), seen); + let (manager, _signer) = funded_asset_lock_manager_with_persistence( + Arc::new(CountingOkBroadcaster::default()), + Arc::new(CapturingPersistence::default()), + ) + .await; + assert!(matches!( + assign_on_current_generation(&manager, &out_point, identity).await, + Err(PlatformWalletError::Persistence(_)) + )); } /// The funding resolver every fund-from-asset-lock flow calls hands the @@ -2734,7 +3955,7 @@ mod tests { broadcaster: Arc, persistence: Arc

, ) -> (Arc>, WalletSigner) { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); @@ -2745,6 +3966,7 @@ mod tests { Arc::new(Notify::new()), broadcaster, WalletPersister::new(wallet_id, persistence as Arc), + Arc::clone(&generation), )); (manager, signer) @@ -2968,7 +4190,7 @@ mod tests { /// Only the unknown outcome describes what actually happened. #[tokio::test] async fn rejected_broadcast_racing_concurrent_resume_keeps_row_and_reservation() { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let broadcaster = Arc::new(RejectAfterConcurrentResumeBroadcaster { @@ -2987,6 +4209,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + Arc::clone(&generation), )); let result = manager @@ -3083,7 +4306,7 @@ mod tests { /// that a concurrent resume already advanced beyond `Built`. #[tokio::test] async fn create_broadcast_does_not_downgrade_a_concurrently_finalized_row() { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let broadcaster = Arc::new(FinalizeDuringCreateBroadcast { wallet_manager: Arc::clone(&wallet_manager), @@ -3101,6 +4324,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + Arc::clone(&generation), ); let (_path, out_point) = manager @@ -3213,7 +4437,7 @@ mod tests { async fn concurrent_invitation_builds_cannot_roll_back_the_used_index_snapshot() { use key_wallet::account::AccountType; - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = crate::test_support::funded_wallet_manager_with_outputs( StandardAccountType::BIP44Account, &[10_000_000, 10_000_000], @@ -3238,6 +4462,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + Arc::clone(&generation), )); let manager_a = Arc::clone(&manager); @@ -3592,6 +4817,7 @@ mod tests { ) -> (Arc>, Arc) { let persistence = Arc::new(CapturingPersistence::for_wallet(&wallet_manager, wallet_id)); let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); + let generation = crate::test_support::wallet_generation(&wallet_manager, &wallet_id); let manager = Arc::new(AssetLockManager::new( sdk, wallet_manager, @@ -3602,6 +4828,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + generation, )); (manager, persistence) } @@ -4538,7 +5765,7 @@ mod tests { #[tokio::test] async fn should_wallet_drain_refuse_missing_durable_wallet_snapshot() { - let (wallet_manager, wallet_id, _, _) = + let (wallet_manager, wallet_id, generation, _) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let broadcaster = Arc::new(CountingOkBroadcaster::default()); let manager = AssetLockManager::new( @@ -4556,6 +5783,7 @@ mod tests { ..Default::default() }), ), + Arc::clone(&generation), ); // A globally successful load that omits this wallet must never be // interpreted as a definitive NotSent for an old persisted host UUID. @@ -5152,7 +6380,11 @@ mod tests { Some(outpoint) ); assert_eq!( - manager.tracked_resume_metadata(&outpoint).await.unwrap().0, + manager + .tracked_resume_metadata(&outpoint) + .await + .unwrap() + .funding_type, AssetLockFundingType::AssetLockShieldedAddressTopUp ); let result = manager @@ -5193,7 +6425,7 @@ mod tests { } async fn assert_wallet_drain_pool_failure_can_retry(fail_store: bool) { - let (wallet_manager, wallet_id, _, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager_dual_standard(&[700_000, 900_000], &[800_000]).await; let persistence = Arc::new(CapturingPersistence { fail_next_pool_store: std::sync::atomic::AtomicBool::new(fail_store), @@ -5208,6 +6440,7 @@ mod tests { Arc::new(Notify::new()), broadcaster.clone(), WalletPersister::new(wallet_id, persistence.clone()), + Arc::clone(&generation), ); let operation = Arc::new(super::AssetLockOperationContext::new([41; 16])); let registration = manager.register_wallet_drain_operation(operation.clone()); @@ -5411,7 +6644,7 @@ mod tests { for fail_remove_store in [false, true] { { let commits_inline = true; - let (wallet_manager, wallet_id, _, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(CapturingPersistence { commits_inline, @@ -5427,6 +6660,7 @@ mod tests { Arc::new(Notify::new()), Arc::new(AlwaysRejectedBroadcaster), WalletPersister::new(wallet_id, persistence.clone()), + Arc::clone(&generation), ); let operation = Arc::new(super::AssetLockOperationContext::new([53; 16])); let registration = manager.register_wallet_drain_operation(operation.clone()); @@ -5509,7 +6743,7 @@ mod tests { #[cfg(feature = "shielded")] #[tokio::test] async fn should_report_a_wallet_drain_lock_before_its_row_is_stored() { - let (wallet_manager, wallet_id, _, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(CapturingPersistence { commits_inline: true, @@ -5525,6 +6759,7 @@ mod tests { Arc::new(Notify::new()), broadcaster.clone(), WalletPersister::new(wallet_id, persistence.clone()), + Arc::clone(&generation), ); let operation = Arc::new(super::AssetLockOperationContext::new([58; 16])); let registration = manager.register_wallet_drain_operation(operation.clone()); @@ -5600,7 +6835,7 @@ mod tests { #[tokio::test] async fn should_retry_rolled_back_drain_checkpoint_without_rebuilding() { { - let (wallet_manager, wallet_id, _, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(CapturingPersistence { commits_inline: true, @@ -5616,6 +6851,7 @@ mod tests { Arc::new(Notify::new()), broadcaster.clone(), WalletPersister::new(wallet_id, persistence.clone()), + Arc::clone(&generation), ); let operation = Arc::new(super::AssetLockOperationContext::new([56; 16])); let registration = manager.register_wallet_drain_operation(operation.clone()); @@ -5742,7 +6978,7 @@ mod tests { #[tokio::test] async fn should_wallet_drain_failed_row_flush_never_publish_resumable_lock() { - let (wallet_manager, wallet_id, _, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(CapturingPersistence { fail_on_flush: Some(2), @@ -5757,6 +6993,7 @@ mod tests { Arc::new(Notify::new()), broadcaster.clone(), WalletPersister::new(wallet_id, persistence.clone()), + Arc::clone(&generation), ); let operation = Arc::new(super::AssetLockOperationContext::new([61; 16])); let _registration = manager.register_wallet_drain_operation(operation.clone()); @@ -5842,7 +7079,7 @@ mod tests { #[tokio::test] async fn should_wallet_drain_panic_keep_exact_outpoint_and_pending_status() { - let (wallet_manager, wallet_id, _, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(CapturingPersistence::for_wallet(&wallet_manager, wallet_id)); let manager = Arc::new(AssetLockManager::new( @@ -5854,6 +7091,7 @@ mod tests { persistence: persistence.clone(), }), WalletPersister::new(wallet_id, persistence), + Arc::clone(&generation), )); let operation = Arc::new(super::AssetLockOperationContext::new([71; 16])); let _registration = manager.register_wallet_drain_operation(operation.clone()); diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/manager.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/manager.rs index 52f473021a9..321fdd64c7e 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/manager.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/manager.rs @@ -12,6 +12,7 @@ use tokio::sync::{Notify, RwLock}; use crate::broadcaster::TransactionBroadcaster; use crate::changeset::changeset::AssetLockChangeSet; +use crate::wallet::core::WalletGeneration; use crate::wallet::persister::WalletPersister; use crate::wallet::platform_wallet::{PlatformWalletInfo, WalletId}; @@ -36,6 +37,13 @@ pub struct AssetLockManager { pub(super) wallet_manager: Arc>>, /// Identifies which wallet within the manager this manager operates on. pub(super) wallet_id: WalletId, + /// The wallet generation this manager was created for. A wallet removed + /// and re-created under `wallet_id` gets a new generation and a new + /// manager, so a handle that outlived its registration would otherwise + /// build from the replacement's wallet info and spend its funds: a build + /// on any other generation is refused before anything is reserved (see + /// `build_asset_lock_transaction_fenced`). + pub(super) generation: Arc, /// Notified on InstantLock / ChainLock events by `LockNotifyHandler`. /// Used by `wait_for_proof()` and `wait_for_chain_lock()`. pub(super) lock_notify: Arc, @@ -158,11 +166,13 @@ impl AssetLockManager { lock_notify: Arc, broadcaster: Arc, persister: WalletPersister, + generation: Arc, ) -> Self { Self { sdk, wallet_manager, wallet_id, + generation, lock_notify, broadcaster, persister, @@ -199,6 +209,7 @@ impl AssetLockManager { sdk: Arc::clone(&self.sdk), wallet_manager: Arc::clone(&self.wallet_manager), wallet_id: self.wallet_id, + generation: Arc::clone(&self.generation), lock_notify: Arc::clone(&self.lock_notify), broadcaster: Arc::clone(&self.broadcaster), persister: self.persister.clone(), diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs index ab401c35572..38d0d7a7d4b 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs @@ -34,9 +34,9 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; -use crate::changeset::ShieldedRecipientRaw; +use crate::changeset::AssetLockRecipient; use dashcore::OutPoint; -use dpp::prelude::AssetLockProof; +use dpp::prelude::{AssetLockProof, Identifier}; use key_wallet::bip32::DerivationPath; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -48,6 +48,7 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use crate::broadcaster::TransactionBroadcaster; use crate::error::{is_asset_lock_already_consumed, PlatformWalletError}; use crate::wallet::asset_lock::manager::AssetLockManager; +use crate::wallet::asset_lock::sync::tracking::TrackedResumeMetadata; use crate::wallet::asset_lock::AssetLockOperationContext; use super::build::{AssetLockBuildAmount, AssetLockBuiltObserver}; @@ -506,6 +507,13 @@ impl AssetLockManager { /// `find_tracked_unproven_lock` BTreeMap walk needed), so the /// `IsTimeout` outcome is built directly from the error payload. /// + /// `recipient` is who the operation pays. A newly built lock records it + /// when its funding type does (a shielded funding, an unbound identity + /// top-up). For an existing unbound top-up lock it must be the identity + /// the lock recorded: a different one is refused with + /// [`PlatformWalletError::AssetLockIdentityRecipientMismatch`], and a lock + /// that records none with [`PlatformWalletError::AssetLockRecipientUnknown`]. + /// /// `on_built` receives the outpoint of a newly built lock; see /// [`AssetLockBuiltObserver`]. pub(crate) async fn resolve_funding_with_is_timeout_fallback( @@ -513,7 +521,7 @@ impl AssetLockManager { funding: AssetLockFunding, funding_type: AssetLockFundingType, destination_index: u32, - shielded_recipient: Option, + recipient: Option, asset_lock_signer: &AS, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result @@ -531,7 +539,7 @@ impl AssetLockManager { account_index, funding_type, destination_index, - shielded_recipient, + recipient, asset_lock_signer, on_built, ) @@ -570,7 +578,7 @@ impl AssetLockManager { minimum_lock_duffs, funding_type, destination_index, - shielded_recipient, + recipient, asset_lock_signer, &operation, on_built, @@ -602,7 +610,7 @@ impl AssetLockManager { account, funding_type, destination_index, - shielded_recipient, + recipient, asset_lock_signer, on_built, ) @@ -625,7 +633,12 @@ impl AssetLockManager { out_point, consume_invitation_voucher, } => { - let (actual_funding_type, actual_identity_index, status) = self + let TrackedResumeMetadata { + funding_type: actual_funding_type, + identity_index: actual_identity_index, + status, + identity_recipient: recorded_identity, + } = self .tracked_resume_metadata(&out_point) .await .ok_or(PlatformWalletError::AssetLockNotTracked(out_point))?; @@ -644,12 +657,18 @@ impl AssetLockManager { consume_invitation_voucher, ); if !invitation_reclaim { + let requested_identity = match recipient { + Some(AssetLockRecipient::Identity(identity)) => Some(identity), + _ => None, + }; validate_existing_asset_lock_role( out_point, funding_type, destination_index, + requested_identity, actual_funding_type, actual_identity_index, + recorded_identity, )?; } // 300s is a window for the record or a mined-height lookup to @@ -698,15 +717,22 @@ fn authorized_invitation_reclaim( /// Authorize a tracked one-shot output for the operation that is about to /// consume it. Identity registration and bound top-up paths must match their -/// identity index; an unbound top-up is deliberately eligible for any target. -/// Invitation vouchers never pass this generic validator—the explicit reclaim -/// authorization above is the only bypass. +/// identity index. An unbound top-up may serve a top-up, but only of the +/// identity its row recorded (`recorded_identity`): another identity is +/// [`PlatformWalletError::AssetLockIdentityRecipientMismatch`], and a lock that +/// records none (rebuilt from the chain, its credit output naming no identity) +/// is [`PlatformWalletError::AssetLockRecipientUnknown`] until a recipient is +/// assigned. Invitation vouchers never pass this generic validator—the +/// explicit reclaim authorization above is the only bypass. +#[allow(clippy::too_many_arguments)] fn validate_existing_asset_lock_role( out_point: OutPoint, expected_funding_type: AssetLockFundingType, expected_identity_index: u32, + requested_identity: Option, actual_funding_type: AssetLockFundingType, actual_identity_index: u32, + recorded_identity: Option, ) -> Result<(), PlatformWalletError> { let eligible = match expected_funding_type { AssetLockFundingType::IdentityRegistration => { @@ -720,16 +746,31 @@ fn validate_existing_asset_lock_role( } _ => actual_funding_type == expected_funding_type, }; - if eligible { - Ok(()) - } else { - Err(PlatformWalletError::AssetLockFundingMismatch { - out_point, - expected_funding_type, - expected_identity_index, - actual_funding_type, - actual_identity_index, - }) + let mismatch = PlatformWalletError::AssetLockFundingMismatch { + out_point, + expected_funding_type, + expected_identity_index, + actual_funding_type, + actual_identity_index, + }; + if !eligible { + return Err(mismatch); + } + if actual_funding_type != AssetLockFundingType::IdentityTopUpNotBound { + return Ok(()); + } + match (recorded_identity, requested_identity) { + (None, _) => Err(PlatformWalletError::AssetLockRecipientUnknown(out_point)), + (Some(recorded), Some(requested)) if recorded == requested => Ok(()), + (Some(recorded), Some(requested)) => { + Err(PlatformWalletError::AssetLockIdentityRecipientMismatch { + out_point, + recorded, + requested, + }) + } + // An operation that names no identity cannot pay the one recorded. + (Some(_), None) => Err(mismatch), } } @@ -744,9 +785,19 @@ mod tests { #[test] fn existing_lock_role_validation_binds_identity_funding() { let out_point = OutPoint::null(); + let validate = |expected, expected_index, actual, actual_index| { + validate_existing_asset_lock_role( + out_point, + expected, + expected_index, + None, + actual, + actual_index, + None, + ) + }; - assert!(validate_existing_asset_lock_role( - out_point, + assert!(validate( AssetLockFundingType::IdentityRegistration, 7, AssetLockFundingType::IdentityRegistration, @@ -754,22 +805,19 @@ mod tests { ) .is_ok()); for error in [ - validate_existing_asset_lock_role( - out_point, + validate( AssetLockFundingType::IdentityRegistration, 7, AssetLockFundingType::IdentityRegistration, 8, ), - validate_existing_asset_lock_role( - out_point, + validate( AssetLockFundingType::IdentityRegistration, 7, AssetLockFundingType::IdentityTopUp, 7, ), - validate_existing_asset_lock_role( - out_point, + validate( AssetLockFundingType::IdentityRegistration, 0, AssetLockFundingType::IdentityInvitation, @@ -782,25 +830,15 @@ mod tests { )); } - assert!(validate_existing_asset_lock_role( - out_point, + assert!(validate( AssetLockFundingType::IdentityTopUp, 11, AssetLockFundingType::IdentityTopUp, 11, ) .is_ok()); - assert!(validate_existing_asset_lock_role( - out_point, - AssetLockFundingType::IdentityTopUp, - 11, - AssetLockFundingType::IdentityTopUpNotBound, - 999, - ) - .is_ok()); assert!(matches!( - validate_existing_asset_lock_role( - out_point, + validate( AssetLockFundingType::IdentityTopUp, 11, AssetLockFundingType::IdentityTopUp, @@ -810,6 +848,66 @@ mod tests { )); } + #[test] + fn should_resume_an_unbound_top_up_lock_only_to_the_identity_it_recorded() { + let out_point = OutPoint::null(); + let recorded = Identifier::from([0x21; 32]); + let other = Identifier::from([0x22; 32]); + let validate = |expected, requested, recorded| { + validate_existing_asset_lock_role( + out_point, + expected, + 11, + requested, + AssetLockFundingType::IdentityTopUpNotBound, + 999, + recorded, + ) + }; + + // The recorded identity, through the managed or the unbound route. + for expected in [ + AssetLockFundingType::IdentityTopUp, + AssetLockFundingType::IdentityTopUpNotBound, + ] { + assert!(validate(expected, Some(recorded), Some(recorded)).is_ok()); + } + // Any other identity, the holder's own included, is refused. + assert!(matches!( + validate(AssetLockFundingType::IdentityTopUp, Some(other), Some(recorded)), + Err(PlatformWalletError::AssetLockIdentityRecipientMismatch { + out_point: o, + recorded: r, + requested: q, + }) if o == out_point && r == recorded && q == other + )); + // A lock that records no identity pays nobody until one is assigned. + for requested in [Some(other), None] { + assert!(matches!( + validate(AssetLockFundingType::IdentityTopUp, requested, None), + Err(PlatformWalletError::AssetLockRecipientUnknown(o)) if o == out_point + )); + } + // An operation that names no identity cannot pay the recorded one. + assert!(matches!( + validate( + AssetLockFundingType::IdentityTopUpNotBound, + None, + Some(recorded) + ), + Err(PlatformWalletError::AssetLockFundingMismatch { .. }) + )); + // Not a top-up operation at all. + assert!(matches!( + validate( + AssetLockFundingType::IdentityRegistration, + Some(recorded), + Some(recorded) + ), + Err(PlatformWalletError::AssetLockFundingMismatch { .. }) + )); + } + #[test] fn explicit_invitation_reclaim_allows_registration_and_topup_only() { for expected in [ @@ -892,6 +990,7 @@ mod tests { transaction: dashcore::Transaction, out_point: OutPoint, instant_proof: AssetLockProof, + signer: crate::test_support::WalletSigner, } async fn instant_reconciliation_context() -> InstantReconciliationContext { @@ -935,7 +1034,7 @@ mod tests { use key_wallet::account::account_type::StandardAccountType; use tokio::sync::Notify; - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -950,6 +1049,7 @@ mod tests { Arc::new(Notify::new()), Arc::new(AlwaysRejectedBroadcaster), WalletPersister::new(wallet_id, persistence), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -980,6 +1080,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: transaction.clone(), account_index: 0, @@ -999,9 +1100,74 @@ mod tests { transaction, out_point, instant_proof, + signer, } } + /// Re-track the fixture's lock as an unbound top-up recording + /// `recorded` (or nothing). + async fn track_as_unbound_top_up( + ctx: &InstantReconciliationContext, + recorded: Option, + ) { + let mut wm = ctx.wallet_manager.write().await; + let lock = wm + .get_wallet_info_mut(&ctx.wallet_id) + .expect("wallet must remain registered") + .tracked_asset_locks + .get_mut(&ctx.out_point) + .expect("fixture lock is tracked"); + lock.funding_type = AssetLockFundingType::IdentityTopUpNotBound; + lock.identity_recipient = recorded; + } + + /// The managed top-up's resume of an existing unbound lock goes through + /// the recorded recipient: another identity and a lock that records none + /// are refused before any proof is awaited, and the lock stays tracked + /// and unconsumed for the right resume. + #[tokio::test] + async fn should_refuse_to_resume_an_unbound_top_up_lock_to_another_identity() { + let ctx = instant_reconciliation_context().await; + let recorded = Identifier::from([0x31; 32]); + let holder = Identifier::from([0x32; 32]); + let resolve = |identity| { + ctx.manager.resolve_funding_with_is_timeout_fallback( + AssetLockFunding::FromExistingAssetLock { + out_point: ctx.out_point, + consume_invitation_voucher: false, + }, + AssetLockFundingType::IdentityTopUp, + 0, + Some(AssetLockRecipient::Identity(identity)), + &ctx.signer, + None, + ) + }; + + track_as_unbound_top_up(&ctx, Some(recorded)).await; + assert!(matches!( + resolve(holder).await, + Err(PlatformWalletError::AssetLockIdentityRecipientMismatch { + recorded: r, + requested: q, + .. + }) if r == recorded && q == holder + )); + + track_as_unbound_top_up(&ctx, None).await; + assert!(matches!( + resolve(holder).await, + Err(PlatformWalletError::AssetLockRecipientUnknown(o)) if o == ctx.out_point + )); + + let wm = ctx.wallet_manager.read().await; + let lock = &wm + .get_wallet_info(&ctx.wallet_id) + .unwrap() + .tracked_asset_locks[&ctx.out_point]; + assert_eq!(lock.status, AssetLockStatus::InstantSendLocked); + } + /// The unauthenticated code-24 consensus response that puts /// `reconcile_asset_lock_submit_result` on the reconciliation path. fn already_consumed_error(out_point: OutPoint) -> dash_sdk::Error { diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/mod.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/mod.rs index 94fcee27550..8e58b9e12a1 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/mod.rs @@ -8,4 +8,4 @@ pub(crate) mod locate; mod proof; pub(crate) mod reconstruction; pub(crate) mod recovery; -mod tracking; +pub(crate) mod tracking; diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs index fa6c92ff20c..9e045c06642 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs @@ -2229,6 +2229,7 @@ mod chain_lock_wait_tests { Arc::clone(¬ify), Arc::new(AlwaysRejectedBroadcaster), WalletPersister::new(wallet_id, persister(&record)), + crate::test_support::wallet_generation(&wallet_manager, &wallet_id), ); if let Some(locator) = locator { manager = manager.with_mined_height_locator(locator); @@ -2243,6 +2244,7 @@ mod chain_lock_wait_tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -2291,7 +2293,7 @@ mod chain_lock_wait_tests { proof: Option, locator: Option>, ) -> OkCtx { - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -2306,6 +2308,7 @@ mod chain_lock_wait_tests { Arc::new(Notify::new()), Arc::new(AlwaysOkBroadcaster), WalletPersister::new(wallet_id, Arc::new(NoopTestPersister)), + Arc::clone(&generation), ); if let Some(locator) = locator { manager = manager.with_mined_height_locator(locator); @@ -2348,6 +2351,7 @@ mod chain_lock_wait_tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs index 5e6eadfb761..b806de81df0 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs @@ -233,6 +233,7 @@ fn reconstruct_candidates( Some(TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: record.transaction.clone(), account_index, @@ -575,7 +576,7 @@ mod tests { WalletId, Transaction, ) { - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -593,6 +594,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + Arc::clone(&generation), ); let (tx, _path) = manager .build_asset_lock_transaction(1_000_000, 0, funding_type, identity_index, &signer) @@ -768,6 +770,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: tx.clone(), account_index: 0, @@ -1005,6 +1008,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: tx.clone(), account_index: 0, @@ -1151,6 +1155,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + crate::test_support::wallet_generation(&wallet_manager, &wallet_id), ); let out_point = OutPoint::new(tx.txid(), 0); let (proof, _path) = manager @@ -1236,6 +1241,7 @@ mod tests { wallet_id, Arc::new(NoopTestPersister) as Arc, ), + crate::test_support::wallet_generation(&wallet_manager, &wallet_id), ); let live_proof = dpp::prelude::AssetLockProof::Chain(chain_proof(78, out_point)); manager diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs index 922a47968b7..3448bfc43c8 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs @@ -109,6 +109,7 @@ impl AssetLockManager { let lock = TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: tx, account_index, @@ -2187,7 +2188,7 @@ mod tests { #[tokio::test] async fn built_resume_rebroadcasts_original_and_typed_failures_do_not_broadcast() { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(RecordingPersistence::default()); let broadcaster = Arc::new(RecordingBroadcaster::default()); @@ -2204,6 +2205,7 @@ mod tests { Arc::new(Notify::new()), Arc::clone(&broadcaster), WalletPersister::new(wallet_id, persistence), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -2226,6 +2228,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: transaction.clone(), account_index: 0, @@ -2326,7 +2329,7 @@ mod tests { AssetLockManager, WalletSigner, ) { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -2341,6 +2344,7 @@ mod tests { Arc::new(Notify::new()), broadcaster, WalletPersister::new(wallet_id, Arc::new(RecordingPersistence::default())), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -2363,6 +2367,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -2497,7 +2502,7 @@ mod tests { // --- Session 1: build a top-up asset lock. This lazily creates // the IdentityTopUp{7} account and must persist its registration. - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(RecordingPersistence::default()); // The mock SDK network must match the testnet wallet fixture: @@ -2519,6 +2524,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + Arc::clone(&generation), ); let (tx, path) = manager .build_asset_lock_transaction( @@ -2589,6 +2595,7 @@ mod tests { let lock = TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction: tx, account_index: 0, @@ -2602,6 +2609,7 @@ mod tests { .tracked_asset_locks .insert(out_point, lock.clone()); + let generation = Arc::clone(&restored_info.generation); let mut wm = WalletManager::::new(Network::Testnet); let restored_id = wm .insert_wallet(restored_wallet, restored_info) @@ -2618,6 +2626,7 @@ mod tests { Arc::new(Notify::new()), Arc::new(AlwaysRejectedBroadcaster), WalletPersister::new(wallet_id, persistence as Arc), + generation, ); // Re-derive under a held read guard while a writer is queued behind // it — the shape `resume_asset_lock` step 4 runs in. tokio's @@ -2783,7 +2792,7 @@ mod tests { WalletId, ) -> Arc, ) -> Self { - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let broadcaster = Arc::new(broadcaster); let sdk = Arc::new( @@ -2803,6 +2812,7 @@ mod tests { wallet_id, persistence(Arc::clone(&wallet_manager), wallet_id), ), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -2867,6 +2877,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point: self.out_point, transaction: self.transaction.clone(), account_index: 0, @@ -4342,7 +4353,7 @@ mod tests { broadcaster: Arc, status: AssetLockStatus, ) -> TrackedLockFixture { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -4357,6 +4368,7 @@ mod tests { Arc::new(Notify::new()), broadcaster, WalletPersister::new(wallet_id, Arc::new(RecordingPersistence::default())), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -4379,6 +4391,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -4834,7 +4847,7 @@ mod tests { }; use key_wallet::transaction_checking::{TransactionContext, TransactionType}; - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -4849,6 +4862,7 @@ mod tests { Arc::new(Notify::new()), Arc::new(AlwaysRejectedBroadcaster), WalletPersister::new(wallet_id, Arc::new(RecordingPersistence::default())), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -4894,6 +4908,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -4957,7 +4972,7 @@ mod tests { }; use key_wallet::transaction_checking::{TransactionContext, TransactionType}; - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -4974,6 +4989,7 @@ mod tests { Arc::new(Notify::new()), Arc::clone(&broadcaster) as Arc, WalletPersister::new(wallet_id, Arc::clone(&persistence) as Arc<_>), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -5019,6 +5035,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -5492,6 +5509,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + crate::test_support::wallet_generation(&wallet_manager, &wallet_id), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -5523,6 +5541,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -5570,7 +5589,7 @@ mod tests { /// outcome whose contract says the row and reservation still exist. #[tokio::test(start_paused = true)] async fn offline_broadcast_resume_preserves_wallet_removal_during_refresh() { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(InterleavedPersistence::new( Arc::clone(&wallet_manager), @@ -5599,6 +5618,7 @@ mod tests { wallet_id, Arc::clone(&persistence) as Arc, ), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -5629,6 +5649,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -5851,7 +5872,7 @@ mod tests { ) { use dashcore::ephemerealdata::instant_lock::InstantLock; - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -5867,6 +5888,7 @@ mod tests { Arc::new(Notify::new()), Arc::clone(&broadcaster) as Arc, WalletPersister::new(wallet_id, Arc::new(RecordingPersistence::default())), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -5909,6 +5931,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -6008,7 +6031,7 @@ mod tests { /// thing standing between an already-final lock and a resume that fails /// it every launch. async fn finality_landing_in_the_transport_wait_completes_the_resume(status: AssetLockStatus) { - let (wallet_manager, wallet_id, _balance, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -6029,6 +6052,7 @@ mod tests { Arc::new(Notify::new()), Arc::clone(&broadcaster) as Arc, WalletPersister::new(wallet_id, Arc::new(RecordingPersistence::default())), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -6055,6 +6079,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, @@ -6207,7 +6232,7 @@ mod tests { impl SmallCoinRow { async fn tracked(coins: usize, amount_duffs: u64, status: AssetLockStatus) -> Self { - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = crate::test_support::funded_wallet_manager_with_outputs( StandardAccountType::BIP44Account, &vec![10_000; coins], @@ -6228,6 +6253,7 @@ mod tests { Arc::new(Notify::new()), Arc::clone(&broadcaster), WalletPersister::new(wallet_id, Arc::clone(&persistence) as Arc<_>), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -6258,6 +6284,7 @@ mod tests { status, proof: None, shielded_recipient: None, + identity_recipient: None, }, ); } diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs index 7d55bd91ebb..05d93397901 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs @@ -3,11 +3,15 @@ use crate::broadcaster::TransactionBroadcaster; use dashcore::OutPoint; use std::collections::BTreeMap; +use std::sync::Arc; use crate::changeset::changeset::AssetLockChangeSet; -use crate::changeset::changeset::PlatformWalletChangeSet; +use crate::changeset::changeset::{AssetLockEntry, PlatformWalletChangeSet}; use crate::changeset::PersistenceCapabilities; use crate::error::PlatformWalletError; +use crate::wallet::core::WalletGeneration; +use dpp::prelude::Identifier; +use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use super::super::manager::AssetLockManager; use super::super::tracked::{AssetLockStatus, TrackedAssetLock}; @@ -94,31 +98,30 @@ impl AssetLockManager { } /// Whether active or sticky resume state excludes rejected-build cleanup. - fn resume_cleanup_excluded(&self, out_point: &OutPoint) -> bool { + pub(crate) fn resume_cleanup_excluded(&self, out_point: &OutPoint) -> bool { self.resume_dispatch_claims .lock() .unwrap_or_else(|e| e.into_inner()) .contains_key(out_point) } - /// Snapshot the funding role, bound index and status used to authorize an - /// existing-lock resume. Taking all three under one read lock avoids a - /// role/status time-of-check/time-of-use split in the resolver. - /// - /// [`AssetLockFundingType`]: - /// key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType + /// Snapshot the funding role, bound index, status and recorded identity + /// used to authorize an existing-lock resume. Taking them under one read + /// lock avoids a role/status time-of-check/time-of-use split in the + /// resolver. pub(crate) async fn tracked_resume_metadata( &self, out_point: &OutPoint, - ) -> Option<( - key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType, - u32, - AssetLockStatus, - )> { + ) -> Option { let wm = self.wallet_manager.read().await; wm.get_wallet_info(&self.wallet_id) .and_then(|info| info.tracked_asset_locks.get(out_point)) - .map(|lock| (lock.funding_type, lock.identity_index, lock.status.clone())) + .map(|lock| TrackedResumeMetadata { + funding_type: lock.funding_type, + identity_index: lock.identity_index, + status: lock.status.clone(), + identity_recipient: lock.identity_recipient, + }) } /// The wallet-drain operation a tracked lock belongs to, if any. @@ -143,14 +146,97 @@ impl AssetLockManager { .and_then(|lock| lock.shielded_recipient) } + /// Assign the identity an unbound identity top-up lock pays, for a lock + /// that records none (see [`TrackedAssetLock::is_unassigned_identity_top_up`]): + /// one rebuilt from the chain after a restore, whose credit output names + /// no identity. The user chooses the identity; afterwards a resume pays it + /// and refuses any other, exactly as for a lock built with a recipient. + /// Callers outside the crate go through + /// `IdentityWallet::assign_identity_top_up_recipient`, which first checks + /// that Platform knows the identity. + /// + /// Refused on a backend that cannot keep the assignment + /// ([`PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS`]). The + /// identity is recorded in memory first and then stored and flushed, so + /// memory always holds what a failed flush leaves queued for the next + /// one: a later assignment of another identity is + /// [`PlatformWalletError::AssetLockIdentityRecipientMismatch`] rather than + /// a change the store would drop. If the store fails, the error is + /// returned and the assignment holds for this session; assigning the + /// same identity again stores it again, so a retry makes it durable. + /// Only an unbound top-up lock that is not consumed can be assigned. + /// + /// `generation` is the caller's handle's wallet generation. A wallet + /// removed, or re-created under its id, since the handle was taken is + /// refused with [`PlatformWalletError::WalletRemovedBeforeSend`] and + /// nothing is assigned or stored. + pub(crate) async fn assign_identity_top_up_recipient( + &self, + out_point: &OutPoint, + identity: Identifier, + generation: &Arc, + ) -> Result<(), PlatformWalletError> { + self.require_identity_recipient_persistence()?; + // The caller may have awaited a Platform lookup since it took its + // handle, and a replacement generation can track a lock at the same + // outpoint (one it restored from the store): assigning there would make + // a later resume pay this caller's identity from the replacement's + // lock. The generation's lifecycle gate is held from the check through + // the store, taken before the manager lock as teardown takes them, so + // a removal cannot land between them. + let _lifecycle = generation.payment_guard().await; + let entry = { + let mut wm = self.wallet_manager.write().await; + let lock = wm + .get_wallet_info_mut(&self.wallet_id) + .filter(|info| Arc::ptr_eq(&info.generation, generation)) + .ok_or_else(|| { + PlatformWalletError::WalletRemovedBeforeSend(hex::encode(self.wallet_id)) + })? + .tracked_asset_locks + .get_mut(out_point) + .ok_or(PlatformWalletError::AssetLockNotTracked(*out_point))?; + check_identity_recipient_assignable(lock, identity)?; + lock.identity_recipient = Some(identity); + AssetLockEntry::from(&*lock) + }; + self.persister + .store(PlatformWalletChangeSet { + asset_locks: Some(AssetLockChangeSet { + asset_locks: [(*out_point, entry)].into(), + ..Default::default() + }), + ..Default::default() + }) + .and_then(|()| self.persister.flush()) + .map_err(|error| { + PlatformWalletError::Persistence(format!( + "asset-lock identity recipient was not made durable: {error}" + )) + }) + } + /// Track a new asset lock in memory, returning a changeset describing /// the inserted entry. /// /// If an entry already exists at `out_point`, it is overwritten. - pub(crate) async fn track_asset_lock(&self, lock: TrackedAssetLock) -> AssetLockChangeSet { + /// + /// Only on `generation`, the one the lock was built on: the build awaits + /// between its build and this insert, and a wallet re-created under the + /// same id in that window must not be handed a lock it never built — it + /// could resume it while the build reports the removal. On any other + /// generation nothing is inserted and the changeset is empty. + pub(crate) async fn track_asset_lock( + &self, + lock: TrackedAssetLock, + generation: &Arc, + ) -> AssetLockChangeSet { let mut wm = self.wallet_manager.write().await; let mut cs = AssetLockChangeSet::default(); - if let Some(info) = wm.get_wallet_info_mut(&self.wallet_id) { + if let Some(info) = wm + .get_wallet_info_mut(&self.wallet_id) + .filter(|info| Arc::ptr_eq(&info.generation, generation)) + { let out_point = lock.out_point; cs.asset_locks.insert(out_point, (&lock).into()); info.tracked_asset_locks.insert(out_point, lock); @@ -715,3 +801,59 @@ impl AssetLockManager { } } } + +/// Whether `lock` may be assigned `identity` as its recipient: an unconsumed +/// unbound top-up lock recording no identity, or this one already. +fn check_identity_recipient_assignable( + lock: &TrackedAssetLock, + identity: Identifier, +) -> Result<(), PlatformWalletError> { + if lock.funding_type != AssetLockFundingType::IdentityTopUpNotBound { + return Err(not_an_unbound_top_up( + lock.out_point, + lock.funding_type, + lock.identity_index, + )); + } + if lock.status.is_consumed() { + return Err(PlatformWalletError::AssetLockAlreadyConsumed( + lock.out_point, + )); + } + match lock.identity_recipient { + Some(recorded) if recorded != identity => { + Err(PlatformWalletError::AssetLockIdentityRecipientMismatch { + out_point: lock.out_point, + recorded, + requested: identity, + }) + } + _ => Ok(()), + } +} + +/// The funding-mismatch error for an operation that needs an unbound identity +/// top-up lock (assigning or resuming to a recorded recipient) and was handed +/// a lock of another funding type. +pub(crate) fn not_an_unbound_top_up( + out_point: OutPoint, + funding_type: AssetLockFundingType, + identity_index: u32, +) -> PlatformWalletError { + PlatformWalletError::AssetLockFundingMismatch { + out_point, + expected_funding_type: AssetLockFundingType::IdentityTopUpNotBound, + expected_identity_index: 0, + actual_funding_type: funding_type, + actual_identity_index: identity_index, + } +} + +/// What an existing-lock resume reads off a tracked row (see +/// [`AssetLockManager::tracked_resume_metadata`]). +pub(crate) struct TrackedResumeMetadata { + pub funding_type: AssetLockFundingType, + pub identity_index: u32, + pub status: AssetLockStatus, + pub identity_recipient: Option, +} diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs index 8294b98793b..208cf0ac072 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs @@ -13,6 +13,7 @@ use dpp::prelude::AssetLockProof; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use crate::changeset::{AssetLockEntry, ShieldedRecipientRaw}; +use dpp::prelude::Identifier; /// Asset lock status on Core chain. /// @@ -152,6 +153,28 @@ pub struct TrackedAssetLock { /// funding type and for shielded locks tracked before the recipient was /// recorded (those keep accepting the resuming caller's recipient). pub shielded_recipient: Option, + /// The identity an unbound identity top-up (`IdentityTopUpNotBound`) was + /// built to pay, recorded with the row before the lock is dispatched, or + /// assigned later by the user to a lock that had none; immutable once + /// set. A resume pays this identity and refuses any other. `None` for + /// every other funding type, and for an unbound lock nothing recorded a + /// recipient for (one rebuilt from the chain after a restore): such a + /// lock is unassigned (see [`Self::is_unassigned_identity_top_up`]) and + /// is resumable only once a recipient is assigned, since its credit + /// output names no identity and it may have been meant for someone else. + pub identity_recipient: Option, +} + +impl TrackedAssetLock { + /// An unbound identity top-up with no recorded recipient, not yet + /// consumed: its funds are recoverable (the wallet holds the credit + /// output's key), but the identity it was meant to pay is unknown, so no + /// resume pays it until the user assigns one. + pub fn is_unassigned_identity_top_up(&self) -> bool { + self.funding_type == AssetLockFundingType::IdentityTopUpNotBound + && self.identity_recipient.is_none() + && !self.status.is_consumed() + } } impl From<&TrackedAssetLock> for AssetLockEntry { @@ -167,6 +190,7 @@ impl From<&TrackedAssetLock> for AssetLockEntry { status: lock.status.clone(), proof: lock.proof.clone(), shielded_recipient: lock.shielded_recipient, + identity_recipient: lock.identity_recipient, } } } diff --git a/packages/rs-platform-wallet/src/wallet/core/generation.rs b/packages/rs-platform-wallet/src/wallet/core/generation.rs index 885dbddd8e9..2a40ebf735a 100644 --- a/packages/rs-platform-wallet/src/wallet/core/generation.rs +++ b/packages/rs-platform-wallet/src/wallet/core/generation.rs @@ -850,6 +850,13 @@ impl InBroadcastPin { Arc::ptr_eq(&self.generation, generation) } + /// The generation this pin was taken on. A dispatch takes its + /// [`payment_guard`](WalletGeneration::payment_guard) and checks it is + /// still current before sending. + pub(crate) fn generation(&self) -> &Arc { + &self.generation + } + /// End the dispatching phase and open the pending-spend fence, which then /// waits for [`WalletGeneration::observe_spent`] and for nothing else — it /// carries no deadline. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index f54f1791730..c755735a834 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -3931,6 +3931,7 @@ mod tests { Arc::new(tokio::sync::Notify::new()), Arc::clone(&broadcaster), persister.clone(), + Arc::clone(&generation), )); IdentityWallet { sdk: Arc::clone(&sdk), diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index babb0e9fee1..59bcef2675e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -45,6 +45,7 @@ mod key_selection; mod loading; mod register_from_addresses; mod registration; +pub use registration::min_top_up_duffs; mod state_transition_summary; mod top_up; mod top_up_from_addresses; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/registration.rs b/packages/rs-platform-wallet/src/wallet/identity/network/registration.rs index 68d3c47e0d0..ad41172d099 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/registration.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/registration.rs @@ -58,6 +58,9 @@ use std::collections::BTreeMap; +use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; +use dpp::balances::credits::CREDITS_PER_DUFF; +use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; use dpp::identity::v0::IdentityV0; use dpp::identity::Identity; @@ -66,16 +69,23 @@ use dpp::identity::KeyID; use dpp::identity::Purpose; use dpp::identity::SecurityLevel; use dpp::prelude::Identifier; +use dpp::state_transition::identity_topup_transition::v0::IdentityTopUpTransitionV0; +use dpp::state_transition::identity_topup_transition::IdentityTopUpTransition; +use dpp::state_transition::StateTransitionEstimatedFeeValidation; +use dpp::version::{PlatformVersion, PLATFORM_VERSIONS}; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use dash_sdk::platform::transition::put_identity::PutIdentity; use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::platform::transition::top_up_identity::TopUpIdentityWithMetadata; +use dash_sdk::platform::Fetch; +use crate::changeset::AssetLockRecipient; use crate::error::PlatformWalletError; use crate::wallet::asset_lock::orchestration::{ out_point_from_proof, FundingResolution, ResolvedFunding, }; +use crate::wallet::asset_lock::sync::tracking::not_an_unbound_top_up; use crate::wallet::asset_lock::AssetLockFunding; use crate::BlockTime; @@ -389,6 +399,7 @@ impl IdentityWallet { where AS: ::key_wallet::signer::ExtendedPubKeySigner + Send + Sync, { + let funding = apply_top_up_minimum(funding)?; // Step 1: retrieve the identity + its HD index. let (identity, identity_index) = { let wm = self.wallet_manager.read().await; @@ -408,6 +419,281 @@ impl IdentityWallet { (identity, index) }; + // Steps 2–3. A resumed unbound top-up lock pays this identity only if + // its row recorded it; a new lock is bound and records nothing. + let (mut new_balance, metadata) = self + .submit_top_up_with_funding( + &identity, + funding, + AssetLockFundingType::IdentityTopUp, + identity_index, + asset_lock_signer, + settings, + ) + .await?; + + // Step 4 (best-effort): persist the new balance. The tracked lock was + // already consumed in step 3. + new_balance = self + .record_top_up_balance(identity_id, new_balance, metadata) + .await; + Ok(new_balance) + } + + /// Top up someone else's identity — one this wallet does not manage — + /// from the wallet's Core balance. + /// + /// 1. Fetch the identity from Platform (proved) instead of the local + /// `IdentityManager`. An identity Platform does not know is + /// [`PlatformWalletError::IdentityNotFound`]; nothing is built. + /// 2. Fund the lock from the wallet's unbound top-up account + /// (`IdentityTopUpNotBound`, DIP-9), which needs no registration + /// index. The lock's row records `identity_id` and is stored before + /// the lock is broadcast, so an interrupted top-up resumes to this + /// identity and to no other (see + /// [`Self::resume_identity_top_up_to_recorded_recipient`]). Requires a + /// persister declaring `ASSET_LOCK_IDENTITY_RECIPIENTS`. + /// 3. Submit the `IdentityTopUp` with the same IS→CL fallbacks as the + /// managed top-up, and return the identity's proved new balance. + /// 4. Consume the tracked lock. Nothing is added to the identity + /// manager; if the wallet does hold this identity, its local balance + /// is updated as on the managed route. + /// + /// `funding` may also be an existing unbound lock that recorded this + /// identity; a lock recording another identity is refused. + pub async fn top_up_external_identity_with_funding( + &self, + identity_id: &Identifier, + funding: AssetLockFunding, + asset_lock_signer: &AS, + settings: Option, + ) -> Result + where + AS: ::key_wallet::signer::ExtendedPubKeySigner + Send + Sync, + { + let funding = apply_top_up_minimum(funding)?; + let identity = self.fetch_identity_to_pay(identity_id).await?; + + let (new_balance, metadata) = self + .submit_top_up_with_funding( + &identity, + funding, + AssetLockFundingType::IdentityTopUpNotBound, + 0, + asset_lock_signer, + settings, + ) + .await?; + // The caller may name an identity this wallet holds after all; its + // local balance then follows Platform's, as on the managed route. The + // proved balance is what this route reports, not the local one: on + // metadata no newer than the cached balance's, the local record keeps + // the cached value, which can predate this top-up. + self.record_top_up_balance(identity_id, new_balance, metadata) + .await; + Ok(new_balance) + } + + /// Assign the identity an unassigned unbound top-up lock pays + /// ([`TrackedAssetLock::is_unassigned_identity_top_up`]), after checking + /// that Platform knows it: an assignment is permanent, so a mistyped id + /// would otherwise strand the lock. An unknown identity is + /// [`PlatformWalletError::IdentityNotFound`] and nothing is assigned. + /// Afterwards a resume pays this identity and refuses any other. + /// + /// Also refused on a backend that cannot keep the assignment + /// (`PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS`), for a lock + /// that is not an unassigned unbound top-up, and for a lock recording + /// another identity + /// ([`PlatformWalletError::AssetLockIdentityRecipientMismatch`]). If the + /// store fails, the error is returned and the assignment holds for this + /// session; assigning the same identity again retries the store. A wallet + /// removed or re-created under its id while the identity was looked up is + /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing + /// assigned. + /// + /// [`TrackedAssetLock::is_unassigned_identity_top_up`]: crate::wallet::asset_lock::tracked::TrackedAssetLock::is_unassigned_identity_top_up + pub async fn assign_identity_top_up_recipient( + &self, + out_point: &dashcore::OutPoint, + identity_id: &Identifier, + ) -> Result<(), PlatformWalletError> { + self.fetch_identity_to_pay(identity_id).await?; + self.asset_locks + .assign_identity_top_up_recipient(out_point, *identity_id, &self.generation) + .await + } + + /// Fetch an identity this wallet may not manage, before anything pays it. + async fn fetch_identity_to_pay( + &self, + identity_id: &Identifier, + ) -> Result { + // TODO(dashpay/platform#5860): report a failed lookup as + // `PlatformWalletError::IdentityLookupFailed` (FFI 80) once #5860 + // merges, as its external top-up from Platform addresses does. Until + // then it surfaces as the plain SDK error; either way nothing is built + // or assigned. + Identity::fetch(&self.sdk, *identity_id) + .await + .map_err(PlatformWalletError::Sdk)? + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id)) + } + + /// Resume an interrupted identity top-up to the identity its lock pays. + /// The caller names no identity, so a host's recovery cannot redirect + /// someone else's top-up into one of its own identities, and needs no + /// classifier of its own: this one call resumes any top-up lock. + /// + /// - A bound top-up lock (`IdentityTopUp`) pays the wallet's identity at + /// its registration index, read from the lock's derivation path. If + /// the wallet does not hold that identity yet, the result is + /// [`PlatformWalletError::AssetLockIdentityNotLoaded`]. + /// - An unbound top-up lock (`IdentityTopUpNotBound`) pays the identity + /// its row recorded. One that records none (rebuilt from the chain) is + /// [`PlatformWalletError::AssetLockRecipientUnknown`] until the user + /// assigns one. + /// + /// An identity this wallet holds is topped up through + /// [`Self::top_up_identity_with_funding`] (which also updates its local + /// balance); any other through + /// [`Self::top_up_external_identity_with_funding`]. Returns the identity + /// paid and its proved new balance. Any other lock is + /// [`PlatformWalletError::AssetLockFundingMismatch`]. + pub async fn resume_identity_top_up_to_recorded_recipient( + &self, + out_point: dashcore::OutPoint, + asset_lock_signer: &AS, + settings: Option, + ) -> Result<(Identifier, u64), PlatformWalletError> + where + AS: ::key_wallet::signer::ExtendedPubKeySigner + Send + Sync, + { + let lock = self + .asset_locks + .tracked_resume_metadata(&out_point) + .await + .ok_or(PlatformWalletError::AssetLockNotTracked(out_point))?; + let (identity_id, managed) = { + let wm = self.wallet_manager.read().await; + let identities = wm + .get_wallet_info(&self.wallet_id) + .map(|info| &info.identity_manager); + match lock.funding_type { + AssetLockFundingType::IdentityTopUp => { + let identity_id = identities + .and_then(|manager| manager.wallet_identities.get(&self.wallet_id)) + .and_then(|by_index| by_index.get(&lock.identity_index)) + .map(|managed| managed.identity.id()) + .ok_or(PlatformWalletError::AssetLockIdentityNotLoaded { + out_point, + identity_index: lock.identity_index, + })?; + (identity_id, true) + } + AssetLockFundingType::IdentityTopUpNotBound => { + // A consumed lock pays no one, assigned or not; say so + // first, as the unassigned listing and assignment do. + if lock.status.is_consumed() { + return Err(PlatformWalletError::AssetLockAlreadyConsumed(out_point)); + } + let identity_id = lock + .identity_recipient + .ok_or(PlatformWalletError::AssetLockRecipientUnknown(out_point))?; + // Only a signing-capable identity of this wallet takes + // the managed route: an observed one has no index. + let managed = identities.is_some_and(|manager| { + manager + .wallet_identity(&self.wallet_id, &identity_id) + .is_some() + }); + (identity_id, managed) + } + _ => { + return Err(not_an_unbound_top_up( + out_point, + lock.funding_type, + lock.identity_index, + )) + } + } + }; + let funding = AssetLockFunding::FromExistingAssetLock { + out_point, + consume_invitation_voucher: false, + }; + let new_balance = if managed { + self.top_up_identity_with_funding(&identity_id, funding, asset_lock_signer, settings) + .await? + } else { + self.top_up_external_identity_with_funding( + &identity_id, + funding, + asset_lock_signer, + settings, + ) + .await? + }; + Ok((identity_id, new_balance)) + } + + /// Record a top-up's proved new balance on the identity, if this wallet + /// holds it, and return the balance to report. Best-effort: Platform has + /// ALREADY accepted the top-up, so a missing local wallet must NOT + /// propagate as `Err` (the caller would report failure for credits that + /// exist on chain). The stale local balance self-heals on the next + /// identity re-sync. Same posture as register's step 4. + async fn record_top_up_balance( + &self, + identity_id: &Identifier, + new_balance: u64, + metadata: ResponseMetadata, + ) -> u64 { + let mut wm = self.wallet_manager.write().await; + match wm.get_wallet_info_mut(&self.wallet_id) { + Some(info) => info + .identity_manager + .managed_identity_mut(identity_id) + .map_or(new_balance, |managed| { + managed.persist_confirmed_balance( + new_balance, + BlockTime::from(metadata), + &self.persister, + ) + }), + None => { + tracing::warn!( + identity = %identity_id, + "identity top-up accepted on Platform but wallet info was not found \ + locally; skipping balance persistence" + ); + new_balance + } + } + } + + /// Steps 2–3 of a Core-funded top-up, shared by the managed + /// ([`Self::top_up_identity_with_funding`]) and external + /// ([`Self::top_up_external_identity_with_funding`]) routes: resolve the + /// funding to a proof (with the IS→CL fallback), submit the + /// `IdentityTopUp` for `identity`, and reconcile the result. The lock pays + /// `identity`: a new unbound lock records it, and an existing unbound + /// lock must have recorded it. Once Platform has accepted the top-up the + /// tracked lock is consumed (best-effort: a cleanup failure is logged, not + /// reported). Returns the proved new balance and the response metadata. + #[allow(clippy::too_many_arguments)] + async fn submit_top_up_with_funding( + &self, + identity: &Identity, + funding: AssetLockFunding, + funding_type: AssetLockFundingType, + identity_index: u32, + asset_lock_signer: &AS, + settings: Option, + ) -> Result<(u64, ResponseMetadata), PlatformWalletError> + where + AS: ::key_wallet::signer::ExtendedPubKeySigner + Send + Sync, + { // Step 2: resolve funding. Same IS→CL fallback shape as // `register_identity_with_funding` — see that method for the // architectural rationale. @@ -419,9 +705,9 @@ impl IdentityWallet { .asset_locks .resolve_funding_with_is_timeout_fallback( funding, - AssetLockFundingType::IdentityTopUp, + funding_type, identity_index, - None, + Some(AssetLockRecipient::Identity(identity.id())), asset_lock_signer, None, ) @@ -470,7 +756,7 @@ impl IdentityWallet { }, ) .await?; - let (mut new_balance, metadata) = self + let (new_balance, metadata) = self .asset_locks .reconcile_asset_lock_submit_result( submit_result, @@ -479,46 +765,10 @@ impl IdentityWallet { None, ) .await?; - - // Step 4 (best-effort): persist the new balance + clean up the - // tracked lock. - // - // Platform has ALREADY accepted the top-up, so a missing local - // wallet must NOT propagate as `Err` — the caller would report - // failure for credits that exist on chain, and the early return - // would skip the `consume_asset_lock` below, leaving the spent - // lock in the Resumable Funding list where a Resume gets - // Platform's deterministic "lock already consumed" rejection. - // The stale local balance self-heals on the next identity - // re-sync. Same posture as register's Step 4. - { - let mut wm = self.wallet_manager.write().await; - match wm.get_wallet_info_mut(&self.wallet_id) { - Some(info) => { - if let Some(managed) = info.identity_manager.managed_identity_mut(identity_id) { - new_balance = managed.persist_confirmed_balance( - new_balance, - BlockTime::from(metadata), - &self.persister, - ); - } - } - None => { - tracing::warn!( - identity = %identity_id, - "top_up_identity_with_funding: top-up accepted on Platform \ - but wallet info was not found locally; skipping balance \ - persistence" - ); - } - } - } if let Some(out_point) = tracked_out_point { - // Cleanup failure here can only mean WalletNotFound - // (the wallet handle that just registered an identity - // vanished). Surface as a warn — the identity DID - // register successfully on Platform, so propagating the - // error to the caller would be misleading. + // Cleanup failure here can only mean WalletNotFound (the wallet + // handle that just topped up the identity vanished). Platform has + // accepted the top-up, so reporting it as an error would mislead. if let Err(e) = self.asset_locks.consume_asset_lock(&out_point).await { tracing::warn!( outpoint = %out_point, @@ -527,8 +777,75 @@ impl IdentityWallet { ); } } + Ok((new_balance, metadata)) + } +} - Ok(new_balance) +/// The minimum asset-lock funding, in duffs, Platform accepts for an +/// identity top-up under every protocol version this build supports. +/// +/// Platform rejects an `IdentityTopUp` whose asset-lock output value (in +/// credits) is below `IdentityTopUpTransition::calculate_min_required_fee`, +/// so that calculation is the minimum: 50_000 duffs under fee v0, and 50_500 +/// under v1 (protocol v11+), which adds `identity_topup_base_cost`. Below it, +/// a lock built and broadcast is accepted by Core (spending real UTXOs) but +/// rejected by Platform, stranding the funds in a lock that can never +/// complete the top-up. +/// +/// The largest minimum across the versions, not the SDK's current one: the +/// SDK's version can move during the top-up (a proved fetch ratchets it up, +/// and a pinned SDK can lag the network), so an amount held to the version +/// read first could clear a lower floor and then be submitted under a higher +/// one, after its Core funds are locked. +pub fn min_top_up_duffs() -> Result { + PLATFORM_VERSIONS + .iter() + .try_fold(0, |max, platform_version| { + Ok(max.max(min_top_up_duffs_at(platform_version)?)) + }) +} + +/// Platform's top-up minimum, in duffs, under `platform_version` alone. +fn min_top_up_duffs_at(platform_version: &PlatformVersion) -> Result { + let credits = IdentityTopUpTransition::V0(IdentityTopUpTransitionV0::default()) + .calculate_min_required_fee(platform_version) + .map_err(dash_sdk::Error::Protocol)?; + Ok(credits.div_ceil(CREDITS_PER_DUFF)) +} + +/// Hold a new top-up lock to [`min_top_up_duffs`] before anything is looked +/// up, built or broadcast. An amount below it is refused; a drain gets it as +/// its floor, which the builder enforces on the built lock before tracking or +/// broadcasting it. An existing lock's amount is already fixed. +fn apply_top_up_minimum( + funding: AssetLockFunding, +) -> Result { + let min_duffs = min_top_up_duffs()?; + let floor = |minimum: Option| Some(minimum.unwrap_or(0).max(min_duffs)); + match funding { + AssetLockFunding::FromWalletBalance { amount_duffs, .. } if amount_duffs < min_duffs => { + Err(PlatformWalletError::InvalidParameter(format!( + "a top-up of {amount_duffs} duffs is below the minimum top-up asset-lock \ + balance of {min_duffs} duffs" + ))) + } + AssetLockFunding::DrainAccountBalance { + account, + minimum_lock_duffs, + } => Ok(AssetLockFunding::DrainAccountBalance { + account, + minimum_lock_duffs: floor(minimum_lock_duffs), + }), + AssetLockFunding::DrainWalletBalance { + account_index, + minimum_lock_duffs, + operation, + } => Ok(AssetLockFunding::DrainWalletBalance { + account_index, + minimum_lock_duffs: floor(minimum_lock_duffs), + operation, + }), + funding => Ok(funding), } } @@ -552,6 +869,416 @@ mod tests { use crate::error::is_instant_lock_timeout; use dashcore::{OutPoint, Txid}; + use crate::test_support::{ + funded_wallet_manager, platform_wallet_in, platform_wallet_with_sdk, WalletSigner, + }; + use crate::wallet::asset_lock::tracked::{AssetLockStatus, TrackedAssetLock}; + use crate::wallet::platform_wallet::PlatformWallet; + use key_wallet::account::account_type::StandardAccountType; + + /// A funded wallet over a mock SDK whose identity fetch for `id` answers + /// `answer` (`None`: Platform does not know it). + async fn wallet_where_platform_answers( + id: Identifier, + answer: Option, + ) -> (PlatformWallet, WalletSigner) { + let (wallet_manager, wallet_id, _generation, signer) = + funded_wallet_manager(StandardAccountType::BIP44Account).await; + let network = { + let wm = wallet_manager.read().await; + wm.get_wallet_and_info(&wallet_id).unwrap().0.network + }; + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(network) + .with_version(dpp::version::PlatformVersion::latest()) + .build() + .expect("mock sdk"); + sdk.mock() + .expect_fetch(id, answer) + .await + .expect("identity expectation"); + ( + platform_wallet_with_sdk(wallet_manager, wallet_id, sdk).await, + signer, + ) + } + + /// Track a proof-less lock of `funding_type` recording `recorded`. + async fn track_lock( + wallet: &PlatformWallet, + vout: u32, + funding_type: AssetLockFundingType, + recorded: Option, + ) -> OutPoint { + let transaction = dashcore::Transaction { + version: 3, + lock_time: 0, + input: vec![], + output: vec![], + special_transaction_payload: None, + }; + let out_point = OutPoint::new(Txid::from([0x61u8; 32]), vout); + let mut wm = wallet.identity().wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .tracked_asset_locks + .insert( + out_point, + TrackedAssetLock { + operation_id: None, + out_point, + transaction, + account_index: 0, + funding_type, + identity_index: 0, + amount: 1_000_000, + status: AssetLockStatus::Broadcast, + proof: None, + shielded_recipient: None, + identity_recipient: recorded, + }, + ); + out_point + } + + /// An identity Platform does not know is refused before any lock is + /// built: nothing is tracked afterwards. + #[tokio::test] + async fn should_refuse_an_external_top_up_of_an_identity_platform_does_not_know() { + let unknown = Identifier::from([0x62u8; 32]); + let (wallet, signer) = wallet_where_platform_answers(unknown, None).await; + + let result = wallet + .identity() + .top_up_external_identity_with_funding( + &unknown, + AssetLockFunding::FromWalletBalance { + amount_duffs: 1_000_000, + account_index: 0, + }, + &signer, + None, + ) + .await; + + assert!( + matches!(result, Err(PlatformWalletError::IdentityNotFound(id)) if id == unknown), + "{result:?}" + ); + assert!(wallet.asset_locks().list_tracked_locks().await.is_empty()); + } + + /// A known identity is still refused before any lock is built when the + /// host's persister cannot keep the lock's recipient across a restart. + #[tokio::test] + async fn should_refuse_an_external_top_up_a_persister_cannot_record() { + let known = Identifier::from([0x64u8; 32]); + let identity = Identity::V0(IdentityV0 { + id: known, + public_keys: BTreeMap::new(), + balance: 5, + revision: 0, + }); + let (wallet, signer) = wallet_where_platform_answers(known, Some(identity)).await; + + let result = wallet + .identity() + .top_up_external_identity_with_funding( + &known, + AssetLockFunding::FromWalletBalance { + amount_duffs: 1_000_000, + account_index: 0, + }, + &signer, + None, + ) + .await; + + assert!( + matches!(&result, Err(PlatformWalletError::Persistence(message)) + if message.contains("asset_lock_identity_recipients")), + "{result:?}" + ); + assert!(wallet.asset_locks().list_tracked_locks().await.is_empty()); + } + + /// A new top-up lock below the minimum is refused on both routes before + /// the identity is looked up or anything is built. + #[tokio::test] + async fn should_refuse_a_top_up_below_the_minimum_on_both_routes() { + let id = Identifier::from([0x65u8; 32]); + // No fetch expectation: reaching Platform would fail differently. + let (wallet_manager, wallet_id, _generation, signer) = + funded_wallet_manager(StandardAccountType::BIP44Account).await; + let wallet = platform_wallet_in(wallet_manager, wallet_id).await; + let below = min_top_up_duffs().unwrap() - 1; + let funding = || AssetLockFunding::FromWalletBalance { + amount_duffs: below, + account_index: 0, + }; + let identity = wallet.identity(); + for result in [ + identity + .top_up_identity_with_funding(&id, funding(), &signer, None) + .await, + identity + .top_up_external_identity_with_funding(&id, funding(), &signer, None) + .await, + ] { + assert!( + matches!(result, Err(PlatformWalletError::InvalidParameter(_))), + "{result:?}" + ); + } + assert!(wallet.asset_locks().list_tracked_locks().await.is_empty()); + } + + /// A drain cannot build a top-up lock below the minimum either: its floor + /// is raised to [`min_top_up_duffs`], a higher floor is kept, and an amount + /// at the minimum passes unchanged. + #[test] + fn should_hold_every_new_top_up_funding_to_the_minimum() { + use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingAccount; + + let min = min_top_up_duffs().unwrap(); + let drain = |minimum_lock_duffs| AssetLockFunding::DrainAccountBalance { + account: AssetLockFundingAccount::Bip44 { account_index: 0 }, + minimum_lock_duffs, + }; + let floor_of = |funding| match apply_top_up_minimum(funding) { + Ok(AssetLockFunding::DrainAccountBalance { + minimum_lock_duffs, .. + }) => minimum_lock_duffs, + other => panic!("a drain stays a drain: {other:?}"), + }; + assert_eq!(floor_of(drain(None)), Some(min)); + assert_eq!(floor_of(drain(Some(1))), Some(min)); + assert_eq!(floor_of(drain(Some(min + 1))), Some(min + 1)); + assert!(matches!( + apply_top_up_minimum( + AssetLockFunding::FromWalletBalance { + amount_duffs: min, + account_index: 0, + }, + ), + Ok(AssetLockFunding::FromWalletBalance { amount_duffs, .. }) + if amount_duffs == min + )); + } + + /// The minimum is Platform's own top-up fee floor, the largest across the + /// protocol versions this build supports, so it holds whichever of them + /// the top-up is submitted under: the bare asset-lock floor under fee v0, + /// plus the top-up base cost under v1. + #[test] + fn should_take_the_top_up_minimum_from_every_protocol_version() { + assert_eq!( + min_top_up_duffs_at(PlatformVersion::first()).unwrap(), + 50_000 + ); + assert_eq!( + min_top_up_duffs_at(PlatformVersion::latest()).unwrap(), + 50_500 + ); + let min = min_top_up_duffs().unwrap(); + assert_eq!(min, 50_500); + for platform_version in PLATFORM_VERSIONS { + assert!( + min >= min_top_up_duffs_at(platform_version).unwrap(), + "protocol version {}", + platform_version.protocol_version + ); + } + } + + /// A top-up's proved balance lands on the identity when this wallet holds + /// it, on either route; an identity it does not hold is left alone. + #[tokio::test] + async fn should_record_a_top_up_balance_on_an_identity_the_wallet_holds() { + let (wallet_manager, wallet_id, _generation, _signer) = + funded_wallet_manager(StandardAccountType::BIP44Account).await; + let wallet = platform_wallet_in(wallet_manager, wallet_id).await; + let own = Identifier::from([0x67u8; 32]); + { + let mut wm = wallet.identity().wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity_unstored( + Identity::V0(IdentityV0 { + id: own, + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }), + 0, + wallet.wallet_id(), + ) + .unwrap(); + } + + let reported = wallet + .identity() + .record_top_up_balance(&own, 7_000_000, ResponseMetadata::default()) + .await; + assert_eq!(reported, 7_000_000); + let wm = wallet.identity().wallet_manager.read().await; + let identities = &wm + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager; + assert_eq!( + identities.identity(&own).unwrap().identity.balance(), + 7_000_000 + ); + drop(wm); + + let stranger = Identifier::from([0x68u8; 32]); + assert_eq!( + wallet + .identity() + .record_top_up_balance(&stranger, 5, ResponseMetadata::default()) + .await, + 5 + ); + } + + /// An assignment is permanent, so an identity Platform does not know is + /// refused before anything is recorded: the lock stays unassigned. + #[tokio::test] + async fn should_refuse_to_assign_an_identity_platform_does_not_know() { + let unknown = Identifier::from([0x66u8; 32]); + let (wallet, _signer) = wallet_where_platform_answers(unknown, None).await; + let out_point = track_lock( + &wallet, + 0, + AssetLockFundingType::IdentityTopUpNotBound, + None, + ) + .await; + + let result = wallet + .identity() + .assign_identity_top_up_recipient(&out_point, &unknown) + .await; + + assert!( + matches!(result, Err(PlatformWalletError::IdentityNotFound(id)) if id == unknown), + "{result:?}" + ); + let tracked = wallet.asset_locks().list_tracked_locks().await; + assert!(tracked[0].is_unassigned_identity_top_up()); + } + + /// The resume names no identity: it pays the one the lock recorded (or, + /// for a bound lock, the wallet's identity at its index), or nobody. A + /// lock that is not a top-up, a bound lock whose identity is not loaded, + /// and an unbound lock recording no identity are refused; a recorded identity this wallet does not manage takes the + /// external route (here Platform does not know it, so nothing is paid). + /// Every refused lock stays tracked. + #[tokio::test] + async fn should_resume_a_top_up_lock_only_to_the_identity_it_pays() { + let recorded = Identifier::from([0x63u8; 32]); + let (wallet, signer) = wallet_where_platform_answers(recorded, None).await; + let resume = |out_point| { + wallet + .identity() + .resume_identity_top_up_to_recorded_recipient(out_point, &signer, None) + }; + + let missing = OutPoint::new(Txid::from([0x60u8; 32]), 0); + assert!(matches!( + resume(missing).await, + Err(PlatformWalletError::AssetLockNotTracked(o)) if o == missing + )); + + let registration = + track_lock(&wallet, 4, AssetLockFundingType::IdentityRegistration, None).await; + assert!(matches!( + resume(registration).await, + Err(PlatformWalletError::AssetLockFundingMismatch { .. }) + )); + + // A bound lock pays the wallet's identity at its index: none is + // loaded at index 0, so nothing is paid. + let bound = track_lock(&wallet, 0, AssetLockFundingType::IdentityTopUp, None).await; + assert!(matches!( + resume(bound).await, + Err(PlatformWalletError::AssetLockIdentityNotLoaded { out_point, identity_index: 0 }) + if out_point == bound + )); + // With an identity loaded at the lock's index, the lock resolves to + // it and takes the managed route, which refuses a consumed lock. + let own = Identifier::from([0x64u8; 32]); + let bound_to_own = track_lock(&wallet, 5, AssetLockFundingType::IdentityTopUp, None).await; + { + let mut wm = wallet.identity().wallet_manager.write().await; + let info = wm.get_wallet_info_mut(&wallet.wallet_id()).unwrap(); + info.identity_manager + .add_identity_unstored( + Identity::V0(IdentityV0 { + id: own, + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }), + 3, + wallet.wallet_id(), + ) + .unwrap(); + let lock = info.tracked_asset_locks.get_mut(&bound_to_own).unwrap(); + lock.identity_index = 3; + lock.status = AssetLockStatus::Consumed; + } + assert!(matches!( + resume(bound_to_own).await, + Err(PlatformWalletError::AssetLockAlreadyConsumed(o)) if o == bound_to_own + )); + + let unassigned = track_lock( + &wallet, + 1, + AssetLockFundingType::IdentityTopUpNotBound, + None, + ) + .await; + assert!(matches!( + resume(unassigned).await, + Err(PlatformWalletError::AssetLockRecipientUnknown(o)) if o == unassigned + )); + // Once consumed it pays no one: that is the answer, not the missing + // recipient, as listing and assignment already say. + wallet + .identity() + .wallet_manager + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .tracked_asset_locks + .get_mut(&unassigned) + .unwrap() + .status = AssetLockStatus::Consumed; + assert!(matches!( + resume(unassigned).await, + Err(PlatformWalletError::AssetLockAlreadyConsumed(o)) if o == unassigned + )); + + let external = track_lock( + &wallet, + 2, + AssetLockFundingType::IdentityTopUpNotBound, + Some(recorded), + ) + .await; + assert!(matches!( + resume(external).await, + Err(PlatformWalletError::IdentityNotFound(id)) if id == recorded + )); + + assert_eq!(wallet.asset_locks().list_tracked_locks().await.len(), 5); + } + /// Pins the IS-timeout discriminator: only `FinalityTimeout` /// matches, so the IS→CL fallback arms route exactly the cases /// we expect. Companion to `is_instant_lock_proof_invalid` diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/provider.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/provider.rs index d522927468f..f01fda5a2a0 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/provider.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/provider.rs @@ -1665,6 +1665,7 @@ mod tests { use crate::events::PlatformEventManager; use crate::spv::SpvRuntime; use crate::wallet::asset_lock::manager::AssetLockManager; + use crate::wallet::core::WalletGeneration; use crate::wallet::persister::WalletPersister; use crate::wallet::platform_addresses::PlatformAddressWallet; use tokio::sync::Notify; @@ -1682,6 +1683,8 @@ mod tests { Arc::new(Notify::new()), broadcaster, persister.clone(), + // No wallet is registered under this id; nothing builds here. + Arc::new(WalletGeneration::new()), )); let wallet = PlatformAddressWallet::new( sdk, diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/transfer.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/transfer.rs index 014b375270e..12bb7ab2608 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/transfer.rs @@ -1920,6 +1920,7 @@ mod auto_select_tests { use crate::events::PlatformEventManager; use crate::spv::SpvRuntime; use crate::wallet::asset_lock::manager::AssetLockManager; + use crate::wallet::core::WalletGeneration; use crate::wallet::persister::{NoPlatformPersistence, WalletPersister}; use crate::wallet::platform_addresses::PlatformAddressWallet; use std::sync::Arc; @@ -1940,6 +1941,8 @@ mod auto_select_tests { Arc::new(Notify::new()), broadcaster, persister.clone(), + // No wallet is registered under this id; nothing builds here. + Arc::new(WalletGeneration::new()), )); PlatformAddressWallet::new(sdk, wallet_manager, [0u8; 32], asset_locks, persister) } diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/wallet.rs index 3774e48e203..f9dc07c5799 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/wallet.rs @@ -803,6 +803,7 @@ mod tests { use crate::events::PlatformEventManager; use crate::spv::SpvRuntime; use crate::wallet::asset_lock::manager::AssetLockManager; + use crate::wallet::core::WalletGeneration; use crate::wallet::persister::{NoPlatformPersistence, WalletPersister}; use std::sync::Arc; use tokio::sync::{Notify, RwLock}; @@ -822,6 +823,8 @@ mod tests { Arc::new(Notify::new()), broadcaster, persister.clone(), + // No wallet is registered under this id; nothing builds here. + Arc::new(WalletGeneration::new()), )); PlatformAddressWallet::new(sdk, wallet_manager, [0u8; 32], asset_locks, persister) } diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/withdrawal.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/withdrawal.rs index 765a4330cdb..91c8a4f819c 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/withdrawal.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/withdrawal.rs @@ -1659,6 +1659,7 @@ mod plan_withdrawal_seam_tests { Arc::new(Notify::new()), broadcaster, persister.clone(), + crate::test_support::wallet_generation(&wallet_manager, &wallet_id), )); PlatformAddressWallet::new(sdk, wallet_manager, wallet_id, asset_locks, persister) } diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index c67a5462f70..095a5cfbd6d 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -787,6 +787,7 @@ impl PlatformWallet { lock_notify, broadcaster, wallet_persister.clone(), + Arc::clone(&generation), ) .with_mined_height_locator(mined_height_locator), ); 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..4d04adb05d8 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 @@ -36,7 +36,7 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use dashcore::OutPoint; use dpp::address_funds::{OrchardAddress, PlatformAddress, ORCHARD_ADDRESS_SIZE}; -use crate::changeset::{ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; +use crate::changeset::{AssetLockRecipient, ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; use dpp::asset_lock::StoredAssetLockInfo; use dpp::balances::credits::CREDITS_PER_DUFF; use dpp::fee::Credits; @@ -398,7 +398,7 @@ impl PlatformWallet { funding, AssetLockFundingType::AssetLockShieldedAddressTopUp, /* destination_index */ 0, - Some(recipient.to_raw_bytes()), + Some(AssetLockRecipient::Shielded(recipient.to_raw_bytes())), asset_lock_signer, on_asset_lock_built, ) @@ -1247,7 +1247,7 @@ mod tests { async fn consumption_report_context_for( funding_type: AssetLockFundingType, ) -> ConsumptionReportContext { - let (wallet_manager, wallet_id, _generation, signer) = + let (wallet_manager, wallet_id, generation, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; let persistence = Arc::new(RecordingPersistence::default()); let sdk = Arc::new( @@ -1263,6 +1263,7 @@ mod tests { Arc::new(Notify::new()), Arc::new(AlwaysRejectedBroadcaster), WalletPersister::new(wallet_id, Arc::::clone(&persistence)), + Arc::clone(&generation), ); let (transaction, _path) = manager .build_asset_lock_transaction( @@ -1289,6 +1290,7 @@ mod tests { TrackedAssetLock { operation_id: None, shielded_recipient: None, + identity_recipient: None, out_point, transaction, account_index: 0, diff --git a/packages/rs-platform-wallet/src/wallet/shielded/wallet_drain_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/wallet_drain_tests.rs index b5ca65d2429..e4da04d3ef5 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/wallet_drain_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/wallet_drain_tests.rs @@ -78,6 +78,7 @@ fn drain_lock_fixture() -> (TrackedAssetLock, BTreeMap) status: AssetLockStatus::RecoveredFromChain, proof: Some(proof), shielded_recipient: None, + identity_recipient: None, }, BTreeMap::from([(0, keys)]), ) @@ -161,6 +162,7 @@ impl PlatformWalletPersistence for RecoveryPersistence { status: row.status.clone(), proof: row.proof.clone(), shielded_recipient: row.shielded_recipient, + identity_recipient: row.identity_recipient, }, ) }) @@ -1171,10 +1173,15 @@ async fn fund_typed_amount( /// A typed-amount funding whose recipient cannot be made durable stops before /// the broadcaster: a rejected store and a rejected flush of a buffered store -/// both fail the call with a persistence error, leave the lock untracked and -/// uncommitted, and hand the inputs back so the next attempt builds again. -/// The abandoned row of a failed flush is withdrawn from the buffer, so the -/// next successful flush does not commit it. +/// both fail the call with a persistence error and leave the lock untracked +/// and uncommitted. The abandoned row's removal must be durable before the +/// inputs are released, and on this buffered backend neither case can make it +/// so: a refused store refuses the removal too, and a failed flush leaves the +/// removal only buffered, while another flush may already have committed the +/// row, so a crash would bring the lock back resumable after the inputs +/// funded a retry. The inputs therefore stay reserved in both cases. After +/// the failed flush the removal is still stored behind the row, so the next +/// successful flush does not commit the abandoned row. #[tokio::test] async fn should_abort_typed_amount_funding_when_the_recipient_cannot_be_made_durable() { for fail_flush in [false, true] { @@ -1195,7 +1202,8 @@ async fn should_abort_typed_amount_funding_when_the_recipient_cannot_be_made_dur let (error, seen) = fund_typed_amount(&wallet, &coordinator, &signer, recipient).await; assert!( matches!(&error, PlatformWalletError::Persistence(message) - if message.contains("shielded recipient was not made durable")), + if message.contains("shielded recipient was not made durable") + && message.contains("inputs stay reserved")), "fail_flush={fail_flush}: {error}" ); assert_eq!(seen.len(), 1, "fail_flush={fail_flush}"); @@ -1206,24 +1214,17 @@ async fn should_abort_typed_amount_funding_when_the_recipient_cannot_be_made_dur .iter() .any(|tracked| tracked.out_point == seen[0])); assert!(!persistence.committed.lock().unwrap().contains_key(&seen[0])); + if !fail_flush { + continue; + } - // The inputs were handed back: the retry builds a lock again and gets - // as far as the broadcaster. switch.store(false, Ordering::SeqCst); - let (error, retried) = fund_typed_amount(&wallet, &coordinator, &signer, recipient).await; - assert!( - !matches!(error, PlatformWalletError::Persistence(_)), - "fail_flush={fail_flush}: {error}" - ); - assert_eq!(retried.len(), 1, "fail_flush={fail_flush}"); - assert_ne!(retried[0], seen[0]); + persistence + .flush(wallet.wallet_id()) + .expect("the backend flushes again"); assert!( !persistence.committed.lock().unwrap().contains_key(&seen[0]), - "fail_flush={fail_flush}: the abandoned row was committed by a later flush" - ); - assert_eq!( - persistence.committed.lock().unwrap()[&retried[0]].shielded_recipient, - Some(recipient.to_raw_bytes()) + "the abandoned row was committed by a later flush" ); } }