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 211a7d709ca..924a90304f3 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 @@ -177,6 +178,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). Two meanings. On a build: nothing was broadcast, the reservation is released, no partial drain, and a rebuild after consolidating is safe. On the resume of a tracked `Built` / `Broadcast` lock over the cap (since #5714): it is not re-sent, but an earlier attempt may have reached peers; the row stays tracked and nothing is released. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | +| 61 | `ErrorAssetLockRecipientMismatch` | dashpay/platform#5603 (tracked-lock shielded recipient) | Proposed — a shielded fund-from-asset-lock resume (the generic outpoint resume or a repeated-UUID wallet drain) names a different Orchard recipient than the one the tracked lock recorded when it was built. Nothing was submitted or paid; resume with the recorded recipient, which the row and `TrackedAssetLockFFI` expose. Rows tracked before recipients were recorded carry none and accept the caller's. Typed in Rust, Swift and Kotlin | **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..69141b9a065 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,8 @@ 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.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 eb4b9e74127..c20fb4adbf5 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 @@ -1050,6 +1057,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. @@ -2249,6 +2259,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 = [1u8; 43]; + let requested = [2u8; 43]; + 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))); + } + #[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 eb5865fc361..c1a86ac0a98 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -161,6 +161,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 +330,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 +518,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 +561,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 +584,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 +1717,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 +2763,41 @@ 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 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 +3585,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() { @@ -6243,6 +6359,40 @@ fn load_asset_lock_operation_ids( Ok(()) } +/// Rehydrate the shielded-recipient sidecar after decoding the frozen legacy +/// 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, + 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; platform_wallet::changeset::SHIELDED_RECIPIENT_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 = found.then_some(raw); + } + 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 @@ -6344,6 +6494,7 @@ fn build_unused_asset_locks( identity_index: spec.identity_index, amount: spec.amount_duffs, operation_id: None, + shielded_recipient: None, status, proof, }; @@ -9815,6 +9966,7 @@ mod tests { status: status.clone(), proof: None, operation_id, + shielded_recipient: None, }; let (entries, _storage) = build_asset_lock_entries(&[&entry]); let wallet = WalletRestoreEntryFFI { @@ -9896,6 +10048,149 @@ 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 key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; + + let raw = [0x33u8; 43]; + 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(raw), + }; + 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); + } + + 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( @@ -10268,6 +10563,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!( @@ -10330,6 +10645,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 @@ -12627,6 +12946,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 232d8a9a9c8..c135350795d 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -853,7 +853,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 { .. } @@ -3126,6 +3127,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: [1; 43], + requested: [2; 43], + }), + "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-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/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 ced3c0e2ec6..e0bb8032e06 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 @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; 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; @@ -62,6 +62,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 +122,7 @@ impl AssetLockEntryWire { status: self.status, proof, operation_id: None, + shielded_recipient: None, }) } } @@ -147,30 +149,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 +188,19 @@ pub fn apply( )); } } + let shielded_recipient = entry.shielded_recipient; + 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 +223,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 +320,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 +333,15 @@ fn decode_row( }) }) .transpose()?; + entry.shielded_recipient = shielded_recipient + .map(|bytes| { + <[u8; SHIELDED_RECIPIENT_SIZE]>::try_from(bytes).map_err(|_| { + WalletStorageError::blob_decode( + "asset_locks.shielded_recipient must contain 43 bytes", + ) + }) + }) + .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 +384,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 +400,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 +413,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 +441,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 +454,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() { @@ -490,6 +526,7 @@ mod tests { funding_type: AssetLockFundingType::IdentityRegistration, identity_index: 0, operation_id: None, + shielded_recipient: None, amount_duffs: 1000, status, proof, @@ -528,6 +565,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") } @@ -718,6 +756,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 f8e1250bf09..3c3a14eafa3 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 @@ -9,7 +9,10 @@ use crate::common; use common::{ensure_wallet_meta, fresh_persister, wid}; 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; @@ -35,6 +38,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, @@ -339,3 +343,107 @@ 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 = recipient_bytes(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(recipient_bytes(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", + [recipient_bytes(0x13).to_vec()] + ) + .is_err()); +} + +#[test] +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); + 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(); + // 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; 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() + ); +} + +#[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_blob_roundtrip_coverage.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_blob_roundtrip_coverage.rs index d3b06a00f37..538f310b37e 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 @@ -52,6 +52,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 b473251becb..b2fe76f2c9e 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 @@ -1087,6 +1087,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, @@ -1392,6 +1393,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 c33c3959fbc..58cc3c18f3b 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 @@ -406,6 +406,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, @@ -472,6 +473,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 { @@ -543,6 +545,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 f99dd4d9310..b5b136ff238 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 @@ -290,6 +290,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_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-storage/tests/integration/sqlite_structural_hardening.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_structural_hardening.rs index fdbb97788c7..6671c463a72 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 @@ -377,6 +377,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 d51d95f7e35..acf6835a3e9 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 @@ -365,6 +365,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 36d3faeef7c..0611158faf1 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -1493,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 @@ -1527,17 +1539,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_shielded_recipient" + ) + )] + 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 +1574,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 +1605,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; } } @@ -2737,6 +2775,7 @@ mod tests { }; let entry_with = |status: AssetLockStatus| AssetLockEntry { operation_id: None, + shielded_recipient: None, out_point: outpoint, transaction: Transaction { version: 3, @@ -2805,6 +2844,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 = [0x71u8; SHIELDED_RECIPIENT_SIZE]; + 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([0x72; SHIELDED_RECIPIENT_SIZE]); + 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). @@ -3452,6 +3519,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 407ad4325d5..9706a17a14d 100644 --- a/packages/rs-platform-wallet/src/changeset/core_bridge.rs +++ b/packages/rs-platform-wallet/src/changeset/core_bridge.rs @@ -7941,6 +7941,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/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/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..d4deed2a0a9 100644 --- a/packages/rs-platform-wallet/src/changeset/serde_adapters.rs +++ b/packages/rs-platform-wallet/src/changeset/serde_adapters.rs @@ -208,3 +208,90 @@ mod optional_asset_lock_proof_tests { ); } } + +/// 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 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 crate::changeset::{ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; + + pub fn serialize( + value: &Option, + serializer: S, + ) -> Result { + value.map(|raw| raw.to_vec()).serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let bytes = Option::>::deserialize(deserializer)?; + bytes + .map(|bytes| { + 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(test)] +mod optional_shielded_recipient_tests { + use crate::changeset::{ShieldedRecipientRaw, SHIELDED_RECIPIENT_SIZE}; + + #[derive(serde::Serialize, serde::Deserialize)] + struct Carrier { + #[serde(with = "super::optional_shielded_recipient")] + 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 = [0x5au8; SHIELDED_RECIPIENT_SIZE]; + assert_eq!(roundtrip(Some(recipient)).unwrap(), Some(recipient)); + assert_eq!(roundtrip(None).unwrap(), None); + } + + #[test] + 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 02424fe16d8..b7c9e0d7b2e 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -646,6 +646,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), + hex::encode(requested) + )] + AssetLockRecipientMismatch { + out_point: dashcore::OutPoint, + recorded: crate::changeset::ShieldedRecipientRaw, + requested: crate::changeset::ShieldedRecipientRaw, + }, + #[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 25cbd8f5f5b..9dd50f7e669 100644 --- a/packages/rs-platform-wallet/src/test_support.rs +++ b/packages/rs-platform-wallet/src/test_support.rs @@ -956,6 +956,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..f1bccb35b8b 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 = [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); + + // 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([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)); + 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 ac46e6fa3c9..592cd028917 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/build.rs @@ -6,6 +6,7 @@ use crate::broadcaster::TransactionBroadcaster; use std::time::Duration; +use crate::changeset::ShieldedRecipientRaw; use dashcore::Address as DashAddress; use dashcore::{OutPoint, Transaction, TxOut}; use key_wallet::account::AccountType; @@ -24,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; @@ -253,7 +256,7 @@ impl AssetLockManager { DerivationPath, Option, Vec, - crate::wallet::core::InBroadcastPin, + InBroadcastPin, Vec, ), PlatformWalletError, @@ -928,6 +931,7 @@ impl AssetLockManager { account_index, funding_type, identity_index, + None, signer, None, ) @@ -936,12 +940,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 +957,7 @@ impl AssetLockManager { account_index, funding_type, identity_index, + shielded_recipient, signer, on_built, ) @@ -976,6 +983,7 @@ impl AssetLockManager { funding_account, funding_type, identity_index, + None, signer, None, ) @@ -984,6 +992,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 +1001,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 +1011,7 @@ impl AssetLockManager { funding_account.account_index(), funding_type, identity_index, + shielded_recipient, signer, on_built, ) @@ -1022,17 +1033,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 +1122,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 +1158,64 @@ 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 + } + + /// 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, + /// 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()?; @@ -1349,17 +1423,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}" @@ -1373,6 +1443,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, @@ -1383,6 +1461,7 @@ impl AssetLockManager { amount: locked_amount_duffs, status: AssetLockStatus::Built, proof: None, + shielded_recipient, }; if let Some(operation) = operation { operation.retain_checkpoint(tracked.clone()); @@ -1413,6 +1492,50 @@ 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 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, + &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 @@ -2011,6 +2134,7 @@ mod tests { amount: entry.amount_duffs, status: entry.status.clone(), proof: entry.proof.clone(), + shielded_recipient: entry.shielded_recipient, }, ); } @@ -2436,6 +2560,7 @@ mod tests { }, AssetLockFundingType::AssetLockAddressTopUp, 0, + None, &signer, Some(&observer), ) @@ -2465,6 +2590,7 @@ mod tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &signer, Some(&observer), ) @@ -3406,6 +3532,7 @@ mod tests { }, AssetLockFundingType::IdentityRegistration, 0, + None, &signer, None, ) @@ -3436,6 +3563,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..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,6 +34,7 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; +use crate::changeset::ShieldedRecipientRaw; use dashcore::OutPoint; use dpp::prelude::AssetLockProof; use key_wallet::bip32::DerivationPath; @@ -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 4ed6033a54f..3a1b7623bd4 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 @@ -2164,6 +2164,7 @@ mod chain_lock_wait_tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -2268,6 +2269,7 @@ mod chain_lock_wait_tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -3453,6 +3455,7 @@ mod chain_lock_wait_tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &ctx.signer, None, ), @@ -3490,6 +3493,7 @@ mod chain_lock_wait_tests { }, AssetLockFundingType::AssetLockShieldedAddressTopUp, 0, + None, &ctx.signer, None, ), @@ -3729,6 +3733,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 b1fa14d4d94..68639545469 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, @@ -765,6 +766,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: tx.clone(), account_index: 0, @@ -1001,6 +1003,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 bbc92c1aa05..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 @@ -108,6 +108,7 @@ impl AssetLockManager { } let lock = TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: tx, account_index, @@ -2224,6 +2225,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction: transaction.clone(), account_index: 0, @@ -2360,6 +2362,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -2584,6 +2587,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, @@ -2861,6 +2865,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, @@ -4372,6 +4377,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -4886,6 +4892,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5010,6 +5017,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5513,6 +5521,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5618,6 +5627,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -5897,6 +5907,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -6042,6 +6053,7 @@ mod tests { out_point, TrackedAssetLock { operation_id: None, + shielded_recipient: None, out_point, transaction, account_index: 0, @@ -6244,6 +6256,7 @@ mod tests { amount: amount_duffs, status, proof: None, + shielded_recipient: None, }, ); } diff --git a/packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs b/packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs index e8c6ba57f41..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 @@ -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..8294b98793b 100644 --- a/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs +++ b/packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs @@ -12,7 +12,7 @@ use dashcore::{OutPoint, Transaction}; 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. /// @@ -145,6 +145,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 +166,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..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; @@ -270,6 +272,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 +397,7 @@ impl PlatformWallet { funding, AssetLockFundingType::AssetLockShieldedAddressTopUp, /* destination_index */ 0, + Some(recipient.to_raw_bytes()), asset_lock_signer, on_asset_lock_built, ) @@ -469,8 +489,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 +968,32 @@ 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. +/// +/// 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, + requested: OrchardAddress, +) -> Result { + const _: () = assert!(SHIELDED_RECIPIENT_SIZE == ORCHARD_ADDRESS_SIZE); + match recorded { + None => Ok(requested), + Some(recorded) if recorded == requested.to_raw_bytes() => Ok(requested), + Some(recorded) => Err(PlatformWalletError::AssetLockRecipientMismatch { + out_point, + recorded, + requested: requested.to_raw_bytes(), + }), + } +} + pub(super) fn validate_shielded_recipients( recipients: &[(T, Option)], ) -> Result<(), PlatformWalletError> { @@ -1056,6 +1100,31 @@ 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.to_raw_bytes()), recorded).unwrap(), + recorded + ); + assert_eq!(resume_recipient(out_point, None, other).unwrap(), other); + assert!(matches!( + 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.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 { .. }) + )); + } + #[test] fn validate_rejects_empty_recipients() { let v: Vec<(u8, Option)> = Vec::new(); @@ -1218,6 +1287,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..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 @@ -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)]), ) @@ -93,6 +94,7 @@ struct RecoveryPersistence { fail_flush: AtomicBool, commits_inline: AtomicBool, fail_load: AtomicBool, + records_recipients: AtomicBool, } impl PlatformWalletPersistence for RecoveryPersistence { @@ -100,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, @@ -111,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(); @@ -147,6 +160,7 @@ impl PlatformWalletPersistence for RecoveryPersistence { amount: row.amount_duffs, status: row.status.clone(), proof: row.proof.clone(), + shielded_recipient: row.shielded_recipient, }, ) }) @@ -231,6 +245,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() @@ -698,6 +713,7 @@ async fn should_refuse_drain_on_a_buffered_persistence_backend() { }, lock.funding_type, 0, + None, &signer, None, ) @@ -902,3 +918,335 @@ 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.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; + 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.to_raw_bytes() && *q == other.to_raw_bytes() + ), + "{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.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; + 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(); + // 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::AssetLockTransaction(_)), + "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 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] { + 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; + 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])); + 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() + .expect("the built lock's row was committed before the broadcast"); + assert_eq!( + stored.shielded_recipient, + Some(recipient.to_raw_bytes()), + "drain={drain}" + ); + 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. +/// 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] { + 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_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()) + ); + } +} + +/// 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); +} 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/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/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index 63b20689d2c..292f790b408 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 f1d499682d7..7bc7e76188e 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 @@ -3257,6 +3310,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { | PlatformWalletPersistenceCapabilities.coreSweepRemoval | PlatformWalletPersistenceCapabilities.dashpayPayments | PlatformWalletPersistenceCapabilities.assetLockOperationIds + | PlatformWalletPersistenceCapabilities.assetLockShieldedRecipients ) } @@ -3296,6 +3350,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 +11956,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 b8a2f107ad7..15f618e0bee 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: @@ -587,6 +592,14 @@ public enum PlatformWalletError: LocalizedError { /// tracked lock over the cap: it is not re-sent (an earlier attempt may /// have reached the network), it stays tracked, and nothing is released. 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 @@ -811,7 +824,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), @@ -930,6 +943,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..6c6888c53f4 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,8 +120,9 @@ 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)) + 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, 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,