From 57c480941536d7f4c523d9335de10a5ae5579b79 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 4 Nov 2026 14:51:19 +0100 Subject: [PATCH 1/7] feat(platform-wallet): persist the Orchard recipient of a shielded asset-lock funding A Core -> Shielded funding (Type 18) broadcasts an asset lock first and submits the shield transition after the lock is proven. If the host is killed in between, the transfer is resumed from the tracked lock, but the row carried no recipient, so both the generic resume and a repeated-UUID wallet drain paid whatever recipient the resuming call named. Record the recipient on `TrackedAssetLock` / `AssetLockEntry` (`shielded_recipient: Option`, address only) at the one row-creation site, so it is exactly as durable before dispatch as `operation_id`. On resume, pay the recorded recipient and refuse a different one with the new typed `AssetLockRecipientMismatch` (FFI code 61), before any funding resolution. Rows tracked before the recipient was recorded carry none and keep accepting the caller's. The recipient is immutable once recorded: merge, apply, the SQLite upsert and the Swift persister all keep it when a later snapshot lacks it and reject a change. Persistence: serde adapter on the changeset; SQLite migration V020 adds a nullable 43-byte column with an immutability trigger (lifecycle blob untouched); two size-negotiated FFI extension slots carry it as a sidecar next to the frozen `AssetLockEntryFFI` row, attested by the new `ASSET_LOCK_SHIELDED_RECIPIENTS` capability (reported, not required by `WALLET_DRAIN`; a host without the slots still stores the row). Swift adds `PersistentAssetLock.shieldedRecipientRaw43` to the live V4 model (not yet frozen: schema-releases.json registers 3.0.0 only) with the sidecar callbacks; `TrackedAssetLockFFI` and the Swift `TrackedAssetLock` expose the recipient read-only. Kotlin maps code 61; its sidecar follows with the UUID sidecar it also lacks. Closes dashpay/platform#5603. Co-Authored-By: Claude Fable 5.1 --- .../dashsdk/errors/DashSdkError.kt | 10 + .../dashsdk/errors/DashSdkErrorTest.kt | 9 + .../ERROR_CODE_REGISTRY.md | 1 + .../src/asset_lock/manager.rs | 13 + packages/rs-platform-wallet-ffi/src/error.rs | 39 ++ .../rs-platform-wallet-ffi/src/manager.rs | 13 +- .../rs-platform-wallet-ffi/src/persistence.rs | 343 ++++++++++++++++++ .../src/shielded_send.rs | 20 +- .../src/test_fixtures.rs | 11 + packages/rs-platform-wallet-storage/SCHEMA.md | 1 + .../V020__asset_lock_shielded_recipient.rs | 12 + .../src/sqlite/schema/asset_locks.rs | 65 +++- .../integration/sqlite_asset_locks_filter.rs | 95 +++++ .../sqlite_blob_roundtrip_coverage.rs | 1 + .../integration/sqlite_load_reconstruction.rs | 2 + .../integration/sqlite_persist_roundtrip.rs | 3 + .../tests/integration/sqlite_recovery_mode.rs | 1 + .../integration/sqlite_schema_pinning.rs | 4 +- .../sqlite_structural_hardening.rs | 1 + .../tests/integration/sqlite_version_bump.rs | 1 + .../src/changeset/changeset.rs | 69 +++- .../src/changeset/core_bridge.rs | 1 + .../src/changeset/persistence_capabilities.rs | 19 +- .../src/changeset/serde_adapters.rs | 86 +++++ packages/rs-platform-wallet/src/error.rs | 16 + .../rs-platform-wallet/src/test_support.rs | 13 + .../rs-platform-wallet/src/wallet/apply.rs | 37 +- .../src/wallet/asset_lock/build.rs | 56 ++- .../src/wallet/asset_lock/orchestration.rs | 6 + .../src/wallet/asset_lock/sync/proof.rs | 5 + .../wallet/asset_lock/sync/reconstruction.rs | 3 + .../src/wallet/asset_lock/sync/recovery.rs | 12 + .../src/wallet/asset_lock/sync/tracking.rs | 13 + .../src/wallet/asset_lock/tracked.rs | 9 + .../wallet/identity/network/registration.rs | 2 + .../fund_from_asset_lock.rs | 1 + .../wallet/shielded/fund_from_asset_lock.rs | 62 +++- .../src/wallet/shielded/wallet_drain_tests.rs | 217 +++++++++++ .../Models/PersistentAssetLock.swift | 17 +- .../AssetLock/ManagedAssetLockManager.swift | 10 +- .../PlatformWalletPersistenceHandler.swift | 92 ++++- .../PlatformWallet/PlatformWalletResult.swift | 16 +- .../AssetLockOperationPersistenceTests.swift | 36 ++ 43 files changed, 1411 insertions(+), 32 deletions(-) create mode 100644 packages/rs-platform-wallet-storage/migrations/V020__asset_lock_shielded_recipient.rs diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 9f19d1653a0..02cf721a115 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -243,6 +243,15 @@ sealed class DashSdkError( class AssetLockTooManyInputs(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * Code 61: a shielded fund-from-asset-lock resume named a different Orchard + * recipient than the one the tracked lock recorded when it was built. Nothing + * was submitted or paid; resume with the recorded recipient. Locks tracked + * before the recipient was recorded carry none and accept the caller's. + */ + class AssetLockRecipientMismatch(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) + /** * `ErrorShieldedNoRecordedAnchor` (native code 19). A shielded spend * could not be built against a Platform-recorded anchor because the @@ -771,6 +780,7 @@ sealed class DashSdkError( 27 -> PlatformWallet.ShutdownIncomplete(message, cause) // ErrorShutdownIncomplete 29 -> PlatformWallet.AssetLockInsufficientFunds(message, cause) // ErrorAssetLockInsufficientFunds 60 -> PlatformWallet.AssetLockTooManyInputs(message, cause) // ErrorAssetLockTooManyInputs + 61 -> PlatformWallet.AssetLockRecipientMismatch(message, cause) // ErrorAssetLockRecipientMismatch // The deferred-token trio sits at the contiguous block 34-36 because // 27-33 are claimed elsewhere: 27 ErrorShutdownIncomplete // (dashpay/platform#4268, merged), 29 ErrorAssetLockInsufficientFunds diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index fd09ae4051a..9614b42fa2f 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -19,6 +19,15 @@ class DashSdkErrorTest { assertFalse(mapped.isRetryable) } + @Test + fun shouldPreserveAssetLockRecipientMismatchAsATypedRefusal() { + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 61, "cannot be resumed to") + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.AssetLockRecipientMismatch) + assertEquals(native.message, mapped.message) + assertFalse(mapped.isRetryable) + } + @Test fun mapsNativeCodesToHierarchy() { // Codes mirror DashSDKErrorCode in rs-sdk-ffi/src/error.rs. diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index 65b3aed4c6b..63f7292ebb7 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -177,6 +177,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 58 | `ErrorIdentityBalanceUnavailable` | #4799 | Proposed — Platform returned no balance for a managed identity. Retrying the read is safe; this is distinct from missing wallet ownership and must not trigger registration or funding | | 59 | `ErrorSpvProcessRestartRequired` | #5322 | Proposed — SPV startup or teardown panicked; restart the host process. Not retryable, unlike 27, which SPV start, stop and storage clear now return while an SPV teardown is still running. Typed in Rust, Swift and Kotlin (the PR also types 27 on Kotlin) | | 60 | `ErrorAssetLockTooManyInputs` | Core-to-shielded pooled Max | Proposed — an asset lock needs more inputs than one may carry (100 on Dash Core relay policy and Platform consensus): the full drain, or since #5712 a fixed amount held only in many small coins (identity registration, top-up, invitation, platform-address funding); nothing was broadcast, and no partial drain. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | +| 61 | `ErrorAssetLockRecipientMismatch` | dashpay/platform#5603 (tracked-lock shielded recipient) | Proposed — a shielded fund-from-asset-lock resume (the generic outpoint resume or a repeated-UUID wallet drain) names a different Orchard recipient than the one the tracked lock recorded when it was built. Nothing was submitted or paid; resume with the recorded recipient, which the row and `TrackedAssetLockFFI` expose. Rows tracked before recipients were recorded carry none and accept the caller's. Typed in Rust, Swift and Kotlin | **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 ba95989bb6a..fa3374400c9 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs @@ -30,6 +30,14 @@ pub struct TrackedAssetLockFFI { pub status: u32, /// Whether a proof is attached. pub has_proof: bool, + /// Whether `shielded_recipient_raw_43` carries the Orchard recipient a + /// shielded funding (funding type 5) was built to pay. False for other + /// funding types and for shielded locks tracked before the recipient was + /// recorded (a resume of those pays the recipient the caller names). + pub has_shielded_recipient: bool, + /// 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], } /// Destroy an AssetLockManager handle. @@ -85,6 +93,11 @@ pub unsafe extern "C" fn asset_lock_manager_list_tracked_locks( AssetLockStatus::DrainCompleted => 6, }, has_proof: lock.proof.is_some(), + has_shielded_recipient: lock.shielded_recipient.is_some(), + shielded_recipient_raw_43: lock + .shielded_recipient + .map(|recipient| recipient.to_raw_bytes()) + .unwrap_or([0; 43]), } }) .collect(); diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 0039095186a..605dacf9c0d 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -622,6 +622,13 @@ pub enum PlatformWalletFFIResultCode { /// coins lets either lock fit. ErrorAssetLockTooManyInputs = 60, + /// A shielded funding is being resumed to a different Orchard recipient + /// than the one its tracked asset lock recorded when it was built. Nothing + /// 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. + ErrorAssetLockRecipientMismatch = 61, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1047,6 +1054,9 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::AssetLockTooManyInputs { .. } => { PlatformWalletFFIResultCode::ErrorAssetLockTooManyInputs } + PlatformWalletError::AssetLockRecipientMismatch { .. } => { + PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch + } // 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. @@ -2238,6 +2248,35 @@ mod tests { /// starts emitting it. The message must carry the typed `Display` — /// including the spender's finality — since that is the only detail /// channel the frozen `{ code, message }` ABI has. + /// The recipient-mismatch refusal a shielded resume raises, pinned so the + /// Swift/Kotlin mirrors decode it, together with the conversion that keeps + /// it from flattening to `ErrorUnknown`. + #[test] + fn asset_lock_recipient_mismatch_code_is_pinned_at_61() { + assert_eq!( + PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch as i32, + 61 + ); + let recorded = crate::test_fixtures::orchard_address(1); + let requested = crate::test_fixtures::orchard_address(2); + let result: PlatformWalletFFIResult = PlatformWalletError::AssetLockRecipientMismatch { + out_point: dashcore::OutPoint::null(), + recorded, + requested, + } + .into(); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch + ); + let message = message_of(&result); + assert!( + message.contains("cannot be resumed to"), + "the typed Display must survive the conversion: {message}" + ); + assert!(message.contains(&hex::encode(recorded.to_raw_bytes()))); + } + #[test] fn asset_lock_input_conflict_code_is_pinned_at_47() { use dashcore::OutPoint; diff --git a/packages/rs-platform-wallet-ffi/src/manager.rs b/packages/rs-platform-wallet-ffi/src/manager.rs index dd0675fca9f..0723585c6e2 100644 --- a/packages/rs-platform-wallet-ffi/src/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/manager.rs @@ -9,8 +9,9 @@ use crate::event_handler::{ use crate::handle::*; use crate::persistence::{ FFIPersister, FreeTrackedMasternodesFn, LoadAssetLockOperationIdFn, - LoadIdentityBalanceBlockTimeFn, LoadTrackedMasternodesFn, PersistAssetLockOperationIdFn, - PersistDpnsNameStatesFn, PersistIdentityBalanceBlockTimeFn, PersistTrackedMasternodesFn, + LoadAssetLockShieldedRecipientFn, LoadIdentityBalanceBlockTimeFn, LoadTrackedMasternodesFn, + PersistAssetLockOperationIdFn, PersistAssetLockShieldedRecipientFn, PersistDpnsNameStatesFn, + PersistIdentityBalanceBlockTimeFn, PersistTrackedMasternodesFn, PersistWalletChangesetChainLockHeightFn, PersistWalletChangesetSweepsFn, PersistWalletChangesetUtxoVerdictsFn, PersistWalletDashPayBackfillFn, PersistenceCallbacks, PersistenceCallbacksExtension, PersistenceCapabilitiesFFI, PersistenceExtensionCallbacks, @@ -290,6 +291,14 @@ unsafe fn persistence_extension_callbacks( on_load_asset_lock_operation_id_fn, LoadAssetLockOperationIdFn ), + persist_asset_lock_shielded_recipient: slot!( + on_persist_asset_lock_shielded_recipient_fn, + PersistAssetLockShieldedRecipientFn + ), + load_asset_lock_shielded_recipient: slot!( + on_load_asset_lock_shielded_recipient_fn, + LoadAssetLockShieldedRecipientFn + ), } } diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index bbc3861e23a..7c7d58b6d7d 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -10,6 +10,7 @@ //! same integers on a different callback family. use bincode::config; +use dpp::address_funds::{OrchardAddress, ORCHARD_ADDRESS_SIZE}; use key_wallet::account::account_collection::AccountCollection; use key_wallet::account::{Account, AccountType, StandardAccountType}; use key_wallet::bip32::DerivationPath; @@ -161,6 +162,13 @@ pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_TRACKED_MASTERNODES: u64 = 1 << pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_CORE_SWEEP_REMOVAL: u64 = 1 << 11; pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_DASHPAY_PAYMENTS: u64 = 1 << 12; pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_OPERATION_IDS: u64 = 1 << 13; +/// The Orchard recipient of a shielded asset-lock funding survives store and +/// load with its row (so a resume after restart pays the confirmed recipient). +/// Attested when the host wires both `on_persist_asset_lock_shielded_recipient_fn` +/// and `on_load_asset_lock_shielded_recipient_fn` next to the legacy asset-lock +/// persist/load callbacks. Reported, never required: a host without the slots +/// loads such rows with no recipient and a resume accepts the caller's. +pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS: u64 = 1 << 14; /// Version of [`PersistenceCallbacksExtension`]. The extension is deliberately /// separate from [`PersistenceCallbacks`]: existing hosts pass the latter by @@ -323,6 +331,28 @@ pub type LoadAssetLockOperationIdFn = unsafe extern "C" fn( out_operation_id: *mut u8, ) -> i32; +/// Associate the immutable raw 43-byte Orchard recipient of a shielded asset-lock +/// funding with a 36-byte raw outpoint. Runs after the legacy asset-lock upsert +/// (and the UUID sidecar), inside the same atomic changeset. All three byte +/// pointers are readable for the duration of the callback. +pub type PersistAssetLockShieldedRecipientFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + recipient_raw_43: *const u8, +) -> i32; + +/// Read the optional recipient for a restored outpoint, including consumed rows. +/// `out_recipient_raw_43` points to 43 writable bytes. An unreadable or missing +/// asset-lock row must return an error, not a successful `out_found = false`. +pub type LoadAssetLockShieldedRecipientFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_recipient_raw_43: *mut u8, +) -> i32; + /// Size- and version-tagged additive persistence callbacks. /// /// `context` is the context in the accompanying [`PersistenceCallbacks`] @@ -489,6 +519,29 @@ pub struct PersistenceCallbacksExtension { out_operation_id: *mut u8, ) -> i32, >, + /// Additive sidecar for the Orchard recipient a shielded funding was built + /// to pay (see [`PersistAssetLockShieldedRecipientFn`]). Both slots plus + /// the legacy persist/load callbacks are required before the host can + /// attest `ASSET_LOCK_SHIELDED_RECIPIENTS`. A host without them is never + /// handed a recipient and loads rows with none, as every host did before + /// the slot existed. + pub on_persist_asset_lock_shielded_recipient_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + recipient_raw_43: *const u8, + ) -> i32, + >, + pub on_load_asset_lock_shielded_recipient_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_recipient_raw_43: *mut u8, + ) -> i32, + >, } impl Default for PersistenceCallbacksExtension { @@ -509,6 +562,8 @@ impl Default for PersistenceCallbacksExtension { on_persist_wallet_dashpay_backfill_fn: None, on_persist_asset_lock_operation_id_fn: None, on_load_asset_lock_operation_id_fn: None, + on_persist_asset_lock_shielded_recipient_fn: None, + on_load_asset_lock_shielded_recipient_fn: None, } } } @@ -530,6 +585,8 @@ pub struct PersistenceExtensionCallbacks { pub wallet_dashpay_backfill: Option, pub persist_asset_lock_operation_id: Option, pub load_asset_lock_operation_id: Option, + pub persist_asset_lock_shielded_recipient: Option, + pub load_asset_lock_shielded_recipient: Option, } /// Return value by which a persistence callback reports a **retryable** @@ -1661,6 +1718,20 @@ impl FFIPersister { // tombstones and fail-closed loads. Legacy hosts do not set this bit. capabilities = capabilities.union(PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS); } + if wallet_restore + && self.callbacks.on_persist_asset_locks_fn.is_some() + && self + .tracked_masternodes_callbacks + .persist_asset_lock_shielded_recipient + .is_some() + && self + .tracked_masternodes_callbacks + .load_asset_lock_shielded_recipient + .is_some() + { + capabilities = + capabilities.union(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS); + } if self .tracked_masternodes_callbacks .persist_tracked_masternodes @@ -2693,6 +2764,42 @@ impl PlatformWalletPersistence for FFIPersister { } } } + // The shielded recipient is a second additive sidecar. Unlike the + // UUID, a host without the slot is not failed: every Type 18 + // funding now carries a recipient, and a host that cannot keep it + // simply resumes as it always did (the caller names the recipient). + if let Some(cb) = self + .tracked_masternodes_callbacks + .persist_asset_lock_shielded_recipient + { + for entry in al_cs.asset_locks.values() { + let Some(recipient) = entry.shielded_recipient else { + continue; + }; + let out_point = outpoint_to_bytes(&entry.out_point); + let recipient = recipient.to_raw_bytes(); + let rc = unsafe { + cb( + self.callbacks.context, + wallet_id.as_ptr(), + out_point.as_ptr(), + recipient.as_ptr(), + ) + }; + if rc != 0 { + outcome.record(rc); + } + } + } else if al_cs + .asset_locks + .values() + .any(|entry| entry.shielded_recipient.is_some()) + { + tracing::debug!( + "host has no shielded-recipient persistence slot; the recipient of a \ + shielded asset-lock funding is not persisted with its row" + ); + } } // Send invitation changeset — DIP-13 sent-invitation records, one @@ -3480,6 +3587,17 @@ impl PlatformWalletPersistence for FFIPersister { &mut wallet_state.unused_asset_locks, )?; } + if let Some(cb) = self + .tracked_masternodes_callbacks + .load_asset_lock_shielded_recipient + { + load_asset_lock_shielded_recipients( + cb, + self.callbacks.context, + &entry.wallet_id, + &mut wallet_state.unused_asset_locks, + )?; + } if let Some(cb) = self.load_identity_balance_block_time_callback { for identities in wallet_state.identity_manager.wallet_identities.values_mut() { for managed in identities.values_mut() { @@ -6251,6 +6369,48 @@ fn load_asset_lock_operation_ids( Ok(()) } +/// Rehydrate the shielded-recipient sidecar after decoding the frozen legacy +/// rows. A failed read or a byte string that is not an Orchard address +/// invalidates the whole load: a row that silently lost its recipient would +/// let a resume pay whatever the caller names. +fn load_asset_lock_shielded_recipients( + callback: LoadAssetLockShieldedRecipientFn, + context: *mut c_void, + wallet_id: &WalletId, + locks: &mut BTreeMap>, +) -> 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; ORCHARD_ADDRESS_SIZE]; + let rc = unsafe { + callback( + context, + wallet_id.as_ptr(), + out_point.as_ptr(), + &mut found, + raw.as_mut_ptr(), + ) + }; + if rc != 0 { + return Err(persist_callback_error( + rc, + "Loading asset-lock shielded recipient failed", + )); + } + lock.shielded_recipient = if found { + Some(OrchardAddress::from_raw_bytes(&raw).map_err(|error| { + PersistenceError::backend(format!( + "tracked asset locks: stored shielded recipient is not an Orchard address: {error}" + )) + })?) + } else { + None + }; + } + Ok(()) +} + /// Rebuild tracked locks from the host's frozen `AssetLockEntryFFI` rows. /// Transactions use consensus encoding, proofs use DPP bincode, and outpoints /// are raw txid bytes followed by a little-endian vout. Malformed or duplicate @@ -6354,6 +6514,7 @@ fn build_unused_asset_locks( identity_index: spec.identity_index, amount: spec.amount_duffs, operation_id: None, + shielded_recipient: None, status, proof, }; @@ -9831,6 +9992,7 @@ mod tests { status: status.clone(), proof: None, operation_id, + shielded_recipient: None, }; let (entries, _storage) = build_asset_lock_entries(&[&entry]); let wallet = WalletRestoreEntryFFI { @@ -9912,6 +10074,162 @@ mod tests { } } + /// The recipient sidecar round-trips next to the frozen row: a host with + /// the slots gets every recorded recipient on store and hands it back on + /// load; a host without the slots is not failed (the row stores, the + /// recipient is simply absent after load) and never attests the bit. + #[test] + fn should_roundtrip_shielded_recipients_and_tolerate_a_host_without_the_slots() { + use dashcore::hashes::Hash; + use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; + + let recipient = crate::test_fixtures::orchard_address(0x33); + let raw = recipient.to_raw_bytes(); + 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; 43]>); + *found = stored.is_some(); + if let Some(stored) = stored { + std::ptr::copy_nonoverlapping(stored.as_ptr(), output, 43); + } + 0 + } + let entry = platform_wallet::changeset::AssetLockEntry { + out_point: dashcore::OutPoint { + txid: dashcore::Txid::from_byte_array([4; 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::AssetLockShieldedAddressTopUp, + identity_index: 0, + amount_duffs: 1000, + status: platform_wallet::AssetLockStatus::Broadcast, + proof: None, + operation_id: None, + shielded_recipient: Some(recipient), + }; + 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].shielded_recipient, None, + "legacy ABI has no recipient field" + ); + for stored in [None, Some(raw)] { + load_asset_lock_shielded_recipients( + load_recipient, + (&stored as *const Option<[u8; 43]>).cast_mut().cast(), + &[42; 32], + &mut restored, + ) + .expect("valid recipient sidecar"); + assert_eq!( + restored[&2][&entry.out_point].shielded_recipient, + stored.map(|_| recipient) + ); + } + let garbage: Option<[u8; 43]> = Some([0xff; 43]); + assert!(load_asset_lock_shielded_recipients( + load_recipient, + (&garbage as *const Option<[u8; 43]>).cast_mut().cast(), + &[42; 32], + &mut restored, + ) + .is_err()); + + 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()); + legacy + .store([42; 32], changeset.clone()) + .expect("a host without the recipient slot still stores the row"); + assert!(!legacy + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_SHIELDED_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, 43); + *(context as *mut Option<[u8; 43]>) = Some(seen.try_into().unwrap()); + 0 + } + let mut seen: Option<[u8; 43]> = None; + let extensions = PersistenceExtensionCallbacks { + persist_asset_lock_shielded_recipient: Some(persist_recipient), + load_asset_lock_shielded_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_SHIELDED_RECIPIENTS, + extensions, + ); + assert!(writer + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS)); + writer + .store([42; 32], changeset) + .expect("recipient sidecar persisted with the base row"); + assert_eq!(seen, Some(raw)); + for incomplete in [ + PersistenceExtensionCallbacks { + persist_asset_lock_shielded_recipient: None, + ..extensions + }, + PersistenceExtensionCallbacks { + load_asset_lock_shielded_recipient: None, + ..extensions + }, + ] { + assert!( + !FFIPersister::new_with_persistence_capabilities_and_extensions( + callbacks(), + PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS, + incomplete, + ) + .persistence_capabilities() + .contains(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS) + ); + } + } + #[test] fn should_require_explicit_operation_id_persistence_attestation() { unsafe extern "C" fn persist( @@ -10284,6 +10602,26 @@ mod tests { PersistenceCallbacksExtension, on_load_asset_lock_operation_id_fn ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_asset_lock_shielded_recipient_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_asset_lock_shielded_recipient_fn + ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_asset_lock_shielded_recipient_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_asset_lock_shielded_recipient_fn + ) + std::mem::size_of::>(), std::mem::size_of::() ); assert_eq!( @@ -10346,6 +10684,10 @@ mod tests { PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_OPERATION_IDS, PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS.bits() ); + assert_eq!( + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS, + PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS.bits() + ); assert_eq!( PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ACCOUNT_ADDRESS_POOLS, PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_FUNDING_INDICES @@ -12647,6 +12989,7 @@ mod tests { status: platform_wallet::AssetLockStatus::Consumed, proof: None, operation_id: None, + shielded_recipient: None, }; let out_point = entry.out_point; let host = Arc::new(Host { diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 478d7fae658..a4dd23e89df 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -849,7 +849,8 @@ fn map_asset_lock_funding_result( Err(e @ PlatformWalletError::AssetLockAlreadyConsumed(_)) => e.into(), Err( e @ (PlatformWalletError::AssetLockNotTracked(_) - | PlatformWalletError::AssetLockFundingMismatch { .. }), + | PlatformWalletError::AssetLockFundingMismatch { .. } + | PlatformWalletError::AssetLockRecipientMismatch { .. }), ) => e.into(), Err( e @ (PlatformWalletError::AssetLockInputConflict { .. } @@ -3118,6 +3119,23 @@ mod tests { ); assert!(message_of(¬_tracked).contains("is not tracked by this wallet")); + // A resume naming another recipient than the row recorded is the one + // refusal a host must render as "wrong destination", never as a + // generic operation failure. + let recipient_mismatch = map_asset_lock_funding_result( + Err(PlatformWalletError::AssetLockRecipientMismatch { + out_point, + recorded: crate::test_fixtures::orchard_address(1), + requested: crate::test_fixtures::orchard_address(2), + }), + "shielded resume fund-from-asset-lock", + ); + assert_eq!( + recipient_mismatch.code, + PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch + ); + assert!(message_of(&recipient_mismatch).contains("cannot be resumed to")); + let mismatch = map_asset_lock_funding_result( Err(PlatformWalletError::AssetLockFundingMismatch { out_point, diff --git a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs index d41459b6586..b9154222aa1 100644 --- a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs +++ b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs @@ -72,3 +72,14 @@ pub(crate) fn out_string( unsafe { platform_wallet_free_string(out) }; Ok(Some(string)) } + +/// A valid Orchard payment address, deterministic in `seed_byte`: the +/// external address at diversifier index 0 of the spending key whose 32 +/// bytes all equal `seed_byte`. Two seed bytes give two different addresses. +pub(crate) fn orchard_address(seed_byte: u8) -> dpp::address_funds::OrchardAddress { + use dash_sdk::grovedb_commitment_tree::{FullViewingKey, Scope, SpendingKey}; + let spending_key = + SpendingKey::from_bytes([seed_byte; 32]).expect("a constant spending key is on the curve"); + let full_viewing_key = FullViewingKey::from(&spending_key); + dpp::address_funds::OrchardAddress::from(full_viewing_key.address_at(0u32, Scope::External)) +} diff --git a/packages/rs-platform-wallet-storage/SCHEMA.md b/packages/rs-platform-wallet-storage/SCHEMA.md index 899d88a0c7f..94485778a6c 100644 --- a/packages/rs-platform-wallet-storage/SCHEMA.md +++ b/packages/rs-platform-wallet-storage/SCHEMA.md @@ -850,3 +850,4 @@ table-rebuild migration, as V004 does. | V017 | `V017__identity_scan_state.rs` | Adds `identity_scan_states` (one row per wallet: the last gap-limit identity-scan verdict — `complete`, `probed_from`/`probed_through`, `unlocated_gap`) and `identity_scan_failed_indices` (indices probed without an answer, cascading from the verdict row via `wallet_id`). Purely additive; an upgraded database reads back "no verdict recorded" for every wallet until the next scan (dashpay/platform#4365). | | 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. | diff --git a/packages/rs-platform-wallet-storage/migrations/V020__asset_lock_shielded_recipient.rs b/packages/rs-platform-wallet-storage/migrations/V020__asset_lock_shielded_recipient.rs new file mode 100644 index 00000000000..1d8f3837216 --- /dev/null +++ b/packages/rs-platform-wallet-storage/migrations/V020__asset_lock_shielded_recipient.rs @@ -0,0 +1,12 @@ +//! The Orchard recipient a shielded asset-lock funding was built to pay, so a +//! resume after restart pays the recipient the user confirmed. Legacy blobs +//! stay byte-identical; old rows receive NULL and keep accepting the +//! resuming caller's recipient. +pub fn migration() -> String { + "ALTER TABLE asset_locks ADD COLUMN shielded_recipient BLOB \ + CHECK (shielded_recipient IS NULL OR (typeof(shielded_recipient) = 'blob' AND length(shielded_recipient) = 43)); \ + CREATE TRIGGER asset_locks_shielded_recipient_immutable \ + BEFORE UPDATE OF shielded_recipient ON asset_locks \ + WHEN OLD.shielded_recipient IS NOT NULL AND NEW.shielded_recipient IS NOT OLD.shielded_recipient \ + BEGIN SELECT RAISE(ABORT, 'asset lock shielded recipient cannot change'); END;".to_owned() +} 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 6256705bfbb..e7c6a96294d 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,6 +13,7 @@ use rusqlite::{params, OptionalExtension, Transaction}; use serde::{Deserialize, Serialize}; +use dpp::address_funds::{OrchardAddress, ORCHARD_ADDRESS_SIZE}; use dpp::prelude::AssetLockProof; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use platform_wallet::changeset::AssetLockChangeSet; @@ -62,6 +63,7 @@ impl_persistable_blob!(AssetLockEntryWire); /// Nullable recovery columns read independently of the frozen lifecycle blob. struct AssetLockRecoveryRow { operation_id: Option>, + shielded_recipient: Option>, lifecycle_blob: Vec, } @@ -121,6 +123,7 @@ impl AssetLockEntryWire { status: self.status, proof, operation_id: None, + shielded_recipient: None, }) } } @@ -147,30 +150,33 @@ 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) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) \ + (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) \ ON CONFLICT(wallet_id, outpoint) DO UPDATE SET \ status = excluded.status, \ account_index = excluded.account_index, \ identity_index = excluded.identity_index, \ amount_duffs = excluded.amount_duffs, \ lifecycle_blob = excluded.lifecycle_blob, \ - operation_id = COALESCE(excluded.operation_id, asset_locks.operation_id) \ + operation_id = COALESCE(excluded.operation_id, asset_locks.operation_id), \ + shielded_recipient = COALESCE(excluded.shielded_recipient, asset_locks.shielded_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, lifecycle_blob FROM asset_locks WHERE wallet_id = ?1 AND outpoint = ?2", + "SELECT operation_id, shielded_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)?, - lifecycle_blob: row.get(1)?, + shielded_recipient: row.get(1)?, + lifecycle_blob: row.get(2)?, }), ).optional()?; - // The operation UUID is immutable once stored. Reject the whole - // snapshot before any lifecycle or sidecar write. + // The operation UUID and the shielded recipient are immutable once + // stored. Reject the whole snapshot before any lifecycle or + // sidecar write. if let (Some(incoming), Some(stored)) = ( entry.operation_id.as_ref(), existing @@ -183,6 +189,21 @@ pub fn apply( )); } } + let shielded_recipient = entry + .shielded_recipient + .map(|recipient| recipient.to_raw_bytes()); + if let (Some(incoming), Some(stored)) = ( + shielded_recipient.as_ref(), + existing + .as_ref() + .and_then(|row| row.shielded_recipient.as_deref()), + ) { + if incoming.as_slice() != stored { + return Err(WalletStorageError::blob_decode( + "asset lock shielded 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 { @@ -205,6 +226,9 @@ pub fn apply( )?, lifecycle_blob, entry.operation_id.as_ref().map(|id| id.as_slice()), + shielded_recipient + .as_ref() + .map(|recipient| recipient.as_slice()), ])?; } } @@ -299,6 +323,7 @@ fn decode_row( blob_bytes: &[u8], typed_status: &str, operation_id: Option>, + shielded_recipient: Option>, ctx: &LoadCtx, ) -> Result<(u32, OutPoint, TrackedAssetLock), WalletStorageError> { let outpoint = blob::decode_outpoint(op_bytes)?; @@ -311,6 +336,20 @@ fn decode_row( }) }) .transpose()?; + entry.shielded_recipient = shielded_recipient + .map(|bytes| { + let raw: [u8; ORCHARD_ADDRESS_SIZE] = bytes.try_into().map_err(|_| { + WalletStorageError::blob_decode( + "asset_locks.shielded_recipient must contain 43 bytes", + ) + })?; + OrchardAddress::from_raw_bytes(&raw).map_err(|_| { + WalletStorageError::blob_decode( + "asset_locks.shielded_recipient is not a valid Orchard address", + ) + }) + }) + .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 @@ -353,6 +392,7 @@ fn decode_row( status: entry.status, proof: entry.proof, operation_id: entry.operation_id, + shielded_recipient: entry.shielded_recipient, }; Ok((account_index, outpoint, tracked)) } @@ -368,7 +408,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 \ + "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_recipient \ FROM asset_locks WHERE wallet_id = ?1", )?; let mut rows = stmt.query(params![wallet_id.as_slice()])?; @@ -381,12 +421,14 @@ pub fn load_state( 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 (acct, outpoint, tracked) = decode_row( &op_bytes, account_index, &blob_bytes, &status, operation_id, + shielded_recipient, ctx, )?; out.entry(acct).or_default().insert(outpoint, tracked); @@ -407,7 +449,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 \ + "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_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()])?; @@ -420,12 +462,14 @@ pub fn load_unconsumed( 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 (acct, outpoint, tracked) = decode_row( &op_bytes, account_index, &blob_bytes, &status, operation_id, + shielded_recipient, ctx, )?; if tracked.status.is_consumed() && tracked.operation_id.is_none() { @@ -492,6 +536,7 @@ mod tests { funding_type: AssetLockFundingType::IdentityRegistration, identity_index: 0, operation_id: None, + shielded_recipient: None, amount_duffs: 1000, status, proof, @@ -530,6 +575,7 @@ mod tests { status: tracked.status, proof: tracked.proof, operation_id: tracked.operation_id, + shielded_recipient: tracked.shielded_recipient, }) .expect("stored asset lock must load back") } @@ -720,6 +766,7 @@ mod tests { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_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 b3cac135312..0abc5fac2fe 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 @@ -36,6 +36,7 @@ fn entry(op: OutPoint, status: AssetLockStatus) -> AssetLockEntry { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_recipient: None, amount_duffs: 1000, status, proof: None, @@ -340,3 +341,97 @@ fn should_reject_conflicting_operation_id_before_mutating_any_stored_columns() { ); } } + +#[test] +fn should_preserve_shielded_recipient_when_later_snapshot_lacks_it_and_reject_a_change() { + let (persister, _tmp, path) = fresh_persister(); + let w = wid(0xA9); + ensure_wallet_meta(&persister, &w); + let outpoint = op(0x35); + let recipient = orchard_address(0x11); + 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 mut recorded = entry(outpoint, AssetLockStatus::Built); + recorded.shielded_recipient = Some(recipient); + store(&persister, recorded).unwrap(); + // A later snapshot without the recipient (a status advance) keeps it. + store(&persister, entry(outpoint, AssetLockStatus::Broadcast)).unwrap(); + // A snapshot naming another recipient is refused before any write. + let mut redirected = entry(outpoint, AssetLockStatus::ChainLocked); + redirected.shielded_recipient = Some(orchard_address(0x12)); + 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.shielded_recipient, Some(recipient)); + assert_eq!(restored.status, AssetLockStatus::Broadcast); + // The column refuses any length but 43 and never changes once set. + assert!(conn + .execute( + "UPDATE asset_locks SET shielded_recipient = ?1", + [vec![1_u8; 42]] + ) + .is_err()); + assert!(conn + .execute( + "UPDATE asset_locks SET shielded_recipient = ?1", + [orchard_address(0x13).to_raw_bytes().to_vec()] + ) + .is_err()); +} + +#[test] +fn should_fail_the_load_when_a_stored_shielded_recipient_is_not_an_orchard_address() { + let (persister, _tmp, _) = fresh_persister(); + let w = wid(0xAB); + ensure_wallet_meta(&persister, &w); + let outpoint = op(0x36); + 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(); + // 43 bytes whose pk_d is not a Pallas point: the CHECK and the + // immutability trigger (OLD is NULL) both let it in. + conn.execute( + "UPDATE asset_locks SET shielded_recipient = ?1", + [vec![0xff_u8; 43]], + ) + .unwrap(); + assert!( + asset_locks::load_unconsumed(&conn, &w, &platform_wallet_storage::LoadCtx::strict()) + .is_err() + ); +} + +fn orchard_address(seed_byte: u8) -> dpp::address_funds::OrchardAddress { + use dash_sdk::grovedb_commitment_tree::{FullViewingKey, Scope, SpendingKey}; + let spending_key = SpendingKey::from_bytes([seed_byte; 32]).unwrap(); + let full_viewing_key = FullViewingKey::from(&spending_key); + dpp::address_funds::OrchardAddress::from(full_viewing_key.address_at(0u32, Scope::External)) +} 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 c0235fc8e5e..fb5fcf8a0c4 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) - funding_type: AssetLockFundingType::IdentityRegistration, identity_index: 0, operation_id: None, + shielded_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 4206b1db3bc..314506b9a1f 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() { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_recipient: None, amount_duffs: 1000, status: AssetLockStatus::Built, proof: None, @@ -1394,6 +1395,7 @@ fn tc_p4_008c_asset_locks_corruption_is_hard_error() { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_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 d13e50be66f..ed006a4c7c9 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() { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 9, operation_id: None, + shielded_recipient: None, amount_duffs: 12_345, status: AssetLockStatus::Built, proof: None, @@ -474,6 +475,7 @@ fn tc010b_recovered_from_chain_lock_roundtrip() { funding_type: AssetLockFundingType::AssetLockShieldedAddressTopUp, identity_index: 0, operation_id: None, + shielded_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() { funding_type: AssetLockFundingType::IdentityRegistration, identity_index: 0, operation_id: None, + shielded_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 a2f518dcf97..a6340e12139 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( funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_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 b4ef31e3c31..f1c5755c448 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 = - "5f6d87af51ff949ecf5058c9e1086dc7624f5d6955164e19be33bc460132776b"; + "b1e10a6494cc31d24fabe4852477b3b93a2a98a7f310681b132ca8d9adef7311"; /// 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 = - "3a3e9b2df9b1dde2664ae086a6bd53a30b57208024662b917698184761f14515"; + "4490b15ba9de27bf5b30a47e462dc3b71c061a47f738a5240cdc89b3abc4ff43"; /// 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 414f37074d4..29ca17c0246 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 @@ -381,6 +381,7 @@ fn asset_lock_typed_vs_blob_mismatch_rejected() { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_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 73d2437db0b..090b606f1c1 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 @@ -367,6 +367,7 @@ fn asset_lock_changeset() -> AssetLockChangeSet { funding_type: AssetLockFundingType::IdentityTopUp, identity_index: 0, operation_id: None, + shielded_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 e8beae1b385..725ab92cba6 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -27,6 +27,7 @@ use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::Txid; use dash_sdk::platform::address_sync::AddressFunds; +use dpp::address_funds::OrchardAddress; use dpp::prelude::AssetLockProof; use key_wallet::account::AccountType; use key_wallet::bip32::ExtendedPubKey; @@ -1527,17 +1528,30 @@ pub struct AssetLockEntry { serde(with = "crate::changeset::serde_adapters::optional_asset_lock_proof") )] pub proof: Option, + /// The Orchard recipient a shielded funding was built to pay (raw 43-byte + /// address); `None` for other funding types and for legacy rows. Like + /// `operation_id`, immutable once recorded. + #[cfg_attr( + feature = "serde", + serde( + default, + with = "crate::changeset::serde_adapters::optional_orchard_address" + ) + )] + pub shielded_recipient: Option, } impl AssetLockEntry { - /// Preserve the immutable operation association when folding or replaying - /// a possibly stale snapshot. Returns false for a conflicting UUID: the - /// caller must discard the whole snapshot so its lifecycle cannot be - /// attached to a different operation. + /// Preserve the immutable operation association and shielded recipient + /// 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. #[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, ) -> bool { if let Some(previous_id) = previous_operation_id { if self @@ -1549,6 +1563,16 @@ impl AssetLockEntry { } self.operation_id = Some(previous_id); } + if let Some(previous_recipient) = previous_shielded_recipient { + if self + .shielded_recipient + .is_some_and(|incoming| incoming != previous_recipient) + { + tracing::warn!(out_point = %self.out_point, "Ignoring asset-lock snapshot with a conflicting shielded recipient"); + return false; + } + self.shielded_recipient = Some(previous_recipient); + } true } } @@ -1570,15 +1594,18 @@ 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) { + if !entry + .preserve_recovery_metadata(existing.operation_id, existing.shielded_recipient) + { continue; } if existing.status == AssetLockStatus::DrainCompleted || (existing.status.is_consumed() && !entry.status.is_consumed()) { // Terminality guards lifecycle state, never the operation - // association carried by a delayed snapshot. + // association or recipient carried by a delayed snapshot. existing.operation_id = entry.operation_id; + existing.shielded_recipient = entry.shielded_recipient; continue; } } @@ -2740,6 +2767,7 @@ mod tests { }; let entry_with = |status: AssetLockStatus| AssetLockEntry { operation_id: None, + shielded_recipient: None, out_point: outpoint, transaction: Transaction { version: 3, @@ -2808,6 +2836,34 @@ mod tests { AssetLockStatus::Consumed ); + // The recorded shielded recipient survives a later snapshot without + // one (reconstruction, a status advance) and vetoes a conflicting one. + let recipient = crate::test_support::orchard_address_fixture(0x71); + let mut recorded = cs_with(AssetLockStatus::Broadcast); + recorded + .asset_locks + .get_mut(&outpoint) + .unwrap() + .shielded_recipient = Some(recipient); + recorded.merge(cs_with(AssetLockStatus::RecoveredFromChain)); + assert_eq!( + recorded.asset_locks[&outpoint].shielded_recipient, + Some(recipient) + ); + assert_eq!( + recorded.asset_locks[&outpoint].status, + AssetLockStatus::RecoveredFromChain + ); + let mut redirected = cs_with(AssetLockStatus::ChainLocked); + redirected + .asset_locks + .get_mut(&outpoint) + .unwrap() + .shielded_recipient = Some(crate::test_support::orchard_address_fixture(0x72)); + 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). @@ -3455,6 +3511,7 @@ mod tests { OutPoint::default(), AssetLockEntry { operation_id: None, + shielded_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 ff7fbe734f8..4ca79fc63a1 100644 --- a/packages/rs-platform-wallet/src/changeset/core_bridge.rs +++ b/packages/rs-platform-wallet/src/changeset/core_bridge.rs @@ -7952,6 +7952,7 @@ mod tests { out_point, AssetLockEntry { operation_id: None, + shielded_recipient: None, out_point, transaction: dashcore::Transaction { version: 3, diff --git a/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs b/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs index 6c17b550b1e..afa30546b9a 100644 --- a/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs +++ b/packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs @@ -111,13 +111,20 @@ impl PersistenceCapabilities { /// empty result. Required before a wallet drain can treat absence as not sent. pub const ASSET_LOCK_OPERATION_IDS: Self = Self(1 << 13); + /// The Orchard recipient of a shielded asset-lock funding survives + /// store/load with its row, so a resume after restart pays the recipient + /// the user confirmed. Reported, not required: a backend without it loads + /// such rows with no recipient, and a resume then accepts the caller's + /// (the pre-recipient behaviour). + pub const ASSET_LOCK_SHIELDED_RECIPIENTS: Self = Self(1 << 14); + /// 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 = 13; + const HIGHEST_DECLARED_BIT: u32 = 14; /// Capabilities required before exporting and funding an invitation voucher. pub const INVITATION_CREATION: Self = Self( @@ -221,6 +228,10 @@ impl PersistenceCapabilities { PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS, "asset_lock_operation_ids", ), + ( + PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS, + "asset_lock_shielded_recipients", + ), ]; KNOWN @@ -238,7 +249,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::ASSET_LOCK_OPERATION_IDS.bits() + PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS.bits() == 1u64 << PersistenceCapabilities::HIGHEST_DECLARED_BIT, "HIGHEST_DECLARED_BIT must name the highest declared capability bit" ); @@ -270,6 +281,10 @@ mod tests { PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS.bits(), 0x2000 ); + assert_eq!( + PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS.bits(), + 0x4000 + ); assert_eq!(PersistenceCapabilities::WALLET_DRAIN.bits(), 0x2285); assert_eq!( PersistenceCapabilities::ASSET_LOCK_RECONCILIATION.bits(), diff --git a/packages/rs-platform-wallet/src/changeset/serde_adapters.rs b/packages/rs-platform-wallet/src/changeset/serde_adapters.rs index a4dddbd2092..2a992579115 100644 --- a/packages/rs-platform-wallet/src/changeset/serde_adapters.rs +++ b/packages/rs-platform-wallet/src/changeset/serde_adapters.rs @@ -6,6 +6,7 @@ //! `changeset/mod.rs`). use dash_sdk::platform::address_sync::AddressFunds; +use dpp::address_funds::OrchardAddress; use dpp::balances::credits::Credits; use dpp::prelude::AddressNonce; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -208,3 +209,88 @@ mod optional_asset_lock_proof_tests { ); } } + +/// Adapter for `Option` (upstream has no serde derive, and +/// serde has no impl for `[u8; 43]`). +/// +/// Encodes the raw 43-byte Orchard address as `Option>` — the same +/// bytes `OrchardAddress::to_raw_bytes` gives and every FFI surface already +/// carries (`recipient_raw_43`). Decoding re-validates the Pallas point +/// through `from_raw_bytes`, so a corrupted blob fails loudly instead of +/// yielding an address nothing can pay. +pub mod optional_orchard_address { + use super::*; + use dpp::address_funds::ORCHARD_ADDRESS_SIZE; + + pub fn serialize( + value: &Option, + serializer: S, + ) -> Result { + value + .map(|address| address.to_raw_bytes().to_vec()) + .serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let bytes = Option::>::deserialize(deserializer)?; + bytes + .map(|bytes| { + let raw: [u8; ORCHARD_ADDRESS_SIZE] = + bytes.as_slice().try_into().map_err(|_| { + serde::de::Error::custom(format!( + "shielded recipient must be {ORCHARD_ADDRESS_SIZE} bytes, got {}", + bytes.len() + )) + })?; + OrchardAddress::from_raw_bytes(&raw).map_err(serde::de::Error::custom) + }) + .transpose() + } +} + +#[cfg(all(test, feature = "shielded"))] +mod optional_orchard_address_tests { + use dpp::address_funds::OrchardAddress; + + #[derive(serde::Serialize, serde::Deserialize)] + struct Carrier { + #[serde(with = "super::optional_orchard_address")] + recipient: Option, + } + + fn roundtrip(recipient: Option) -> Result, String> { + let bytes = dpp::bincode::serde::encode_to_vec( + Carrier { recipient }, + dpp::bincode::config::standard(), + ) + .map_err(|e| e.to_string())?; + let (carrier, _): (Carrier, usize) = + dpp::bincode::serde::decode_from_slice(&bytes, dpp::bincode::config::standard()) + .map_err(|e| e.to_string())?; + Ok(carrier.recipient) + } + + #[test] + fn should_roundtrip_a_recipient_and_none() { + let recipient = crate::test_support::orchard_address_fixture(1); + assert_eq!(roundtrip(Some(recipient)).unwrap(), Some(recipient)); + assert_eq!(roundtrip(None).unwrap(), None); + } + + #[test] + fn should_reject_a_wrong_length_or_invalid_recipient() { + let encode = |bytes: Vec| { + dpp::bincode::serde::encode_to_vec((Some(bytes),), dpp::bincode::config::standard()) + .unwrap() + }; + for bytes in [vec![0u8; 42], vec![0u8; 44], vec![0xffu8; 43]] { + let result: Result<(Carrier, usize), _> = dpp::bincode::serde::decode_from_slice( + &encode(bytes), + dpp::bincode::config::standard(), + ); + assert!(result.is_err()); + } + } +} diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 2a3c9432751..4cf1a2d20f4 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -633,6 +633,22 @@ pub enum PlatformWalletError { #[error("Asset lock requires {count} inputs, exceeding the limit of {max}")] AssetLockTooManyInputs { count: usize, max: usize }, + /// A shielded funding is being resumed to a different Orchard recipient + /// than the one its tracked asset lock recorded when it was built. The + /// recorded recipient is the one the user confirmed; the resume pays + /// nobody. Resume with the recorded recipient instead. Rows tracked + /// before the recipient was recorded carry none and accept the caller's. + #[error( + "Asset lock {out_point} was built to pay shielded recipient {} and cannot be resumed to {}", + hex::encode(recorded.to_raw_bytes()), + hex::encode(requested.to_raw_bytes()) + )] + AssetLockRecipientMismatch { + out_point: dashcore::OutPoint, + recorded: dpp::address_funds::OrchardAddress, + requested: dpp::address_funds::OrchardAddress, + }, + #[error("SDK error: {0}")] Sdk(#[from] dash_sdk::Error), diff --git a/packages/rs-platform-wallet/src/test_support.rs b/packages/rs-platform-wallet/src/test_support.rs index 1cdd2b24fef..d293bcc57c3 100644 --- a/packages/rs-platform-wallet/src/test_support.rs +++ b/packages/rs-platform-wallet/src/test_support.rs @@ -957,6 +957,19 @@ pub(crate) async fn platform_wallet_in( ) } +/// A valid Orchard payment address, deterministic in `seed_byte`, for tests +/// that need a recipient without a shielded key set: the external address +/// at diversifier index 0 of the spending key whose 32 bytes all equal +/// `seed_byte`. Two different seed bytes give two different addresses. +#[cfg(all(test, feature = "shielded"))] +pub fn orchard_address_fixture(seed_byte: u8) -> dpp::address_funds::OrchardAddress { + use grovedb_commitment_tree::{FullViewingKey, Scope, SpendingKey}; + let spending_key = + SpendingKey::from_bytes([seed_byte; 32]).expect("a constant spending key is on the curve"); + let full_viewing_key = FullViewingKey::from(&spending_key); + dpp::address_funds::OrchardAddress::from(full_viewing_key.address_at(0u32, Scope::External)) +} + /// Thread-scoped `tracing` event capture for tests that assert on log output. /// /// Every capturing test must route through the one globally-installed diff --git a/packages/rs-platform-wallet/src/wallet/apply.rs b/packages/rs-platform-wallet/src/wallet/apply.rs index 25b8022e280..4521cfa3b68 100644 --- a/packages/rs-platform-wallet/src/wallet/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/apply.rs @@ -361,13 +361,17 @@ impl PlatformWalletInfo { if let Some(al_cs) = asset_locks { for (out_point, mut entry) in al_cs.asset_locks { if let Some(existing) = self.tracked_asset_locks.get_mut(&out_point) { - if !entry.preserve_recovery_metadata(existing.operation_id) { + if !entry.preserve_recovery_metadata( + existing.operation_id, + existing.shielded_recipient, + ) { continue; } if existing.status == AssetLockStatus::DrainCompleted || (existing.status.is_consumed() && !entry.status.is_consumed()) { existing.operation_id = entry.operation_id; + existing.shielded_recipient = entry.shielded_recipient; continue; } } @@ -383,6 +387,7 @@ impl PlatformWalletInfo { amount: entry.amount_duffs, status: entry.status, proof: entry.proof, + shielded_recipient: entry.shielded_recipient, }, ); } @@ -750,6 +755,7 @@ mod tests { out_point, AssetLockEntry { operation_id: None, + shielded_recipient: None, out_point, transaction: dashcore::Transaction { version: 3, @@ -827,6 +833,7 @@ mod tests { amount_duffs: 5_000, status, proof: None, + shielded_recipient: None, } } @@ -876,6 +883,34 @@ mod tests { assert_eq!(restored.status, AssetLockStatus::ChainLocked); } + #[test] + fn should_preserve_the_shielded_recipient_when_applying_stale_snapshots() { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + let recipient = crate::test_support::orchard_address_fixture(0x81); + let mut recorded = recovery_asset_lock(AssetLockStatus::Broadcast, None); + recorded.shielded_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.shielded_recipient, Some(recipient)); + assert_eq!(restored.status, AssetLockStatus::RecoveredFromChain); + + // A snapshot naming another recipient is dropped whole. + let mut redirected = recovery_asset_lock(AssetLockStatus::ChainLocked, None); + redirected.shielded_recipient = Some(crate::test_support::orchard_address_fixture(0x82)); + apply_recovery_asset_lock(&mut info, &mut wallet, redirected); + let restored = &info.tracked_asset_locks[&OutPoint::default()]; + assert_eq!(restored.shielded_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 e25b9154037..7ea0c5505fa 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs @@ -8,6 +8,7 @@ use std::time::Duration; use dashcore::Address as DashAddress; use dashcore::{OutPoint, Transaction, TxOut}; +use dpp::address_funds::OrchardAddress; use key_wallet::account::AccountType; use key_wallet::bip32::DerivationPath; use key_wallet::managed_account::address_pool::AddressState; @@ -928,6 +929,7 @@ impl AssetLockManager { account_index, funding_type, identity_index, + None, signer, None, ) @@ -936,12 +938,14 @@ impl AssetLockManager { /// [`Self::create_funded_asset_lock_proof`] that reports the built lock's /// outpoint to `on_built` (see [`AssetLockBuiltObserver`]). + #[allow(clippy::too_many_arguments)] pub(super) async fn create_funded_asset_lock_proof_observed( &self, amount_duffs: u64, account_index: u32, funding_type: AssetLockFundingType, identity_index: u32, + shielded_recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -951,6 +955,7 @@ impl AssetLockManager { account_index, funding_type, identity_index, + shielded_recipient, signer, on_built, ) @@ -976,6 +981,7 @@ impl AssetLockManager { funding_account, funding_type, identity_index, + None, signer, None, ) @@ -984,6 +990,7 @@ impl AssetLockManager { /// [`Self::create_funded_asset_lock_proof_with_funding`] that reports the /// built lock's outpoint to `on_built` (see [`AssetLockBuiltObserver`]). + #[allow(clippy::too_many_arguments)] pub(super) async fn create_funded_asset_lock_proof_with_funding_observed< S: ExtendedPubKeySigner, >( @@ -992,6 +999,7 @@ impl AssetLockManager { funding_account: AssetLockFundingAccount, funding_type: AssetLockFundingType, identity_index: u32, + shielded_recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -1001,6 +1009,7 @@ impl AssetLockManager { funding_account.account_index(), funding_type, identity_index, + shielded_recipient, signer, on_built, ) @@ -1022,17 +1031,20 @@ impl AssetLockManager { source_index: u32, funding_type: AssetLockFundingType, identity_index: u32, + shielded_recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { let (path, out_point) = self - .broadcast_funded_asset_lock_with_funding( + .broadcast_funded_asset_lock_tracked( amount, funding_sources, source_index, funding_type, identity_index, + shielded_recipient, signer, + None, on_built, ) .await?; @@ -1108,18 +1120,20 @@ impl AssetLockManager { minimum_lock_duffs: Option, funding_type: AssetLockFundingType, identity_index: u32, + shielded_recipient: Option, signer: &S, operation: &AssetLockOperationContext, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { self.require_wallet_drain_persistence()?; let (path, out_point) = self - .broadcast_funded_asset_lock_with_operation( + .broadcast_funded_asset_lock_tracked( AssetLockBuildAmount::DrainAll { minimum_lock_duffs }, &ASSET_LOCK_FUNDING_SOURCES, account_index, funding_type, identity_index, + shielded_recipient, signer, Some(operation), on_built, @@ -1142,6 +1156,38 @@ impl AssetLockManager { signer: &S, operation: Option<&AssetLockOperationContext>, on_built: Option<&AssetLockBuiltObserver<'_>>, + ) -> Result<(DerivationPath, OutPoint), PlatformWalletError> { + self.broadcast_funded_asset_lock_tracked( + amount, + funding_sources, + source_index, + funding_type, + identity_index, + None, + signer, + operation, + on_built, + ) + .await + } + + /// 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. + #[allow(clippy::too_many_arguments)] + async fn broadcast_funded_asset_lock_tracked( + &self, + amount: AssetLockBuildAmount, + funding_sources: &[AccountTypePreference], + source_index: u32, + funding_type: AssetLockFundingType, + identity_index: u32, + shielded_recipient: Option, + signer: &S, + operation: Option<&AssetLockOperationContext>, + on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(DerivationPath, OutPoint), PlatformWalletError> { if operation.is_some() { self.require_wallet_drain_persistence()?; @@ -1388,6 +1434,7 @@ impl AssetLockManager { amount: locked_amount_duffs, status: AssetLockStatus::Built, proof: None, + shielded_recipient, }; if let Some(operation) = operation { operation.retain_checkpoint(tracked.clone()); @@ -1998,6 +2045,7 @@ mod tests { amount: entry.amount_duffs, status: entry.status.clone(), proof: entry.proof.clone(), + shielded_recipient: entry.shielded_recipient, }, ); } @@ -2423,6 +2471,7 @@ mod tests { }, AssetLockFundingType::AssetLockAddressTopUp, 0, + None, &signer, Some(&observer), ) @@ -2452,6 +2501,7 @@ mod tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &signer, Some(&observer), ) @@ -3393,6 +3443,7 @@ mod tests { }, AssetLockFundingType::IdentityRegistration, 0, + None, &signer, None, ) @@ -3423,6 +3474,7 @@ mod tests { }, reclaim_target, 0, + None, &signer, None, ), 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 de4fd11d5b7..e1c4064151c 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs @@ -35,6 +35,7 @@ use std::sync::Arc; use std::time::Duration; use dashcore::OutPoint; +use dpp::address_funds::OrchardAddress; use dpp::prelude::AssetLockProof; use key_wallet::bip32::DerivationPath; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -512,6 +513,7 @@ impl AssetLockManager { funding: AssetLockFunding, funding_type: AssetLockFundingType, destination_index: u32, + shielded_recipient: Option, asset_lock_signer: &AS, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result @@ -529,6 +531,7 @@ impl AssetLockManager { account_index, funding_type, destination_index, + shielded_recipient, asset_lock_signer, on_built, ) @@ -567,6 +570,7 @@ impl AssetLockManager { minimum_lock_duffs, funding_type, destination_index, + shielded_recipient, asset_lock_signer, &operation, on_built, @@ -598,6 +602,7 @@ impl AssetLockManager { account, funding_type, destination_index, + shielded_recipient, asset_lock_signer, on_built, ) @@ -974,6 +979,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: transaction.clone(), account_index: 0, 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 269b1ee0ea1..661d2afa75c 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 @@ -2165,6 +2165,7 @@ mod chain_lock_wait_tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -2269,6 +2270,7 @@ mod chain_lock_wait_tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -3454,6 +3456,7 @@ mod chain_lock_wait_tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &ctx.signer, None, ), @@ -3491,6 +3494,7 @@ mod chain_lock_wait_tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &ctx.signer, None, ), @@ -3730,6 +3734,7 @@ mod chain_lock_wait_tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &ctx.signer, None, ), 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 5cf0b4defc1..8bf0e6b0eec 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 @@ -232,6 +232,7 @@ fn reconstruct_candidates( let (status, proof) = recovered_status(record, out_point); Some(TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: record.transaction.clone(), account_index, @@ -766,6 +767,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: tx.clone(), account_index: 0, @@ -1002,6 +1004,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: tx.clone(), account_index: 0, 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 fe7c196382b..3e42fd9f5c2 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 @@ -106,6 +106,7 @@ impl AssetLockManager { } let lock = TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: tx, account_index, @@ -2192,6 +2193,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: transaction.clone(), account_index: 0, @@ -2328,6 +2330,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -2552,6 +2555,7 @@ mod tests { let out_point = OutPoint::new(tx.txid(), 0); let lock = TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: tx, account_index: 0, @@ -2829,6 +2833,7 @@ mod tests { self.out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point: self.out_point, transaction: self.transaction.clone(), account_index: 0, @@ -4340,6 +4345,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -4854,6 +4860,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -4978,6 +4985,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5481,6 +5489,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5586,6 +5595,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5865,6 +5875,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -6010,6 +6021,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, 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 e8c6ba57f41..a5a45f3467b 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 @@ -130,6 +130,19 @@ impl AssetLockManager { .and_then(|lock| lock.operation_id) } + /// The Orchard recipient a tracked shielded funding was built to pay, if + /// the row recorded one (see `TrackedAssetLock::shielded_recipient`). + #[cfg(any(feature = "shielded", test))] + pub(crate) async fn tracked_shielded_recipient( + &self, + out_point: &OutPoint, + ) -> 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)) + .and_then(|lock| lock.shielded_recipient) + } + /// Track a new asset lock in memory, returning a changeset describing /// the inserted entry. /// 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 8fcf3f482f1..83527bda7c9 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs @@ -9,6 +9,7 @@ //! `funding_type` + `identity_index` via the key-wallet's `Wallet`. use dashcore::{OutPoint, Transaction}; +use dpp::address_funds::OrchardAddress; use dpp::prelude::AssetLockProof; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -145,6 +146,13 @@ pub struct TrackedAssetLock { pub status: AssetLockStatus, /// The proof, available once IS-locked or ChainLocked. pub proof: Option, + /// The Orchard recipient a shielded funding (Type 18) was built to pay, + /// recorded with the row before the lock is dispatched and immutable + /// afterwards, so a resume pays the recipient the user confirmed rather + /// than whatever the resuming call passes. `None` for every other + /// funding type and for shielded locks tracked before the recipient was + /// recorded (those keep accepting the resuming caller's recipient). + pub shielded_recipient: Option, } impl From<&TrackedAssetLock> for AssetLockEntry { @@ -159,6 +167,7 @@ impl From<&TrackedAssetLock> for AssetLockEntry { amount_duffs: lock.amount, status: lock.status.clone(), proof: lock.proof.clone(), + shielded_recipient: lock.shielded_recipient, } } } 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 7cd3f05deef..66c1ed96c2e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/registration.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/registration.rs @@ -179,6 +179,7 @@ impl IdentityWallet { funding, AssetLockFundingType::IdentityRegistration, identity_index, + None, asset_lock_signer, None, ) @@ -417,6 +418,7 @@ impl IdentityWallet { funding, AssetLockFundingType::IdentityTopUp, identity_index, + None, asset_lock_signer, None, ) diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs index 799e0fc6807..50881adff0f 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs @@ -330,6 +330,7 @@ impl PlatformAddressWallet { funding, AssetLockFundingType::AssetLockAddressTopUp, /* destination_index */ 0, + None, asset_lock_signer, on_asset_lock_built, ) 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 257261f7800..68f6fa33c15 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 @@ -270,6 +270,23 @@ impl PlatformWallet { // an unfundable asset-lock tx (or paying for an Orchard proof // build, ~30s, only to reject downstream). validate_shielded_recipients(&recipients)?; + let (requested_recipient, _) = *recipients.first().expect("preflight enforces len() == 1"); + + // A resume pays the recipient its lock was built for. The row recorded + // it before dispatch (`TrackedAssetLock::shielded_recipient`), so a + // host that lost its own marker between the Core broadcast and the + // Type 18 submit cannot redirect the funds by passing another address. + // Decided before any funding resolution: a refused resume touches no + // reservation, waits for no proof and reaches no transport. A row + // tracked before recipients were recorded carries none and accepts + // the caller's, as before. + let recipient = match &funding { + AssetLockFunding::FromExistingAssetLock { out_point, .. } => { + let recorded = self.asset_locks.tracked_shielded_recipient(out_point).await; + resume_recipient(*out_point, recorded, requested_recipient)? + } + _ => requested_recipient, + }; // Pre-broadcast sizing guard for the `FromWalletBalance` path: // refuse to build an L1 asset-lock that can't even cover the @@ -378,6 +395,7 @@ impl PlatformWallet { funding, AssetLockFundingType::AssetLockShieldedAddressTopUp, /* destination_index */ 0, + Some(recipient), asset_lock_signer, on_asset_lock_built, ) @@ -469,8 +487,6 @@ impl PlatformWallet { ))); } } - let (recipient, _) = *recipients.first().expect("preflight enforces len() == 1"); - // Encrypt the output under this wallet's OVK so the shielded sync can // recover the funding (recipient, value, memo) from chain data alone. // Prefer the bound account whose IVK recognizes the recipient address @@ -950,6 +966,27 @@ where /// Generic over `T` so unit tests can pass `(u8, Option)` /// instead of constructing a curve-valid `OrchardAddress` for what /// is really a length / cardinality check. +/// The recipient a resumed shielded funding pays: the one its tracked lock +/// recorded when it was built, or — for a row tracked before recipients were +/// recorded — the one the resuming caller passes. A caller that names a +/// different recipient than the recorded one is refused with +/// [`PlatformWalletError::AssetLockRecipientMismatch`]; nothing is paid. +pub(super) fn resume_recipient( + out_point: OutPoint, + recorded: Option, + requested: OrchardAddress, +) -> Result { + match recorded { + None => Ok(requested), + Some(recorded) if recorded == requested => Ok(recorded), + Some(recorded) => Err(PlatformWalletError::AssetLockRecipientMismatch { + out_point, + recorded, + requested, + }), + } +} + pub(super) fn validate_shielded_recipients( recipients: &[(T, Option)], ) -> Result<(), PlatformWalletError> { @@ -1056,6 +1093,26 @@ mod tests { )); } + #[test] + fn resume_recipient_pays_the_recorded_one_and_refuses_another() { + let out_point = OutPoint::null(); + let recorded = crate::test_support::orchard_address_fixture(0x61); + let other = crate::test_support::orchard_address_fixture(0x62); + assert_eq!( + resume_recipient(out_point, Some(recorded), recorded).unwrap(), + recorded + ); + assert_eq!(resume_recipient(out_point, None, other).unwrap(), other); + assert!(matches!( + resume_recipient(out_point, Some(recorded), other), + Err(PlatformWalletError::AssetLockRecipientMismatch { + out_point: o, + recorded: r, + requested: q, + }) if o == out_point && r == recorded && q == other + )); + } + #[test] fn validate_rejects_empty_recipients() { let v: Vec<(u8, Option)> = Vec::new(); @@ -1218,6 +1275,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_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 28d71460ad7..8a106711552 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 @@ -77,6 +77,7 @@ fn drain_lock_fixture() -> (TrackedAssetLock, BTreeMap) amount: 10_000, status: AssetLockStatus::RecoveredFromChain, proof: Some(proof), + shielded_recipient: None, }, BTreeMap::from([(0, keys)]), ) @@ -147,6 +148,7 @@ impl PlatformWalletPersistence for RecoveryPersistence { amount: row.amount_duffs, status: row.status.clone(), proof: row.proof.clone(), + shielded_recipient: row.shielded_recipient, }, ) }) @@ -698,6 +700,7 @@ async fn should_refuse_drain_on_a_buffered_persistence_backend() { }, lock.funding_type, 0, + None, &signer, None, ) @@ -902,3 +905,217 @@ async fn should_report_a_wallet_drain_lock_to_the_caller() { assert_eq!(snapshot.state, AssetLockOperationState::NotSent); assert!(snapshot.out_point.is_none()); } + +/// A generic outpoint resume that names a different recipient than the row +/// recorded is refused before any funding resolution: no send, no staged +/// write, the row unchanged. +#[tokio::test] +async fn should_refuse_a_generic_resume_to_a_recipient_other_than_the_recorded_one() { + let (mut lock, keys) = drain_lock_fixture(); + lock.operation_id = None; + let recorded = crate::test_support::orchard_address_fixture(0x51); + let other = crate::test_support::orchard_address_fixture(0x52); + lock.shielded_recipient = Some(recorded); + let (wallet, persistence, coordinator, _dir) = wallet_fixture(&lock, keys).await; + let coordinator = Arc::new(coordinator); + let (_, _, _, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; + let prover = super::prover::CachedOrchardProver::new(); + + let error = wallet + .shielded_fund_from_asset_lock( + &coordinator, + AssetLockFunding::FromExistingAssetLock { + out_point: lock.out_point, + consume_invitation_voucher: false, + }, + vec![(other, None)], + &signer, + &prover, + None, + 0, + None, + None, + None, + ) + .await + .unwrap_err(); + assert!( + matches!( + &error, + PlatformWalletError::AssetLockRecipientMismatch { + out_point, + recorded: r, + requested: q, + } if *out_point == lock.out_point && *r == recorded && *q == other + ), + "{error}" + ); + assert!(persistence.staged.lock().unwrap().is_empty()); + assert_eq!( + persistence.committed_status(&lock.out_point), + AssetLockStatus::RecoveredFromChain + ); + assert_eq!( + live_status(&wallet, &lock.out_point).await, + AssetLockStatus::RecoveredFromChain + ); +} + +/// A repeated-UUID drain that names a different recipient is refused the +/// same way, and the operation stays Pending with its outpoint: the lock +/// exists and nothing was sent, so a later resume with the recorded +/// recipient can still complete it. +#[tokio::test] +async fn should_refuse_a_repeated_uuid_drain_to_a_recipient_other_than_the_recorded_one() { + let (mut lock, keys) = drain_lock_fixture(); + let recorded = crate::test_support::orchard_address_fixture(0x53); + let other = crate::test_support::orchard_address_fixture(0x54); + lock.shielded_recipient = Some(recorded); + let (wallet, persistence, coordinator, _dir) = wallet_fixture(&lock, keys).await; + let coordinator = Arc::new(coordinator); + let (_, _, _, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; + let prover = super::prover::CachedOrchardProver::new(); + let operation = Arc::new(AssetLockOperationContext::new(OPERATION_ID)); + + let error = wallet + .shielded_fund_from_asset_lock( + &coordinator, + AssetLockFunding::DrainWalletBalance { + account_index: 0, + minimum_lock_duffs: None, + operation: operation.clone(), + }, + vec![(other, None)], + &signer, + &prover, + None, + 0, + None, + None, + None, + ) + .await + .unwrap_err(); + assert!( + matches!( + error, + PlatformWalletError::AssetLockRecipientMismatch { .. } + ), + "{error}" + ); + let snapshot = operation.snapshot(); + assert_eq!(snapshot.state, AssetLockOperationState::Pending); + assert_eq!(snapshot.out_point, Some(lock.out_point)); + assert!(persistence.staged.lock().unwrap().is_empty()); + assert_ne!( + persistence.committed_status(&lock.out_point), + AssetLockStatus::DrainCompleted + ); + assert_eq!( + wallet + .shielded_wallet_drain_operation_status(OPERATION_ID) + .await + .unwrap() + .state, + AssetLockOperationState::Pending + ); +} + +/// A row tracked before recipients were recorded carries none and accepts +/// the resuming caller's recipient: the resume gets past the recipient check +/// (and fails later, at the network, in this fixture). +#[tokio::test] +async fn should_accept_the_callers_recipient_for_a_legacy_row_without_one() { + let (mut lock, keys) = drain_lock_fixture(); + lock.operation_id = None; + assert_eq!(lock.shielded_recipient, None); + let recipient = crate::test_support::orchard_address_fixture(0x55); + let (wallet, _persistence, coordinator, _dir) = wallet_fixture(&lock, keys).await; + let coordinator = Arc::new(coordinator); + let (_, _, _, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; + let prover = super::prover::CachedOrchardProver::new(); + + let error = wallet + .shielded_fund_from_asset_lock( + &coordinator, + AssetLockFunding::FromExistingAssetLock { + out_point: lock.out_point, + consume_invitation_voucher: false, + }, + vec![(recipient, None)], + &signer, + &prover, + None, + 0, + None, + Some(std::time::Duration::from_millis(10)), + None, + ) + .await + .unwrap_err(); + assert!( + !matches!( + error, + PlatformWalletError::AssetLockRecipientMismatch { .. } + ), + "a legacy row must not refuse the caller's recipient: {error}" + ); +} + +/// A fresh shielded funding records its recipient on the row before the +/// lock is dispatched: the drain's durable checkpoint and the typed-amount +/// path's queued row both carry it, even when the broadcast is then refused. +#[tokio::test] +async fn should_record_the_recipient_with_the_lock_before_dispatch() { + for drain in [false, true] { + let (mut lock, keys) = drain_lock_fixture(); + lock.operation_id = None; + let recipient = crate::test_support::orchard_address_fixture(0x56); + let (wallet, persistence, coordinator, _dir, signer) = + signed_wallet_fixture(&lock, keys).await; + let coordinator = Arc::new(coordinator); + let prover = super::prover::CachedOrchardProver::new(); + let operation = Arc::new(AssetLockOperationContext::new([0x57; 16])); + let seen = Mutex::new(Vec::new()); + let observer = |out_point: OutPoint| seen.lock().unwrap().push(out_point); + let funding = if drain { + AssetLockFunding::DrainWalletBalance { + account_index: 0, + minimum_lock_duffs: None, + operation: operation.clone(), + } + } else { + AssetLockFunding::FromWalletBalance { + amount_duffs: 5_000_000, + account_index: 0, + } + }; + wallet + .shielded_fund_from_asset_lock( + &coordinator, + funding, + vec![(recipient, None)], + &signer, + &prover, + None, + 0, + None, + None, + Some(&observer), + ) + .await + .expect_err("a lock the SPV client refuses to send must fail the call"); + let seen = seen.into_inner().unwrap(); + assert_eq!(seen.len(), 1); + let stored = persistence + .committed + .lock() + .unwrap() + .get(&seen[0]) + .cloned() + .or_else(|| persistence.staged.lock().unwrap().get(&seen[0]).cloned()) + .expect("the built lock's row reached the persister before the broadcast"); + assert_eq!(stored.shielded_recipient, Some(recipient), "drain={drain}"); + assert_eq!(stored.operation_id, drain.then_some([0x57; 16])); + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift index 0ac5f527808..5e338ee1a1a 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentAssetLock.swift @@ -206,6 +206,19 @@ public final class PersistentAssetLock { /// completed transfer from an operation that never reached broadcast. public var operationId: Data? + /// Raw 43-byte Orchard recipient a shielded asset-lock funding + /// (`fundingTypeRaw == 5`) was built to pay — the `recipientShielded*` + /// field-family promised above. Written by Rust with the row before the + /// lock is dispatched and immutable afterwards: a resume pays this + /// recipient and refuses another (`assetLockRecipientMismatch`). `nil` + /// for other funding types and for shielded locks tracked before the + /// recipient was recorded (those accept the resuming caller's). + /// + /// Default `nil` on the column keeps SwiftData's lightweight migration + /// safe for rows that pre-date this field. Lands in the live, not yet + /// published, V4 schema (`schema-releases.json` registers 3.0.0 only). + public var shieldedRecipientRaw43: Data? + /// Record timestamps. public var createdAt: Date public var updatedAt: Date @@ -220,7 +233,8 @@ public final class PersistentAssetLock { amountDuffs: Int64, statusRaw: Int, proofBytes: Data? = nil, - operationId: Data? = nil + operationId: Data? = nil, + shieldedRecipientRaw43: Data? = nil ) { self.outPointHex = outPointHex self.walletId = walletId @@ -232,6 +246,7 @@ public final class PersistentAssetLock { self.statusRaw = statusRaw self.proofBytes = proofBytes self.operationId = operationId + self.shieldedRecipientRaw43 = shieldedRecipientRaw43 self.createdAt = Date() self.updatedAt = Date() } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift index 2a43261fab3..97d02140709 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift @@ -78,6 +78,11 @@ public final class ManagedAssetLockManager: @unchecked Sendable { public let amount: UInt64 public let status: AssetLockStatus public let hasProof: Bool + /// Raw 43-byte Orchard recipient a shielded funding + /// (`.assetLockShieldedAddressTopUp`) was built to pay and a resume + /// pays; `nil` for other funding types and for locks tracked before + /// the recipient was recorded. + public let shieldedRecipientRaw43: Data? } /// Result of building an asset lock transaction. @@ -129,7 +134,10 @@ public final class ManagedAssetLockManager: @unchecked Sendable { identityIndex: lock.identity_index, amount: lock.amount, status: AssetLockStatus(rawValue: lock.status) ?? .built, - hasProof: lock.has_proof + hasProof: lock.has_proof, + shieldedRecipientRaw43: lock.has_shielded_recipient + ? withUnsafeBytes(of: lock.shielded_recipient_raw_43) { Data($0) } + : nil ) } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index f1d499682d7..7aeba8fd280 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -21,6 +21,7 @@ protocol ModelFetching: Sendable { private enum AssetLockPersistenceError: Error { case malformedRecord case duplicateOperationId + case conflictingShieldedRecipient case missingRecord case requiresChangeset } @@ -587,6 +588,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { existing.statusRaw = entry.statusRaw existing.proofBytes = entry.proofBytes existing.operationId = entry.operationId ?? existing.operationId + existing.shieldedRecipientRaw43 = + entry.shieldedRecipientRaw43 ?? existing.shieldedRecipientRaw43 existing.updatedAt = Date() } else { let record = PersistentAssetLock( @@ -599,7 +602,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { amountDuffs: entry.amountDuffs, statusRaw: entry.statusRaw, proofBytes: entry.proofBytes, - operationId: entry.operationId + operationId: entry.operationId, + shieldedRecipientRaw43: entry.shieldedRecipientRaw43 ) backgroundContext.insert(record) } @@ -697,6 +701,48 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } } + /// Shielded-recipient sidecar for the frozen legacy FFI row, saved with + /// the base upsert by endChangeset. Like the UUID, a recorded recipient can + /// never change: a resume must pay the recipient the lock was built for. + func persistAssetLockShieldedRecipient(walletId: Data, outPoint: Data, recipientRaw43: Data) throws { + try onQueue { + guard inChangeset else { throw AssetLockPersistenceError.requiresChangeset } + guard outPoint.count == 36, recipientRaw43.count == 43 else { + throw AssetLockPersistenceError.malformedRecord + } + let hex = PersistentAssetLock.encodeOutPoint(rawBytes: outPoint) + let descriptor = FetchDescriptor(predicate: #Predicate { + $0.walletId == walletId && $0.outPointHex == hex + }) + guard let record = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { + throw AssetLockPersistenceError.missingRecord + } + if let previous = record.shieldedRecipientRaw43, previous != recipientRaw43 { + throw AssetLockPersistenceError.conflictingShieldedRecipient + } + record.shieldedRecipientRaw43 = recipientRaw43 + } + } + + /// A missing base row is a failed read, not evidence of a legacy nil + /// recipient; a stored value of the wrong size is corruption, not absence. + func loadAssetLockShieldedRecipient(walletId: Data, outPoint: Data) throws -> Data? { + try onQueue { + guard outPoint.count == 36 else { throw AssetLockPersistenceError.malformedRecord } + let hex = PersistentAssetLock.encodeOutPoint(rawBytes: outPoint) + let descriptor = FetchDescriptor(predicate: #Predicate { + $0.walletId == walletId && $0.outPointHex == hex + }) + guard let record = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { + throw AssetLockPersistenceError.missingRecord + } + if let recipient = record.shieldedRecipientRaw43, recipient.count != 43 { + throw AssetLockPersistenceError.malformedRecord + } + return record.shieldedRecipientRaw43 + } + } + /// A missing base row is a failed read, not evidence of a legacy nil UUID. func loadAssetLockOperationId(walletId: Data, outPoint: Data) throws -> Data? { try onQueue { @@ -1050,6 +1096,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { throw AssetLockPersistenceError.duplicateOperationId } } + if let recipient = record.shieldedRecipientRaw43, recipient.count != 43 { + throw AssetLockPersistenceError.malformedRecord + } return AssetLockEntrySnapshot( outPointHex: record.outPointHex, transactionBytes: record.transactionBytes, @@ -1059,7 +1108,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { amountDuffs: record.amountDuffs, statusRaw: record.statusRaw, proofBytes: record.proofBytes, - operationId: record.operationId + operationId: record.operationId, + shieldedRecipientRaw43: record.shieldedRecipientRaw43 ) } } @@ -1079,6 +1129,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { public let statusRaw: Int public let proofBytes: Data? public var operationId: Data? = nil + /// Raw 43-byte Orchard recipient of a shielded funding; see + /// `PersistentAssetLock.shieldedRecipientRaw43`. + public var shieldedRecipientRaw43: Data? = nil } /// Owned snapshot of an `InvitationEntryFFI` row. All-POD — the callback @@ -3296,6 +3349,10 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { extensionCallbacks.on_load_identity_balance_block_time_fn = loadIdentityBalanceBlockTimeCallback extensionCallbacks.on_persist_asset_lock_operation_id_fn = persistAssetLockOperationIdCallback extensionCallbacks.on_load_asset_lock_operation_id_fn = loadAssetLockOperationIdCallback + extensionCallbacks.on_persist_asset_lock_shielded_recipient_fn = + persistAssetLockShieldedRecipientCallback + extensionCallbacks.on_load_asset_lock_shielded_recipient_fn = + loadAssetLockShieldedRecipientCallback return extensionCallbacks } @@ -11898,6 +11955,37 @@ private func loadAssetLockOperationIdCallback( } catch { return -1 } } +private func persistAssetLockShieldedRecipientCallback( + context: UnsafeMutableRawPointer?, walletId: UnsafePointer?, + outPoint: UnsafePointer?, recipientRaw43: UnsafePointer? +) -> Int32 { + guard let context, let walletId, let outPoint, let recipientRaw43 else { return -1 } + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + do { + try handler.persistAssetLockShieldedRecipient( + walletId: Data(bytes: walletId, count: 32), outPoint: Data(bytes: outPoint, count: 36), + recipientRaw43: Data(bytes: recipientRaw43, count: 43)) + return 0 + } catch { return -1 } +} + +private func loadAssetLockShieldedRecipientCallback( + context: UnsafeMutableRawPointer?, walletId: UnsafePointer?, outPoint: UnsafePointer?, + outFound: UnsafeMutablePointer?, outRecipientRaw43: UnsafeMutablePointer? +) -> Int32 { + guard let context, let walletId, let outPoint, let outFound, let outRecipientRaw43 else { return -1 } + outFound.pointee = false + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + do { + if let recipient = try handler.loadAssetLockShieldedRecipient( + walletId: Data(bytes: walletId, count: 32), outPoint: Data(bytes: outPoint, count: 36)) { + recipient.copyBytes(to: outRecipientRaw43, count: 43) + outFound.pointee = true + } + return 0 + } catch { return -1 } +} + private func persistIdentityBalanceBlockTimeCallback( context: UnsafeMutableRawPointer?, walletId: UnsafePointer?, identityId: UnsafePointer?, blockTime: UnsafePointer? diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index ff62fb7a7ca..7561936b721 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -265,6 +265,9 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// An asset lock (a drain, or a fixed amount in many small coins) exceeds /// the input cap; nothing was broadcast. case errorAssetLockTooManyInputs = 60 + /// A shielded fund-from-asset-lock resume named a different Orchard + /// recipient than the one its tracked lock recorded; nothing was paid. + case errorAssetLockRecipientMismatch = 61 /// The named thing does not exist. Besides the handle/lookup failures this /// has always covered, BOTH deferred-send paths report the /// wallet-was-REMOVED case here. @@ -396,6 +399,8 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorSpvProcessRestartRequired case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_TOO_MANY_INPUTS: self = .errorAssetLockTooManyInputs + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_MISMATCH: + self = .errorAssetLockRecipientMismatch case PLATFORM_WALLET_FFI_RESULT_CODE_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -585,6 +590,14 @@ public enum PlatformWalletError: LocalizedError { /// was broadcast and no partial drain occurred; consolidating the coins lets /// it fit. case assetLockTooManyInputs(String) + /// A shielded fund-from-asset-lock resume (generic outpoint resume or a + /// repeated-UUID wallet drain) named a different Orchard recipient than + /// the one the tracked lock recorded when it was built. Nothing was + /// submitted or paid; resume with the recorded recipient + /// (`PersistentAssetLock.shieldedRecipientRaw43` / + /// `TrackedAssetLock.shieldedRecipientRaw43`). Locks tracked before the + /// recipient was recorded carry none and accept the caller's. + case assetLockRecipientMismatch(String) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition /// (identity-create or a spend — unshield / transfer / withdrawal) was @@ -809,7 +822,7 @@ public enum PlatformWalletError: LocalizedError { .coreInsufficientFunds(let m), .assetLockNotTracked(let m), .assetLockAlreadyConsumed(let m), .assetLockFundingMismatch(let m), .assetLockInsufficientFunds(let m), - .assetLockTooManyInputs(let m), + .assetLockTooManyInputs(let m), .assetLockRecipientMismatch(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -928,6 +941,7 @@ public enum PlatformWalletError: LocalizedError { case .errorAssetLockFundingMismatch: self = .assetLockFundingMismatch(detail) case .errorAssetLockInsufficientFunds: self = .assetLockInsufficientFunds(detail) case .errorAssetLockTooManyInputs: self = .assetLockTooManyInputs(detail) + case .errorAssetLockRecipientMismatch: self = .assetLockRecipientMismatch(detail) case .errorWalletAlreadyExists: self = .walletAlreadyExists(detail) case .errorShieldedBroadcastFailed: self = .shieldedBroadcastFailed(detail) case .errorShieldedBroadcastUnconfirmed: self = .shieldedBroadcastUnconfirmed(detail) diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift index f1dec9f0c87..cafd35600cc 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift @@ -63,6 +63,41 @@ final class AssetLockOperationPersistenceTests: XCTestCase { XCTAssertEqual(try handler.loadAssetLockOperationId(walletId: walletId, outPoint: rawOutPoint), operationId) } + func testShieldedRecipientSurvivesStaleSnapshotsAndStoreReopenAndCannotChange() throws { + let recipient = Data((0..<43).map { UInt8($0 &+ 7) }) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("wallet.store") + try autoreleasepool { + let container = try DashModelContainer.create(url: url) + let handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) + // No row yet: a read is a failure, not a legacy nil. + XCTAssertThrowsError(try handler.loadAssetLockShieldedRecipient(walletId: walletId, outPoint: rawOutPoint)) + handler.beginChangeset(walletId: walletId) + XCTAssertTrue(handler.persistAssetLocks(walletId: walletId, + upserts: [snapshot(status: 0, operationId: nil)], removed: [])) + try handler.persistAssetLockShieldedRecipient( + walletId: walletId, outPoint: rawOutPoint, recipientRaw43: recipient) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: true)) + // A later snapshot without a recipient (a reconstruction or a + // status advance) must not erase it; a different one is refused. + try persist(handler, status: 1, operationId: nil) + handler.beginChangeset(walletId: walletId) + XCTAssertThrowsError(try handler.persistAssetLockShieldedRecipient( + walletId: walletId, outPoint: rawOutPoint, recipientRaw43: Data(repeating: 9, count: 43))) + XCTAssertFalse(handler.endChangeset(walletId: walletId, success: false)) + XCTAssertEqual(try handler.loadAssetLockShieldedRecipient(walletId: walletId, outPoint: rawOutPoint), recipient) + } + let reopened = try DashModelContainer.create(url: url) + let handler = PlatformWalletPersistenceHandler(modelContainer: reopened, network: .testnet) + let rows = try handler.loadCachedAssetLocks(walletId: walletId) + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows.first?.shieldedRecipientRaw43, recipient) + XCTAssertEqual(rows.first?.statusRaw, 1) + XCTAssertEqual(try handler.loadAssetLockShieldedRecipient(walletId: walletId, outPoint: rawOutPoint), recipient) + } + func testPublishedV3MigratesOperationIdToNil() throws { _ = DashModelContainer.schema let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) @@ -85,6 +120,7 @@ final class AssetLockOperationPersistenceTests: XCTestCase { let rows = try ModelContext(migrated).fetch(FetchDescriptor()) XCTAssertEqual(rows.count, 1) XCTAssertNil(rows.first?.operationId) + XCTAssertNil(rows.first?.shieldedRecipientRaw43) XCTAssertEqual(rows.first?.amountDuffs, 1000) XCTAssertEqual(DashModelContainer.schema.version, Schema.Version(4, 0, 0)) } From 1d16de520593b967da921df4a83ae7cff46896a5 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 4 Nov 2026 16:34:56 +0100 Subject: [PATCH 2/7] fix(platform-wallet): carry the shielded recipient raw and attest its capability The changeset, the tracked locks, the SQLite persister and the FFI persistence layer are built without the `shielded` feature, where `dpp::address_funds::OrchardAddress` does not exist, so the recipient recorded with a tracked asset lock is now carried as its raw 43 bytes (`ShieldedRecipientRaw`). Only shielded code converts: the resume check compares bytes, so a corrupted recorded recipient matches nothing and the resume is refused rather than paid. Storage and FFI loaders check the length only; the feature-independent tests use byte fixtures. The SQLite persister and the Swift handler now report `ASSET_LOCK_SHIELDED_RECIPIENTS`, which both already implement. Co-Authored-By: Claude Fable 5.1 --- .../src/asset_lock/manager.rs | 5 +- packages/rs-platform-wallet-ffi/src/error.rs | 6 +- .../rs-platform-wallet-ffi/src/persistence.rs | 38 ++------- .../src/shielded_send.rs | 4 +- .../src/test_fixtures.rs | 11 --- .../src/sqlite/persister.rs | 1 + .../src/sqlite/schema/asset_locks.rs | 14 +--- .../integration/sqlite_asset_locks_filter.rs | 39 ++++++--- .../sqlite_shielded_viewing_keys.rs | 1 + .../src/changeset/changeset.rs | 23 ++++-- .../rs-platform-wallet/src/changeset/mod.rs | 3 +- .../src/changeset/serde_adapters.rs | 79 ++++++++++--------- packages/rs-platform-wallet/src/error.rs | 8 +- .../rs-platform-wallet/src/wallet/apply.rs | 4 +- .../src/wallet/asset_lock/build.rs | 12 +-- .../src/wallet/asset_lock/orchestration.rs | 4 +- .../src/wallet/asset_lock/sync/tracking.rs | 2 +- .../src/wallet/asset_lock/tracked.rs | 5 +- .../wallet/shielded/fund_from_asset_lock.rs | 28 +++++-- .../src/wallet/shielded/wallet_drain_tests.rs | 12 ++- .../PlatformWalletManager.swift | 5 ++ .../PlatformWalletPersistenceHandler.swift | 1 + .../InvitationPersistenceTests.swift | 3 + 23 files changed, 158 insertions(+), 150 deletions(-) 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 fa3374400c9..69141b9a065 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs @@ -94,10 +94,7 @@ 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 - .map(|recipient| recipient.to_raw_bytes()) - .unwrap_or([0; 43]), + shielded_recipient_raw_43: lock.shielded_recipient.unwrap_or([0; 43]), } }) .collect(); diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 605dacf9c0d..eb8d0342385 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -2257,8 +2257,8 @@ mod tests { PlatformWalletFFIResultCode::ErrorAssetLockRecipientMismatch as i32, 61 ); - let recorded = crate::test_fixtures::orchard_address(1); - let requested = crate::test_fixtures::orchard_address(2); + let recorded = [1u8; 43]; + let requested = [2u8; 43]; let result: PlatformWalletFFIResult = PlatformWalletError::AssetLockRecipientMismatch { out_point: dashcore::OutPoint::null(), recorded, @@ -2274,7 +2274,7 @@ mod tests { message.contains("cannot be resumed to"), "the typed Display must survive the conversion: {message}" ); - assert!(message.contains(&hex::encode(recorded.to_raw_bytes()))); + assert!(message.contains(&hex::encode(recorded))); } #[test] diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 7c7d58b6d7d..45a71de72b2 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -10,7 +10,6 @@ //! same integers on a different callback family. use bincode::config; -use dpp::address_funds::{OrchardAddress, ORCHARD_ADDRESS_SIZE}; use key_wallet::account::account_collection::AccountCollection; use key_wallet::account::{Account, AccountType, StandardAccountType}; use key_wallet::bip32::DerivationPath; @@ -2777,7 +2776,6 @@ impl PlatformWalletPersistence for FFIPersister { continue; }; let out_point = outpoint_to_bytes(&entry.out_point); - let recipient = recipient.to_raw_bytes(); let rc = unsafe { cb( self.callbacks.context, @@ -6370,9 +6368,9 @@ fn load_asset_lock_operation_ids( } /// Rehydrate the shielded-recipient sidecar after decoding the frozen legacy -/// rows. A failed read or a byte string that is not an Orchard address -/// invalidates the whole load: a row that silently lost its recipient would -/// let a resume pay whatever the caller names. +/// rows. A failed read invalidates the whole load: a row that silently lost +/// its recipient would let a resume pay whatever the caller names. The bytes +/// are carried raw; whether they are a payable address is the wallet's call. fn load_asset_lock_shielded_recipients( callback: LoadAssetLockShieldedRecipientFn, context: *mut c_void, @@ -6382,7 +6380,7 @@ fn load_asset_lock_shielded_recipients( 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; ORCHARD_ADDRESS_SIZE]; + let mut raw = [0u8; platform_wallet::changeset::SHIELDED_RECIPIENT_SIZE]; let rc = unsafe { callback( context, @@ -6398,15 +6396,7 @@ fn load_asset_lock_shielded_recipients( "Loading asset-lock shielded recipient failed", )); } - lock.shielded_recipient = if found { - Some(OrchardAddress::from_raw_bytes(&raw).map_err(|error| { - PersistenceError::backend(format!( - "tracked asset locks: stored shielded recipient is not an Orchard address: {error}" - )) - })?) - } else { - None - }; + lock.shielded_recipient = found.then_some(raw); } Ok(()) } @@ -10083,8 +10073,7 @@ mod tests { use dashcore::hashes::Hash; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; - let recipient = crate::test_fixtures::orchard_address(0x33); - let raw = recipient.to_raw_bytes(); + let raw = [0x33u8; 43]; unsafe extern "C" fn load_recipient( context: *mut c_void, _: *const u8, @@ -10118,7 +10107,7 @@ mod tests { status: platform_wallet::AssetLockStatus::Broadcast, proof: None, operation_id: None, - shielded_recipient: Some(recipient), + shielded_recipient: Some(raw), }; let (entries, _storage) = build_asset_lock_entries(&[&entry]); let wallet = WalletRestoreEntryFFI { @@ -10139,19 +10128,8 @@ mod tests { &mut restored, ) .expect("valid recipient sidecar"); - assert_eq!( - restored[&2][&entry.out_point].shielded_recipient, - stored.map(|_| recipient) - ); + assert_eq!(restored[&2][&entry.out_point].shielded_recipient, stored); } - let garbage: Option<[u8; 43]> = Some([0xff; 43]); - assert!(load_asset_lock_shielded_recipients( - load_recipient, - (&garbage as *const Option<[u8; 43]>).cast_mut().cast(), - &[42; 32], - &mut restored, - ) - .is_err()); let changeset = PlatformWalletChangeSet { asset_locks: Some(platform_wallet::changeset::AssetLockChangeSet { diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index a4dd23e89df..c7748a607b5 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -3125,8 +3125,8 @@ mod tests { let recipient_mismatch = map_asset_lock_funding_result( Err(PlatformWalletError::AssetLockRecipientMismatch { out_point, - recorded: crate::test_fixtures::orchard_address(1), - requested: crate::test_fixtures::orchard_address(2), + recorded: [1; 43], + requested: [2; 43], }), "shielded resume fund-from-asset-lock", ); diff --git a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs index b9154222aa1..d41459b6586 100644 --- a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs +++ b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs @@ -72,14 +72,3 @@ pub(crate) fn out_string( unsafe { platform_wallet_free_string(out) }; Ok(Some(string)) } - -/// A valid Orchard payment address, deterministic in `seed_byte`: the -/// external address at diversifier index 0 of the spending key whose 32 -/// bytes all equal `seed_byte`. Two seed bytes give two different addresses. -pub(crate) fn orchard_address(seed_byte: u8) -> dpp::address_funds::OrchardAddress { - use dash_sdk::grovedb_commitment_tree::{FullViewingKey, Scope, SpendingKey}; - let spending_key = - SpendingKey::from_bytes([seed_byte; 32]).expect("a constant spending key is on the curve"); - let full_viewing_key = FullViewingKey::from(&spending_key); - dpp::address_funds::OrchardAddress::from(full_viewing_key.address_at(0u32, Scope::External)) -} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/persister.rs b/packages/rs-platform-wallet-storage/src/sqlite/persister.rs index 15634f6293f..fb4080cc63c 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/persister.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/persister.rs @@ -1321,6 +1321,7 @@ impl PlatformWalletPersistence for SqlitePersister { .union(PersistenceCapabilities::DPNS_NAME_STATES) .union(PersistenceCapabilities::TRACKED_ASSET_LOCKS) .union(PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS) + .union(PersistenceCapabilities::ASSET_LOCK_SHIELDED_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 e7c6a96294d..a2dd6ee62ec 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,10 +13,9 @@ use rusqlite::{params, OptionalExtension, Transaction}; use serde::{Deserialize, Serialize}; -use dpp::address_funds::{OrchardAddress, ORCHARD_ADDRESS_SIZE}; use dpp::prelude::AssetLockProof; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; -use platform_wallet::changeset::AssetLockChangeSet; +use platform_wallet::changeset::{AssetLockChangeSet, SHIELDED_RECIPIENT_SIZE}; use platform_wallet::wallet::asset_lock::tracked::AssetLockStatus; use platform_wallet::wallet::platform_wallet::WalletId; @@ -189,9 +188,7 @@ pub fn apply( )); } } - let shielded_recipient = entry - .shielded_recipient - .map(|recipient| recipient.to_raw_bytes()); + let shielded_recipient = entry.shielded_recipient; if let (Some(incoming), Some(stored)) = ( shielded_recipient.as_ref(), existing @@ -338,15 +335,10 @@ fn decode_row( .transpose()?; entry.shielded_recipient = shielded_recipient .map(|bytes| { - let raw: [u8; ORCHARD_ADDRESS_SIZE] = bytes.try_into().map_err(|_| { + <[u8; SHIELDED_RECIPIENT_SIZE]>::try_from(bytes).map_err(|_| { WalletStorageError::blob_decode( "asset_locks.shielded_recipient must contain 43 bytes", ) - })?; - OrchardAddress::from_raw_bytes(&raw).map_err(|_| { - WalletStorageError::blob_decode( - "asset_locks.shielded_recipient is not a valid Orchard address", - ) }) }) .transpose()?; 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 0abc5fac2fe..f52bb5910f8 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 @@ -10,7 +10,10 @@ use common::{ensure_wallet_meta, fresh_persister, wid}; use dashcore::hashes::Hash; use dashcore::{OutPoint, Transaction, Txid}; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; -use platform_wallet::changeset::{AssetLockChangeSet, AssetLockEntry, PlatformWalletPersistence}; +use platform_wallet::changeset::{ + AssetLockChangeSet, AssetLockEntry, PlatformWalletPersistence, ShieldedRecipientRaw, + SHIELDED_RECIPIENT_SIZE, +}; use platform_wallet::wallet::asset_lock::tracked::AssetLockStatus; use platform_wallet_storage::sqlite::error::WalletStorageError; use platform_wallet_storage::sqlite::schema::asset_locks; @@ -348,7 +351,7 @@ fn should_preserve_shielded_recipient_when_later_snapshot_lacks_it_and_reject_a_ let w = wid(0xA9); ensure_wallet_meta(&persister, &w); let outpoint = op(0x35); - let recipient = orchard_address(0x11); + let recipient = recipient_bytes(0x11); let store = |persister: &platform_wallet_storage::SqlitePersister, row: AssetLockEntry| { persister.store( w, @@ -368,7 +371,7 @@ fn should_preserve_shielded_recipient_when_later_snapshot_lacks_it_and_reject_a_ store(&persister, entry(outpoint, AssetLockStatus::Broadcast)).unwrap(); // A snapshot naming another recipient is refused before any write. let mut redirected = entry(outpoint, AssetLockStatus::ChainLocked); - redirected.shielded_recipient = Some(orchard_address(0x12)); + redirected.shielded_recipient = Some(recipient_bytes(0x12)); assert!(store(&persister, redirected).is_err()); drop(persister); @@ -390,13 +393,13 @@ fn should_preserve_shielded_recipient_when_later_snapshot_lacks_it_and_reject_a_ assert!(conn .execute( "UPDATE asset_locks SET shielded_recipient = ?1", - [orchard_address(0x13).to_raw_bytes().to_vec()] + [recipient_bytes(0x13).to_vec()] ) .is_err()); } #[test] -fn should_fail_the_load_when_a_stored_shielded_recipient_is_not_an_orchard_address() { +fn should_fail_the_load_when_a_stored_shielded_recipient_has_the_wrong_length() { let (persister, _tmp, _) = fresh_persister(); let w = wid(0xAB); ensure_wallet_meta(&persister, &w); @@ -416,22 +419,32 @@ fn should_fail_the_load_when_a_stored_shielded_recipient_is_not_an_orchard_addre ) .unwrap(); let conn = persister.lock_conn_for_test(); - // 43 bytes whose pk_d is not a Pallas point: the CHECK and the - // immutability trigger (OLD is NULL) both let it in. + // 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 a resume would pay to whatever the caller names). + conn.execute_batch("PRAGMA ignore_check_constraints = ON") + .unwrap(); conn.execute( "UPDATE asset_locks SET shielded_recipient = ?1", - [vec![0xff_u8; 43]], + [vec![0xff_u8; SHIELDED_RECIPIENT_SIZE - 1]], ) .unwrap(); + conn.execute_batch("PRAGMA ignore_check_constraints = OFF") + .unwrap(); assert!( asset_locks::load_unconsumed(&conn, &w, &platform_wallet_storage::LoadCtx::strict()) .is_err() ); } -fn orchard_address(seed_byte: u8) -> dpp::address_funds::OrchardAddress { - use dash_sdk::grovedb_commitment_tree::{FullViewingKey, Scope, SpendingKey}; - let spending_key = SpendingKey::from_bytes([seed_byte; 32]).unwrap(); - let full_viewing_key = FullViewingKey::from(&spending_key); - dpp::address_funds::OrchardAddress::from(full_viewing_key.address_at(0u32, Scope::External)) +#[test] +fn sqlite_advertises_asset_lock_shielded_recipients() { + let (persister, _tmp, _) = fresh_persister(); + assert!(persister.persistence_capabilities().contains( + platform_wallet::changeset::PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS + )); +} + +fn recipient_bytes(seed_byte: u8) -> ShieldedRecipientRaw { + [seed_byte; SHIELDED_RECIPIENT_SIZE] } diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_shielded_viewing_keys.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_shielded_viewing_keys.rs index d2a16697f68..29f3622b039 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_shielded_viewing_keys.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_shielded_viewing_keys.rs @@ -96,6 +96,7 @@ fn sqlite_does_not_attest_wallet_drain_without_wallet_restore() { // unsupported all-wallet shielded recovery contract. assert!(capabilities.contains(PersistenceCapabilities::TRACKED_ASSET_LOCKS)); assert!(capabilities.contains(PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS)); + assert!(capabilities.contains(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS)); } #[test] diff --git a/packages/rs-platform-wallet/src/changeset/changeset.rs b/packages/rs-platform-wallet/src/changeset/changeset.rs index 725ab92cba6..0ec2181a1dd 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -27,7 +27,6 @@ use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::Txid; use dash_sdk::platform::address_sync::AddressFunds; -use dpp::address_funds::OrchardAddress; use dpp::prelude::AssetLockProof; use key_wallet::account::AccountType; use key_wallet::bip32::ExtendedPubKey; @@ -1494,6 +1493,18 @@ pub struct AssetLockChangeSet { pub removed: BTreeSet, } +/// Byte length of a raw Orchard payment address (`OrchardAddress::to_raw_bytes`). +pub const SHIELDED_RECIPIENT_SIZE: usize = 43; + +/// The raw bytes of an Orchard payment address, as `OrchardAddress::to_raw_bytes` +/// gives them and every FFI surface carries them (`recipient_raw_43`). +/// +/// The changeset, the tracked locks and the persistence backends are built +/// without the `shielded` feature, where `dpp::address_funds::OrchardAddress` +/// does not exist, so they carry the recipient raw. Only shielded code +/// converts it back into an address, and the resume check compares bytes. +pub type ShieldedRecipientRaw = [u8; SHIELDED_RECIPIENT_SIZE]; + /// A single asset lock entry in the changeset. /// /// Contains all fields needed to fully reconstruct a @@ -1535,10 +1546,10 @@ pub struct AssetLockEntry { feature = "serde", serde( default, - with = "crate::changeset::serde_adapters::optional_orchard_address" + with = "crate::changeset::serde_adapters::optional_shielded_recipient" ) )] - pub shielded_recipient: Option, + pub shielded_recipient: Option, } impl AssetLockEntry { @@ -1551,7 +1562,7 @@ impl AssetLockEntry { pub(crate) fn preserve_recovery_metadata( &mut self, previous_operation_id: Option<[u8; 16]>, - previous_shielded_recipient: Option, + previous_shielded_recipient: Option, ) -> bool { if let Some(previous_id) = previous_operation_id { if self @@ -2838,7 +2849,7 @@ mod tests { // The recorded shielded recipient survives a later snapshot without // one (reconstruction, a status advance) and vetoes a conflicting one. - let recipient = crate::test_support::orchard_address_fixture(0x71); + let recipient = [0x71u8; SHIELDED_RECIPIENT_SIZE]; let mut recorded = cs_with(AssetLockStatus::Broadcast); recorded .asset_locks @@ -2859,7 +2870,7 @@ mod tests { .asset_locks .get_mut(&outpoint) .unwrap() - .shielded_recipient = Some(crate::test_support::orchard_address_fixture(0x72)); + .shielded_recipient = Some([0x72; SHIELDED_RECIPIENT_SIZE]); let expected = recorded.clone(); recorded.merge(redirected); assert_eq!(recorded.asset_locks, expected.asset_locks); diff --git a/packages/rs-platform-wallet/src/changeset/mod.rs b/packages/rs-platform-wallet/src/changeset/mod.rs index f246d3f6056..612d81bccaf 100644 --- a/packages/rs-platform-wallet/src/changeset/mod.rs +++ b/packages/rs-platform-wallet/src/changeset/mod.rs @@ -42,7 +42,8 @@ pub use changeset::{ PendingContactCryptoKind, PendingContactCryptoOp, PlatformAddressBalanceEntry, PlatformAddressChangeSet, PlatformWalletChangeSet, ProviderKeyAccountEntry, ProviderKeyExtendedPubKey, ProviderPlatformNodePubKey, ReceivedContactRequestKey, - SentContactRequestKey, TokenBalanceChangeSet, WalletMetadataEntry, + 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/serde_adapters.rs b/packages/rs-platform-wallet/src/changeset/serde_adapters.rs index 2a992579115..d4deed2a0a9 100644 --- a/packages/rs-platform-wallet/src/changeset/serde_adapters.rs +++ b/packages/rs-platform-wallet/src/changeset/serde_adapters.rs @@ -6,7 +6,6 @@ //! `changeset/mod.rs`). use dash_sdk::platform::address_sync::AddressFunds; -use dpp::address_funds::OrchardAddress; use dpp::balances::credits::Credits; use dpp::prelude::AddressNonce; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -210,57 +209,56 @@ mod optional_asset_lock_proof_tests { } } -/// Adapter for `Option` (upstream has no serde derive, and -/// serde has no impl for `[u8; 43]`). +/// Adapter for `Option` (serde has no impl for +/// `[u8; 43]`). /// /// Encodes the raw 43-byte Orchard address as `Option>` — the same /// bytes `OrchardAddress::to_raw_bytes` gives and every FFI surface already -/// carries (`recipient_raw_43`). Decoding re-validates the Pallas point -/// through `from_raw_bytes`, so a corrupted blob fails loudly instead of -/// yielding an address nothing can pay. -pub mod optional_orchard_address { +/// carries (`recipient_raw_43`). Decoding checks the length only: whether the +/// bytes are a payable address is decided where the recipient is used, in +/// shielded code, and a corrupted recipient never matches the one a resume +/// names, so it refuses the resume rather than paying anyone. +pub mod optional_shielded_recipient { use super::*; - use dpp::address_funds::ORCHARD_ADDRESS_SIZE; + use crate::changeset::{ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; pub fn serialize( - value: &Option, + value: &Option, serializer: S, ) -> Result { - value - .map(|address| address.to_raw_bytes().to_vec()) - .serialize(serializer) + value.map(|raw| raw.to_vec()).serialize(serializer) } pub fn deserialize<'de, D: Deserializer<'de>>( deserializer: D, - ) -> Result, D::Error> { + ) -> Result, D::Error> { let bytes = Option::>::deserialize(deserializer)?; bytes .map(|bytes| { - let raw: [u8; ORCHARD_ADDRESS_SIZE] = - bytes.as_slice().try_into().map_err(|_| { - serde::de::Error::custom(format!( - "shielded recipient must be {ORCHARD_ADDRESS_SIZE} bytes, got {}", - bytes.len() - )) - })?; - OrchardAddress::from_raw_bytes(&raw).map_err(serde::de::Error::custom) + bytes.as_slice().try_into().map_err(|_| { + serde::de::Error::custom(format!( + "shielded recipient must be {SHIELDED_RECIPIENT_SIZE} bytes, got {}", + bytes.len() + )) + }) }) .transpose() } } -#[cfg(all(test, feature = "shielded"))] -mod optional_orchard_address_tests { - use dpp::address_funds::OrchardAddress; +#[cfg(test)] +mod optional_shielded_recipient_tests { + use crate::changeset::{ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; #[derive(serde::Serialize, serde::Deserialize)] struct Carrier { - #[serde(with = "super::optional_orchard_address")] - recipient: Option, + #[serde(with = "super::optional_shielded_recipient")] + recipient: Option, } - fn roundtrip(recipient: Option) -> Result, String> { + fn roundtrip( + recipient: Option, + ) -> Result, String> { let bytes = dpp::bincode::serde::encode_to_vec( Carrier { recipient }, dpp::bincode::config::standard(), @@ -274,23 +272,26 @@ mod optional_orchard_address_tests { #[test] fn should_roundtrip_a_recipient_and_none() { - let recipient = crate::test_support::orchard_address_fixture(1); + let recipient = [0x5au8; SHIELDED_RECIPIENT_SIZE]; assert_eq!(roundtrip(Some(recipient)).unwrap(), Some(recipient)); assert_eq!(roundtrip(None).unwrap(), None); } #[test] - fn should_reject_a_wrong_length_or_invalid_recipient() { - let encode = |bytes: Vec| { - dpp::bincode::serde::encode_to_vec((Some(bytes),), dpp::bincode::config::standard()) - .unwrap() - }; - for bytes in [vec![0u8; 42], vec![0u8; 44], vec![0xffu8; 43]] { - let result: Result<(Carrier, usize), _> = dpp::bincode::serde::decode_from_slice( - &encode(bytes), - dpp::bincode::config::standard(), - ); - assert!(result.is_err()); + fn should_reject_a_recipient_of_the_wrong_length() { + #[derive(serde::Serialize)] + struct Raw { + recipient: Option>, } + let bytes = dpp::bincode::serde::encode_to_vec( + Raw { + recipient: Some(vec![1; SHIELDED_RECIPIENT_SIZE - 1]), + }, + dpp::bincode::config::standard(), + ) + .unwrap(); + let decoded: Result<(Carrier, usize), _> = + dpp::bincode::serde::decode_from_slice(&bytes, dpp::bincode::config::standard()); + assert!(decoded.is_err()); } } diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 4cf1a2d20f4..c7376ec5c68 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -640,13 +640,13 @@ pub enum PlatformWalletError { /// before the recipient was recorded carry none and accept the caller's. #[error( "Asset lock {out_point} was built to pay shielded recipient {} and cannot be resumed to {}", - hex::encode(recorded.to_raw_bytes()), - hex::encode(requested.to_raw_bytes()) + hex::encode(recorded), + hex::encode(requested) )] AssetLockRecipientMismatch { out_point: dashcore::OutPoint, - recorded: dpp::address_funds::OrchardAddress, - requested: dpp::address_funds::OrchardAddress, + recorded: crate::changeset::ShieldedRecipientRaw, + requested: crate::changeset::ShieldedRecipientRaw, }, #[error("SDK error: {0}")] diff --git a/packages/rs-platform-wallet/src/wallet/apply.rs b/packages/rs-platform-wallet/src/wallet/apply.rs index 4521cfa3b68..f1bccb35b8b 100644 --- a/packages/rs-platform-wallet/src/wallet/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/apply.rs @@ -887,7 +887,7 @@ mod tests { fn should_preserve_the_shielded_recipient_when_applying_stale_snapshots() { let mut wallet = build_test_wallet(); let mut info = empty_info(&wallet); - let recipient = crate::test_support::orchard_address_fixture(0x81); + let recipient = [0x81u8; crate::changeset::SHIELDED_RECIPIENT_SIZE]; let mut recorded = recovery_asset_lock(AssetLockStatus::Broadcast, None); recorded.shielded_recipient = Some(recipient); apply_recovery_asset_lock(&mut info, &mut wallet, recorded); @@ -904,7 +904,7 @@ mod tests { // A snapshot naming another recipient is dropped whole. let mut redirected = recovery_asset_lock(AssetLockStatus::ChainLocked, None); - redirected.shielded_recipient = Some(crate::test_support::orchard_address_fixture(0x82)); + redirected.shielded_recipient = Some([0x82; crate::changeset::SHIELDED_RECIPIENT_SIZE]); apply_recovery_asset_lock(&mut info, &mut wallet, redirected); let restored = &info.tracked_asset_locks[&OutPoint::default()]; assert_eq!(restored.shielded_recipient, Some(recipient)); 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 7ea0c5505fa..85d809b2dea 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs @@ -6,9 +6,9 @@ use crate::broadcaster::TransactionBroadcaster; use std::time::Duration; +use crate::changeset::ShieldedRecipientRaw; use dashcore::Address as DashAddress; use dashcore::{OutPoint, Transaction, TxOut}; -use dpp::address_funds::OrchardAddress; use key_wallet::account::AccountType; use key_wallet::bip32::DerivationPath; use key_wallet::managed_account::address_pool::AddressState; @@ -945,7 +945,7 @@ impl AssetLockManager { account_index: u32, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + shielded_recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -999,7 +999,7 @@ impl AssetLockManager { funding_account: AssetLockFundingAccount, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + shielded_recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -1031,7 +1031,7 @@ impl AssetLockManager { source_index: u32, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + shielded_recipient: Option, signer: &S, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result<(dpp::prelude::AssetLockProof, DerivationPath, OutPoint), PlatformWalletError> { @@ -1120,7 +1120,7 @@ impl AssetLockManager { minimum_lock_duffs: Option, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + shielded_recipient: Option, signer: &S, operation: &AssetLockOperationContext, on_built: Option<&AssetLockBuiltObserver<'_>>, @@ -1184,7 +1184,7 @@ impl AssetLockManager { source_index: u32, funding_type: AssetLockFundingType, identity_index: u32, - shielded_recipient: Option, + shielded_recipient: Option, signer: &S, operation: Option<&AssetLockOperationContext>, on_built: Option<&AssetLockBuiltObserver<'_>>, 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 e1c4064151c..2dc021033c6 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs @@ -34,8 +34,8 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; +use crate::changeset::ShieldedRecipientRaw; use dashcore::OutPoint; -use dpp::address_funds::OrchardAddress; use dpp::prelude::AssetLockProof; use key_wallet::bip32::DerivationPath; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -513,7 +513,7 @@ impl AssetLockManager { funding: AssetLockFunding, funding_type: AssetLockFundingType, destination_index: u32, - shielded_recipient: Option, + shielded_recipient: Option, asset_lock_signer: &AS, on_built: Option<&AssetLockBuiltObserver<'_>>, ) -> Result 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 a5a45f3467b..7d55bd91ebb 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 @@ -136,7 +136,7 @@ impl AssetLockManager { pub(crate) async fn tracked_shielded_recipient( &self, out_point: &OutPoint, - ) -> Option { + ) -> 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)) 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 83527bda7c9..8294b98793b 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs @@ -9,11 +9,10 @@ //! `funding_type` + `identity_index` via the key-wallet's `Wallet`. use dashcore::{OutPoint, Transaction}; -use dpp::address_funds::OrchardAddress; use dpp::prelude::AssetLockProof; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; -use crate::changeset::AssetLockEntry; +use crate::changeset::{AssetLockEntry, ShieldedRecipientRaw}; /// Asset lock status on Core chain. /// @@ -152,7 +151,7 @@ pub struct TrackedAssetLock { /// than whatever the resuming call passes. `None` for every other /// funding type and for shielded locks tracked before the recipient was /// recorded (those keep accepting the resuming caller's recipient). - pub shielded_recipient: Option, + pub shielded_recipient: Option, } impl From<&TrackedAssetLock> for AssetLockEntry { 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 68f6fa33c15..ea2befa19a5 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 @@ -33,7 +33,9 @@ use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_settings::PutSettings; use dashcore::OutPoint; -use dpp::address_funds::{OrchardAddress, PlatformAddress}; +use dpp::address_funds::{OrchardAddress, PlatformAddress, ORCHARD_ADDRESS_SIZE}; + +use crate::changeset::{ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; use dpp::asset_lock::StoredAssetLockInfo; use dpp::balances::credits::CREDITS_PER_DUFF; use dpp::fee::Credits; @@ -395,7 +397,7 @@ impl PlatformWallet { funding, AssetLockFundingType::AssetLockShieldedAddressTopUp, /* destination_index */ 0, - Some(recipient), + Some(recipient.to_raw_bytes()), asset_lock_signer, on_asset_lock_built, ) @@ -971,18 +973,23 @@ where /// recorded — the one the resuming caller passes. A caller that names a /// different recipient than the recorded one is refused with /// [`PlatformWalletError::AssetLockRecipientMismatch`]; nothing is paid. +/// +/// The row carries the recipient raw; the comparison is on bytes, so a +/// corrupted recorded recipient matches nothing and the resume is refused +/// rather than paid to an address nobody holds. pub(super) fn resume_recipient( out_point: OutPoint, - recorded: Option, + recorded: Option, requested: OrchardAddress, ) -> Result { + const _: () = assert!(SHIELDED_RECIPIENT_SIZE == ORCHARD_ADDRESS_SIZE); match recorded { None => Ok(requested), - Some(recorded) if recorded == requested => Ok(recorded), + Some(recorded) if recorded == requested.to_raw_bytes() => Ok(requested), Some(recorded) => Err(PlatformWalletError::AssetLockRecipientMismatch { out_point, recorded, - requested, + requested: requested.to_raw_bytes(), }), } } @@ -1099,17 +1106,22 @@ mod tests { let recorded = crate::test_support::orchard_address_fixture(0x61); let other = crate::test_support::orchard_address_fixture(0x62); assert_eq!( - resume_recipient(out_point, Some(recorded), recorded).unwrap(), + resume_recipient(out_point, Some(recorded.to_raw_bytes()), recorded).unwrap(), recorded ); assert_eq!(resume_recipient(out_point, None, other).unwrap(), other); assert!(matches!( - resume_recipient(out_point, Some(recorded), other), + resume_recipient(out_point, Some(recorded.to_raw_bytes()), other), Err(PlatformWalletError::AssetLockRecipientMismatch { out_point: o, recorded: r, requested: q, - }) if o == out_point && r == recorded && q == other + }) if o == out_point && r == recorded.to_raw_bytes() && q == other.to_raw_bytes() + )); + // Bytes that are not an address match nothing: refused, not paid. + assert!(matches!( + resume_recipient(out_point, Some([0xff; SHIELDED_RECIPIENT_SIZE]), other), + Err(PlatformWalletError::AssetLockRecipientMismatch { .. }) )); } 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 8a106711552..a6e0cc497cc 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 @@ -915,7 +915,7 @@ async fn should_refuse_a_generic_resume_to_a_recipient_other_than_the_recorded_o lock.operation_id = None; let recorded = crate::test_support::orchard_address_fixture(0x51); let other = crate::test_support::orchard_address_fixture(0x52); - lock.shielded_recipient = Some(recorded); + lock.shielded_recipient = Some(recorded.to_raw_bytes()); let (wallet, persistence, coordinator, _dir) = wallet_fixture(&lock, keys).await; let coordinator = Arc::new(coordinator); let (_, _, _, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; @@ -946,7 +946,7 @@ async fn should_refuse_a_generic_resume_to_a_recipient_other_than_the_recorded_o out_point, recorded: r, requested: q, - } if *out_point == lock.out_point && *r == recorded && *q == other + } if *out_point == lock.out_point && *r == recorded.to_raw_bytes() && *q == other.to_raw_bytes() ), "{error}" ); @@ -970,7 +970,7 @@ async fn should_refuse_a_repeated_uuid_drain_to_a_recipient_other_than_the_recor let (mut lock, keys) = drain_lock_fixture(); let recorded = crate::test_support::orchard_address_fixture(0x53); let other = crate::test_support::orchard_address_fixture(0x54); - lock.shielded_recipient = Some(recorded); + lock.shielded_recipient = Some(recorded.to_raw_bytes()); let (wallet, persistence, coordinator, _dir) = wallet_fixture(&lock, keys).await; let coordinator = Arc::new(coordinator); let (_, _, _, signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; @@ -1115,7 +1115,11 @@ async fn should_record_the_recipient_with_the_lock_before_dispatch() { .cloned() .or_else(|| persistence.staged.lock().unwrap().get(&seen[0]).cloned()) .expect("the built lock's row reached the persister before the broadcast"); - assert_eq!(stored.shielded_recipient, Some(recipient), "drain={drain}"); + assert_eq!( + stored.shielded_recipient, + Some(recipient.to_raw_bytes()), + "drain={drain}" + ); assert_eq!(stored.operation_id, drain.then_some([0x57; 16])); } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index 5c86e8bce11..a93b4511cff 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -109,6 +109,11 @@ public struct PlatformWalletPersistenceCapabilities: Equatable, Sendable { public static let dashpayPayments: UInt64 = 1 << 12 /// Durable operation UUIDs, including consumed asset-lock tombstones. public static let assetLockOperationIds: UInt64 = 1 << 13 + /// The Orchard recipient of a shielded asset-lock funding survives store + /// and load with its row, so a resume after restart pays the confirmed + /// recipient. Mirrors `PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS`; + /// Rust only honours the declaration when both recipient slots are wired. + public static let assetLockShieldedRecipients: UInt64 = 1 << 14 public let version: UInt32 public let bits: UInt64 diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 7aeba8fd280..7bc7e76188e 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3310,6 +3310,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { | PlatformWalletPersistenceCapabilities.coreSweepRemoval | PlatformWalletPersistenceCapabilities.dashpayPayments | PlatformWalletPersistenceCapabilities.assetLockOperationIds + | PlatformWalletPersistenceCapabilities.assetLockShieldedRecipients ) } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift index 7b51fce43d9..f6c0818f73c 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift @@ -68,6 +68,9 @@ final class InvitationPersistenceTests: XCTestCase { // may ride this store's rounds — genuinely attested. | PlatformWalletPersistenceCapabilities.dashpayPayments | PlatformWalletPersistenceCapabilities.assetLockOperationIds + // Shielded recipients: the handler wires both recipient slots and + // lands the bytes on `PersistentAssetLock.shieldedRecipientRaw43`. + | PlatformWalletPersistenceCapabilities.assetLockShieldedRecipients XCTAssertEqual( capabilities.version, From a5dd3e8cf5aa84549ffbf73a85e9968e22e2df0b Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 4 Nov 2026 17:02:30 +0100 Subject: [PATCH 3/7] docs(platform-wallet-ffi): advance the error-code frontier past 61 Row 61 claims `ErrorAssetLockRecipientMismatch`; the frontier note now says so and names 62 as the next allocatable integer. The legacy-row resume test asserts the funding-resolution error it reaches, so a refusal before the recipient check would fail it. Co-Authored-By: Claude Fable 5.1 --- packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md | 5 +++-- .../src/wallet/shielded/wallet_drain_tests.rs | 7 +++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index 63f7292ebb7..7d59574c8a0 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: 61** — 27–60 are all claimed (27, 29, 31, 34–42 +**Next allocatable integer: 62** — 27–61 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 @@ -123,7 +123,8 @@ shield debits and durable recovery errors; 58 proposed by #4799 for an unavailab identity balance response; 59 proposed by #5322 for an SPV teardown that needs a process restart; 60 proposed by the pooled Core-to-shielded wallet drain for `ErrorAssetLockTooManyInputs` (Rust, Swift and Kotlin mirrors — -renumbered from 59 when #5322 took that number on `v5.1-dev`); 28, 30, +renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by +#5603 for `ErrorAssetLockRecipientMismatch`; 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 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 a6e0cc497cc..7c59988f9d0 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 @@ -1053,11 +1053,10 @@ async fn should_accept_the_callers_recipient_for_a_legacy_row_without_one() { ) .await .unwrap_err(); + // The recipient check passed and funding resolution ran: this fixture's + // lock address is not in the funding account, which is where it fails. assert!( - !matches!( - error, - PlatformWalletError::AssetLockRecipientMismatch { .. } - ), + matches!(error, PlatformWalletError::AssetLockTransaction(_)), "a legacy row must not refuse the caller's recipient: {error}" ); } From 39cc1e20ee6b948835e2d76c3457aa8234312c82 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Thu, 5 Nov 2026 10:26:06 +0100 Subject: [PATCH 4/7] fix(platform-wallet): make the shielded recipient durable before a non-drain broadcast A typed-amount Core -> Shielded funding only queued its row, so a store failure was logged and nothing was flushed before the broadcast. A kill in that window left a lock the chain can recover but whose recipient is gone, and the resume then accepted any address. On a backend that attests ASSET_LOCK_SHIELDED_RECIPIENTS, a recipient-bearing funding without an operation UUID now stores and flushes its row before the lock is tracked or sent, as the drain does. A failed store or flush aborts before the broadcaster, releases the reservation and returns a Persistence error. Identity, Type 14 and hosts without the capability are unchanged. Co-Authored-By: Claude Fable 5.1 --- .../src/wallet/asset_lock/build.rs | 84 ++++++++++-- .../src/wallet/shielded/wallet_drain_tests.rs | 123 +++++++++++++++++- 2 files changed, 195 insertions(+), 12 deletions(-) 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 85d809b2dea..891f4655a4d 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs @@ -25,9 +25,11 @@ use key_wallet::wallet::managed_wallet_info::ManagedWalletInfo; use key_wallet::wallet::Wallet; use crate::changeset::{ - AccountAddressPoolEntry, AccountRegistrationEntry, AssetLockChangeSet, PlatformWalletChangeSet, + AccountAddressPoolEntry, AccountRegistrationEntry, AssetLockChangeSet, PersistenceCapabilities, + PlatformWalletChangeSet, }; use crate::error::PlatformWalletError; +use crate::wallet::core::InBroadcastPin; use crate::wallet::platform_wallet::PlatformWalletInfo; use crate::ASSET_LOCK_FUNDING_SOURCES; @@ -254,7 +256,7 @@ impl AssetLockManager { DerivationPath, Option, Vec, - crate::wallet::core::InBroadcastPin, + InBroadcastPin, Vec, ), PlatformWalletError, @@ -1171,6 +1173,32 @@ impl AssetLockManager { .await } + /// Settles a build that is abandoned before it reached the broadcaster: + /// the owner-guarded reservation is released across every contributing + /// account and the in-broadcast fence comes down after it. The released + /// verdict is recorded before the cleanup's first await, so a cancellation + /// inside it still settles released — nothing was sent, and a pending-spend + /// fence would wait for a spend that can never be observed. The caller + /// drops the build→persist gate first. + async fn abandon_unsent_build( + &self, + mut in_broadcast_pin: InBroadcastPin, + funding_accounts: &[AccountType], + tx: &Transaction, + reservation_token: Option, + ) { + in_broadcast_pin.settle_released_on_drop(); + crate::wallet::reservations::release_reservation_after_rejected_broadcast( + &self.wallet_manager, + &self.wallet_id, + funding_accounts, + tx, + reservation_token, + ) + .await; + in_broadcast_pin.settle_released(); + } + /// 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, @@ -1400,17 +1428,13 @@ impl AssetLockManager { // inputs that provably never went to the wire (same shape as // the drain-floor branch). drop(build_persist_guard); - let mut in_broadcast_pin = in_broadcast_pin; - in_broadcast_pin.settle_released_on_drop(); - crate::wallet::reservations::release_reservation_after_rejected_broadcast( - &self.wallet_manager, - &self.wallet_id, + self.abandon_unsent_build( + in_broadcast_pin, &funding_accounts, &tx, reservation_token, ) .await; - in_broadcast_pin.settle_released(); if operation.is_some() { return Err(PlatformWalletError::Persistence(format!( "drain funding indices could not be made durable before dispatch: {e}" @@ -1424,6 +1448,14 @@ 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. + let recipient_must_be_durable = operation.is_none() + && 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, @@ -1465,6 +1497,42 @@ impl AssetLockManager { })?; self.track_asset_lock(tracked).await; operation.clear_checkpoint(); + } else if recipient_must_be_durable { + // The recipient exists nowhere but this row: a lock recovered from + // the chain after a kill carries none, and a resume would then pay + // whatever address the caller names. So, like the drain above, the + // row is durable BEFORE it is visible or sent, and a backend that + // cannot record it stops the funding while nothing is on the wire. + if let Some(on_built) = on_built { + on_built(out_point); + } + let mut changeset = AssetLockChangeSet::default(); + changeset.asset_locks.insert(out_point, (&tracked).into()); + let durable = self + .persister + .store(PlatformWalletChangeSet { + asset_locks: Some(changeset), + ..Default::default() + }) + .and_then(|()| self.persister.flush()); + if let Err(error) = durable { + // The row may have committed (a store that succeeded before a + // failed flush). It is never tracked here, and a restart that + // loads it finds the right recipient on it. The funding index + // stays consumed, as for the pool gate above. + drop(build_persist_guard); + self.abandon_unsent_build( + in_broadcast_pin, + &funding_accounts, + &tx, + reservation_token, + ) + .await; + return Err(PlatformWalletError::Persistence(format!( + "shielded recipient was not made durable before dispatch: {error}" + ))); + } + self.track_asset_lock(tracked).await; } else { let cs_built = self.track_asset_lock(tracked).await; // Hand the outpoint to the caller before the row is persisted, so a 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 7c59988f9d0..e2a8a3e2441 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 @@ -94,6 +94,7 @@ struct RecoveryPersistence { fail_flush: AtomicBool, commits_inline: AtomicBool, fail_load: AtomicBool, + records_recipients: AtomicBool, } impl PlatformWalletPersistence for RecoveryPersistence { @@ -101,7 +102,12 @@ impl PlatformWalletPersistence for RecoveryPersistence { self.commits_inline.load(Ordering::SeqCst) } fn persistence_capabilities(&self) -> PersistenceCapabilities { - PersistenceCapabilities::WALLET_DRAIN + if self.records_recipients.load(Ordering::SeqCst) { + PersistenceCapabilities::WALLET_DRAIN + .union(PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS) + } else { + PersistenceCapabilities::WALLET_DRAIN + } } fn store( &self, @@ -233,6 +239,7 @@ async fn signed_wallet_fixture( // exists for `should_refuse_drain_on_a_buffered_persistence_backend`. commits_inline: AtomicBool::new(true), fail_load: AtomicBool::new(false), + records_recipients: AtomicBool::new(true), }); let sdk = Arc::new( dash_sdk::SdkBuilder::new_mock() @@ -1063,7 +1070,8 @@ async fn should_accept_the_callers_recipient_for_a_legacy_row_without_one() { /// A fresh shielded funding records its recipient on the row before the /// lock is dispatched: the drain's durable checkpoint and the typed-amount -/// path's queued row both carry it, even when the broadcast is then refused. +/// path's flushed row both carry it, even when the broadcast is then refused. +/// The typed-amount run is on a buffered backend, where only a flush commits. #[tokio::test] async fn should_record_the_recipient_with_the_lock_before_dispatch() { for drain in [false, true] { @@ -1072,6 +1080,7 @@ async fn should_record_the_recipient_with_the_lock_before_dispatch() { let recipient = crate::test_support::orchard_address_fixture(0x56); let (wallet, persistence, coordinator, _dir, signer) = signed_wallet_fixture(&lock, keys).await; + persistence.commits_inline.store(drain, Ordering::SeqCst); let coordinator = Arc::new(coordinator); let prover = super::prover::CachedOrchardProver::new(); let operation = Arc::new(AssetLockOperationContext::new([0x57; 16])); @@ -1112,8 +1121,7 @@ async fn should_record_the_recipient_with_the_lock_before_dispatch() { .unwrap() .get(&seen[0]) .cloned() - .or_else(|| persistence.staged.lock().unwrap().get(&seen[0]).cloned()) - .expect("the built lock's row reached the persister before the broadcast"); + .expect("the built lock's row was committed before the broadcast"); assert_eq!( stored.shielded_recipient, Some(recipient.to_raw_bytes()), @@ -1122,3 +1130,110 @@ async fn should_record_the_recipient_with_the_lock_before_dispatch() { assert_eq!(stored.operation_id, drain.then_some([0x57; 16])); } } + +/// One typed-amount shielded funding against the fixture, returning the call's +/// error and the outpoints the caller was told about. +async fn fund_typed_amount( + wallet: &PlatformWallet, + coordinator: &Arc, + signer: &WalletSigner, + recipient: dpp::address_funds::OrchardAddress, +) -> (PlatformWalletError, Vec) { + let prover = super::prover::CachedOrchardProver::new(); + let seen = Mutex::new(Vec::new()); + let observer = |out_point: OutPoint| seen.lock().unwrap().push(out_point); + let error = wallet + .shielded_fund_from_asset_lock( + coordinator, + AssetLockFunding::FromWalletBalance { + amount_duffs: 5_000_000, + account_index: 0, + }, + vec![(recipient, None)], + signer, + &prover, + None, + 0, + None, + None, + Some(&observer), + ) + .await + .expect_err("the fixture's SPV client never sends"); + (error, seen.into_inner().unwrap()) +} + +/// 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. +#[tokio::test] +async fn should_abort_typed_amount_funding_when_the_recipient_cannot_be_made_durable() { + for fail_flush in [false, true] { + let (mut lock, keys) = drain_lock_fixture(); + lock.operation_id = None; + let recipient = crate::test_support::orchard_address_fixture(0x58); + let (wallet, persistence, coordinator, _dir, signer) = + signed_wallet_fixture(&lock, keys).await; + let coordinator = Arc::new(coordinator); + persistence.commits_inline.store(false, Ordering::SeqCst); + let switch = if fail_flush { + &persistence.fail_flush + } else { + &persistence.fail_store + }; + + switch.store(true, Ordering::SeqCst); + 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")), + "fail_flush={fail_flush}: {error}" + ); + assert_eq!(seen.len(), 1, "fail_flush={fail_flush}"); + assert!(!wallet + .asset_locks + .list_tracked_locks() + .await + .iter() + .any(|tracked| tracked.out_point == seen[0])); + assert!(!persistence.committed.lock().unwrap().contains_key(&seen[0])); + + // 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_eq!( + persistence.committed.lock().unwrap()[&retried[0]].shielded_recipient, + Some(recipient.to_raw_bytes()) + ); + } +} + +/// A backend that cannot record a recipient keeps the best-effort row every +/// other funding has: a rejected store does not stop the dispatch. +#[tokio::test] +async fn should_keep_best_effort_dispatch_on_a_backend_without_recipient_support() { + let (mut lock, keys) = drain_lock_fixture(); + lock.operation_id = None; + let recipient = crate::test_support::orchard_address_fixture(0x59); + let (wallet, persistence, coordinator, _dir, signer) = signed_wallet_fixture(&lock, keys).await; + let coordinator = Arc::new(coordinator); + persistence + .records_recipients + .store(false, Ordering::SeqCst); + persistence.fail_store.store(true, Ordering::SeqCst); + + let (error, seen) = fund_typed_amount(&wallet, &coordinator, &signer, recipient).await; + + assert!( + !matches!(error, PlatformWalletError::Persistence(_)), + "{error}" + ); + assert_eq!(seen.len(), 1); +} From e518924aa176ac8eaff632462af0a10f9193b835 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Thu, 5 Nov 2026 11:58:15 +0100 Subject: [PATCH 5/7] fix(platform-wallet): withdraw the abandoned row when the recipient checkpoint fails A failed pre-dispatch checkpoint released the inputs while its Built row could still be buffered (SQLite restores a transiently failed flush to its buffer) or committed by a store that preceded the failed flush. A later flush or a restart would then surface a resumable row for released inputs. The row's removal is now queued behind it before the inputs are released. Co-Authored-By: Claude Fable 5.1 --- .../src/wallet/asset_lock/build.rs | 14 +++++++++++--- .../src/wallet/shielded/wallet_drain_tests.rs | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) 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 891f4655a4d..af5dbbf2931 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs @@ -1516,10 +1516,18 @@ impl AssetLockManager { }) .and_then(|()| self.persister.flush()); if let Err(error) = durable { - // The row may have committed (a store that succeeded before a - // failed flush). It is never tracked here, and a restart that - // loads it finds the right recipient on it. The funding index + // 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 { + removed: [out_point].into(), + ..Default::default() + }); drop(build_persist_guard); self.abandon_unsent_build( in_broadcast_pin, 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 e2a8a3e2441..b5ca65d2429 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 @@ -118,7 +118,13 @@ impl PlatformWalletPersistence for RecoveryPersistence { return Err(PersistenceError::backend("store failed")); } if let Some(cs) = cs.asset_locks { - self.staged.lock().unwrap().extend(cs.asset_locks); + let mut staged = self.staged.lock().unwrap(); + staged.extend(cs.asset_locks); + // A removal cancels a row that is still only staged; committed + // rows are kept so tests can read what a broadcast saw. + for out_point in &cs.removed { + staged.remove(out_point); + } } if self.store_commits_inline() { self.commit_staged(); @@ -1167,6 +1173,8 @@ async fn fund_typed_amount( /// 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. #[tokio::test] async fn should_abort_typed_amount_funding_when_the_recipient_cannot_be_made_durable() { for fail_flush in [false, true] { @@ -1208,6 +1216,11 @@ async fn should_abort_typed_amount_funding_when_the_recipient_cannot_be_made_dur "fail_flush={fail_flush}: {error}" ); assert_eq!(retried.len(), 1, "fail_flush={fail_flush}"); + assert_ne!(retried[0], seen[0]); + 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()) From dc092c22b9ec87e7b30cee02a182430952ada5d0 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Fri, 6 Nov 2026 10:11:48 +0100 Subject: [PATCH 6/7] fix(platform-wallet): reconcile the v5.1-dev merge with the shielded recipient field A recovery test fixture added on v5.1-dev builds a TrackedAssetLock without the new field, and the FFI persistence test no longer needs its own Hash import now that the test module brings it in. Co-Authored-By: Claude Fable 5.1 --- packages/rs-platform-wallet-ffi/src/persistence.rs | 1 - .../rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 7a12874f1c0..c1a86ac0a98 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -10054,7 +10054,6 @@ mod tests { /// recipient is simply absent after load) and never attests the bit. #[test] fn should_roundtrip_shielded_recipients_and_tolerate_a_host_without_the_slots() { - use dashcore::hashes::Hash; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; let raw = [0x33u8; 43]; 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 b9dea368d72..819e45b89a4 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 @@ -6256,6 +6256,7 @@ mod tests { amount: amount_duffs, status, proof: None, + shielded_recipient: None, }, ); } From daeb18d3a32f613645c92fa7cb6b684f59a902b7 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Fri, 6 Nov 2026 10:38:33 +0100 Subject: [PATCH 7/7] fix(swift-sdk): move the asset-lock shielded recipient to DashSchemaV5 Schema 4.0.0 was published and frozen (#5785), so the recipient attribute can no longer change V4 in place. DashSchemaV4 is bound to its released snapshot, DashSchemaV5 carries the live models, and both migration plans gain a lightweight V4 -> V5 stage. The store-open route labels, the tests that pin the current version and the future-version bridge fixture follow. Co-Authored-By: Claude Fable 5.1 --- packages/swift-sdk/SCHEMA_RELEASES.md | 3 +- .../Persistence/DashModelContainer.swift | 36 ++++++++++++------- .../AssetLockOperationPersistenceTests.swift | 2 +- .../DashLegacySchemaMigrationTests.swift | 15 ++++---- .../DashModelMigrationTests.swift | 14 ++++---- 5 files changed, 43 insertions(+), 27 deletions(-) diff --git a/packages/swift-sdk/SCHEMA_RELEASES.md b/packages/swift-sdk/SCHEMA_RELEASES.md index d9b6170b7c7..bc9c7f29453 100644 --- a/packages/swift-sdk/SCHEMA_RELEASES.md +++ b/packages/swift-sdk/SCHEMA_RELEASES.md @@ -30,7 +30,8 @@ discovering them afterwards as failed opens. The route decision is logged as `store_migration_route` with the validated `source_version`, `source_checksum` and one of `new-store`, `accepted-v1-to-v3`, `historical-v2-to-v3`, `previous-live-v2-current-shape`, -`unsupported-v2`, `labelled-current-v3`, `ordinary-current-plan` or, from the +`unsupported-v2`, `published-v3-to-v4`, `published-v4-to-v5`, +`labelled-current-v5`, `ordinary-current-plan` or, from the bridge, `legacy-v1-bridge-to-v3`. Resolving a frozen schema's identity builds a temporary store, so it is memoized per process and consulted only where a label is undecidable without it (`1.0.0`, `2.0.0`); a `3.0.0` label takes the diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift index ba455874d35..e1ba0479049 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift @@ -100,7 +100,7 @@ public enum DashModelContainer { /// Create the schema for all Dash Platform models public static var schema: Schema { - Schema(versionedSchema: DashSchemaV4.self) + Schema(versionedSchema: DashSchemaV5.self) } /// Create a persistent model container for storing data. @@ -172,7 +172,7 @@ public enum DashModelContainer { bridgeLegacyStore: Bool = true ) throws -> ModelContainer { SDKLogger.event("store_open_started", category: .persistence, - fields: ["target_version": .publicText("4.0.0")]) + fields: ["target_version": .publicText("5.0.0")]) do { let container: ModelContainer if bridgeLegacyStore { @@ -185,7 +185,7 @@ public enum DashModelContainer { configurations: [configuration]) } SDKLogger.event("store_open_succeeded", category: .persistence, - fields: ["target_version": .publicText("4.0.0")]) + fields: ["target_version": .publicText("5.0.0")]) return container } catch { logMigrationFailure(error) @@ -201,7 +201,7 @@ public enum DashModelContainer { let domain = systemDomains.contains(nsError.domain) ? nsError.domain : String(reflecting: type(of: error)) SDKLogger.event("store_open_failed", category: .persistence, severity: .error, fields: ["error_domain": .publicText(domain), "error_code": .integer(Int64(nsError.code)), - "target_version": .publicText("4.0.0")]) + "target_version": .publicText("5.0.0")]) } /// Select by the complete stored model identity, after journal recovery. @@ -218,7 +218,7 @@ public enum DashModelContainer { guard ObjectIdentifier(defaultPlan) == ObjectIdentifier(DashMigrationPlan.self) else { return defaultPlan } guard FileManager.default.fileExists(atPath: url.path) else { SDKLogger.event("store_migration_route", category: .persistence, fields: [ - "route": .publicText("new-store"), "target_version": .publicText("4.0.0")]) + "route": .publicText("new-store"), "target_version": .publicText("5.0.0")]) return defaultPlan } let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(type: .sqlite, at: url) @@ -236,7 +236,7 @@ public enum DashModelContainer { func logRoute(_ route: String) { SDKLogger.event("store_migration_route", category: .persistence, fields: [ "source_version": .publicText(safeVersions), "source_checksum": .publicText(safeChecksum), - "route": .publicText(route), "target_version": .publicText("4.0.0")]) + "route": .publicText(route), "target_version": .publicText("5.0.0")]) } func matches(_ type: any VersionedSchema.Type) throws -> Bool { let expected = try identity(type) @@ -268,7 +268,9 @@ public enum DashModelContainer { // `source_checksum` above already identifies the exact graph. logRoute("published-v3-to-v4") } else if versions == ["4.0.0"] { - logRoute("labelled-current-v4") + logRoute("published-v4-to-v5") + } else if versions == ["5.0.0"] { + logRoute("labelled-current-v5") } else { logRoute("ordinary-current-plan") } @@ -289,13 +291,14 @@ public enum DashModelContainer { /// SwiftData migration plan for Dash Platform model updates public enum DashMigrationPlan: SchemaMigrationPlan { public static var schemas: [any VersionedSchema.Type] { - [DashSchemaV2.self, DashSchemaV3.self, DashSchemaV4.self] + [DashSchemaV2.self, DashSchemaV3.self, DashSchemaV4.self, DashSchemaV5.self] } public static var stages: [MigrationStage] { [ .lightweight(fromVersion: DashSchemaV2.self, toVersion: DashSchemaV3.self), - .lightweight(fromVersion: DashSchemaV3.self, toVersion: DashSchemaV4.self) + .lightweight(fromVersion: DashSchemaV3.self, toVersion: DashSchemaV4.self), + .lightweight(fromVersion: DashSchemaV4.self, toVersion: DashSchemaV5.self) ] } } @@ -303,10 +306,13 @@ public enum DashMigrationPlan: SchemaMigrationPlan { /// Separate compatibility route: V1 has fields missing from historical V2. /// Never insert V2 between this baseline and the current schema. enum DashAcceptedV1MigrationPlan: SchemaMigrationPlan { - static var schemas: [any VersionedSchema.Type] { [DashSchemaV1.self, DashSchemaV3.self, DashSchemaV4.self] } + static var schemas: [any VersionedSchema.Type] { + [DashSchemaV1.self, DashSchemaV3.self, DashSchemaV4.self, DashSchemaV5.self] + } static var stages: [MigrationStage] { [.lightweight(fromVersion: DashSchemaV1.self, toVersion: DashSchemaV3.self), - .lightweight(fromVersion: DashSchemaV3.self, toVersion: DashSchemaV4.self)] + .lightweight(fromVersion: DashSchemaV3.self, toVersion: DashSchemaV4.self), + .lightweight(fromVersion: DashSchemaV4.self, toVersion: DashSchemaV5.self)] } } @@ -382,8 +388,14 @@ public enum DashSchemaV3: VersionedSchema { public static var models: [any PersistentModel.Type] { DashSchemaSnapshotV3.models } } -/// Current schema: optional asset-lock operation IDs correlate drain recovery. +/// Published V4 (optional asset-lock operation IDs). Its complete model graph is frozen. public enum DashSchemaV4: VersionedSchema { public static var versionIdentifier: Schema.Version { Schema.Version(4, 0, 0) } + public static var models: [any PersistentModel.Type] { DashSchemaSnapshotV4.models } +} + +/// Current schema: an asset lock records the optional Orchard recipient of its shielded funding. +public enum DashSchemaV5: VersionedSchema { + public static var versionIdentifier: Schema.Version { Schema.Version(5, 0, 0) } public static var models: [any PersistentModel.Type] { DashModelContainer.modelTypes } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift index cafd35600cc..6c6888c53f4 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift @@ -122,7 +122,7 @@ final class AssetLockOperationPersistenceTests: XCTestCase { XCTAssertNil(rows.first?.operationId) XCTAssertNil(rows.first?.shieldedRecipientRaw43) XCTAssertEqual(rows.first?.amountDuffs, 1000) - XCTAssertEqual(DashModelContainer.schema.version, Schema.Version(4, 0, 0)) + XCTAssertEqual(DashModelContainer.schema.version, Schema.Version(5, 0, 0)) } func testMalformedOperationIdFailsLoadInsteadOfBecomingAbsent() throws { diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift index d3c07c9f73f..b07ad5a84f2 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift @@ -11,16 +11,19 @@ private final class BridgeFutureMarker { var value: String = "future" init() {} } -private enum BridgeFutureV5: VersionedSchema { - static var versionIdentifier: Schema.Version { Schema.Version(5, 0, 0) } - static var models: [any PersistentModel.Type] { DashSchemaV4.models + [BridgeFutureMarker.self] } +private enum BridgeFutureV6: VersionedSchema { + static var versionIdentifier: Schema.Version { Schema.Version(6, 0, 0) } + static var models: [any PersistentModel.Type] { DashSchemaV5.models + [BridgeFutureMarker.self] } } private enum BridgeFuturePlan: SchemaMigrationPlan { - static var schemas: [any VersionedSchema.Type] { [DashSchemaV1.self, DashSchemaV3.self, DashSchemaV4.self, BridgeFutureV5.self] } + static var schemas: [any VersionedSchema.Type] { + [DashSchemaV1.self, DashSchemaV3.self, DashSchemaV4.self, DashSchemaV5.self, BridgeFutureV6.self] + } static var stages: [MigrationStage] { [.lightweight(fromVersion: DashSchemaV1.self, toVersion: DashSchemaV3.self), .lightweight(fromVersion: DashSchemaV3.self, toVersion: DashSchemaV4.self), - .custom(fromVersion: DashSchemaV4.self, toVersion: BridgeFutureV5.self, + .lightweight(fromVersion: DashSchemaV4.self, toVersion: DashSchemaV5.self), + .custom(fromVersion: DashSchemaV5.self, toVersion: BridgeFutureV6.self, willMigrate: { context in for wallet in try context.fetch(FetchDescriptor()) { wallet.name = "explicit future transformation" @@ -771,7 +774,7 @@ final class DashLegacySchemaMigrationTests: XCTestCase { func testSkippingV3UsesFixedBridgeThenRegisteredCustomFutureStage() throws { try withStore { url in - let schema = Schema(versionedSchema: BridgeFutureV5.self) + let schema = Schema(versionedSchema: BridgeFutureV6.self) var checkedV3 = false let configuration = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none) XCTAssertThrowsError(try DashLegacySchemaBridge.open( diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift index e2ea9489f0a..94ee9120cf3 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift @@ -78,8 +78,8 @@ final class DashModelMigrationTests: XCTestCase { XCTAssertTrue(log.contains("route=\"historical-v2-to-v3\"")) XCTAssertTrue(log.contains("source_version=\"2.0.0\"")) XCTAssertTrue(log.contains("source_checksum=\"\(sourceChecksum)\"")) - XCTAssertTrue(log.contains("target_version=\"4.0.0\"")) - XCTAssertTrue(log.contains("route=\"labelled-current-v4\"")) + XCTAssertTrue(log.contains("target_version=\"5.0.0\"")) + XCTAssertTrue(log.contains("route=\"labelled-current-v5\"")) XCTAssertEqual(log.components(separatedBy: "event=store_open_succeeded").count - 1, 2) XCTAssertFalse(log.contains("event=store_open_failed")) XCTAssertFalse(log.contains(directory.path)) @@ -95,7 +95,7 @@ final class DashModelMigrationTests: XCTestCase { let updatedLog = try String(contentsOf: session.appendingPathComponent("swift/run.log"), encoding: .utf8) XCTAssertTrue(updatedLog.contains("route=\"new-store\"")) let failure = try XCTUnwrap(updatedLog.split(separator: "\n").first { $0.contains("event=store_open_failed") }) - XCTAssertTrue(failure.contains("target_version=\"4.0.0\"")) + XCTAssertTrue(failure.contains("target_version=\"5.0.0\"")) XCTAssertTrue(failure.contains("error_code=")) XCTAssertFalse(updatedLog.contains(directory.path)) XCTAssertFalse(updatedLog.contains("private-invalid-store-content")) @@ -106,7 +106,7 @@ final class DashModelMigrationTests: XCTestCase { /// either way. Labels whose route is undecidable without that probe /// (accepted V1 versus the bridge, historical V2 versus a beta layout) /// keep failing closed, leaving the store untouched. - func testCurrentV4RouteNeverDependsOnTheSchemaIdentityProbe() throws { + func testCurrentV5RouteNeverDependsOnTheSchemaIdentityProbe() throws { struct ProbeUnavailable: Error {} let failingProbe: (any VersionedSchema.Type) throws -> DashLegacySchemaBridge.Identity = { _ in throw ProbeUnavailable() @@ -117,7 +117,7 @@ final class DashModelMigrationTests: XCTestCase { defer { try? FileManager.default.removeItem(at: directory) } let current = directory.appendingPathComponent("current.store") try autoreleasepool { _ = try DashModelContainer.create(url: current) } - XCTAssertEqual(try DashLegacySchemaBridge.identity(at: current).versions, ["4.0.0"]) + XCTAssertEqual(try DashLegacySchemaBridge.identity(at: current).versions, ["5.0.0"]) let plan = try DashModelContainer.migrationPlan( at: current, defaultPlan: DashMigrationPlan.self, identity: failingProbe) XCTAssertTrue(ObjectIdentifier(plan) == ObjectIdentifier(DashMigrationPlan.self)) @@ -513,7 +513,7 @@ final class DashModelMigrationTests: XCTestCase { try v1Container?.mainContext.save() v1Container = nil - let v2Schema = Schema(versionedSchema: DashSchemaV4.self) + let v2Schema = Schema(versionedSchema: DashSchemaV5.self) let v2Configuration = ModelConfiguration( "DashKeyLimitsMigrationTest", schema: v2Schema, @@ -590,7 +590,7 @@ final class DashModelMigrationTests: XCTestCase { try v1Container?.mainContext.save() v1Container = nil - let v2Schema = Schema(versionedSchema: DashSchemaV4.self) + let v2Schema = Schema(versionedSchema: DashSchemaV5.self) let v2Configuration = ModelConfiguration( "DashContractBoundsKindMigrationTest", schema: v2Schema,