diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index 864882deb95..4e949c6e9fa 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: 76**: 27–75 are all claimed (27, 29, 31, 34–42 +**Next allocatable integer: 77**: 27–76 are all claimed (27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their rows below); 49–54 proposed by active #4586 (the persister @@ -128,7 +128,7 @@ renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by by open branches with no row here yet (62 both `ErrorShieldedClaimBindingMismatch` and `ErrorIdentityRevisionMismatch`, 63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 -to 75 proposed for DashPay private contact requests; 28, 30, +to 76 proposed for DashPay private contact requests; 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 @@ -183,15 +183,15 @@ Fork-era numbers remain in the collision history, which is immutable record. | 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 in Platform consensus for an instant proof): the full drain, or since #5712 a fixed amount held only in many small coins (identity registration, top-up, invitation, platform-address funding). Two meanings. On a build: nothing was broadcast, the reservation is released, no partial drain, and a rebuild after consolidating is safe. On the resume of a tracked `Built` / `Broadcast` lock over the cap (since #5714): it is not re-sent, but an earlier attempt may have reached peers; the row stays tracked and nothing is released. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | | 61 | `ErrorAssetLockRecipientMismatch` | dashpay/platform#5603 (tracked-lock shielded recipient) | Proposed — a shielded fund-from-asset-lock resume (the generic outpoint resume or a repeated-UUID wallet drain) names a different Orchard recipient than the one the tracked lock recorded when it was built. Nothing was submitted or paid; resume with the recorded recipient, which the row and `TrackedAssetLockFFI` expose. Rows tracked before recipients were recorded carry none and accept the caller's. Typed in Rust, Swift and Kotlin | -| 68 | `ErrorPrivateContactRequestNeedsPrivateReply` | DashPay private contact requests | Proposed. The contact requests with that identity came or went privately (protocol version 15), so a `contactRequest` document to it, in reply or as a rotation, would publish the relationship: the public accept refuses a reply, and the public send refuses a request or a rotation. Nothing was sent; the request goes privately instead, and the in-kind accept picks the private reply itself. The shielded spend contract (`map_spend_result`) keeps the code, as the in-kind accept can raise it. Taken above 61–67, which open branches already hold. The exports that send and accept contact requests, and the Swift and Kotlin typing, are added by the FFI PR (#5812) and the Kotlin PR (#5813); in this tree it reaches a host through the blanket conversion | -| 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number. No export in this tree returns it yet: the in-kind accept export, and the Swift and Kotlin typing, are added by the FFI PR (#5812) and the Kotlin PR (#5813) | -| 70 | `ErrorProtocolVersionNotActive` | DashPay private contact requests | Proposed. The SDK refused a request without sending it (`dash_sdk::Error::ProtocolVersionNotActive`, not pinned) because the network is proven at a protocol version below the one that serves it: for example the private contact request sync on a network before protocol version 15. Expected on such a network, so a host may stay quiet about it; it lifts when the network upgrades. An SDK pinned below the required version has its own code, 75. Mapped by the blanket conversion for every operation that propagates the SDK error. A refusal that may lift sooner (`is_transient_protocol_version_refusal`: the network's version could not be confirmed) keeps the catch-all `ErrorUnknown`, as before. Previously both fell to `ErrorUnknown`. Swift and Kotlin typing is added by the FFI PR (#5812) and the Kotlin PR (#5813) | -| 71 | `ErrorPrivateContactRequestPending` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactRequestPending`: a private contact request to that identity is in flight (another private send or reply reserved it before sealing), or was paid for and a short read-back sync did not find the entry in the store yet, or a private payment the shielded store's journal keeps unresolved holds the pair. Nothing new was paid; a later private contact request sync settles it once the entry is read back, and the shielded sync once the payment provably never executes. Pending, not failed: the host must not submit it again. A private store read that did not finish before the request was decided is 74, not 71. The shielded spend contract (`map_spend_result`) keeps the code rather than flattening it to `ErrorWalletOperation`. Swift and Kotlin typing is added by the FFI PR (#5812) and the Kotlin PR (#5813) | -| 72 | `ErrorPrivateContactPaymentsNotRestored` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactPaymentsNotRestored`: wallet readiness, not one contact's pending request (71). The wallet's unconfirmed private payments may hold pairs no reservation shows yet, which only a restoration from the shielded store's journal shows. In a build with the `shielded` feature: the wallet was published (created or loaded) while no shielded store was configured, its persister declaring the private scan state (bit 15), which holds a wallet removed and registered again from the same seed, in this process or a new one; it was loaded after binding a shielded account in an earlier process; or its last restoration failed, or waits for a busy store. In every build: the identity was loaded with its private scan state marking a private payment that may be unresolved, or was added to a wallet whose backend kept its record marked after an earlier wallet under the id was removed (`ClientStartState::retained_private_contact_scan_states`). Contact requests and acceptances, public and private, are refused with nothing read, signed or broadcast until they are restored: configuring the shielded store restores them with no keys, as binding the wallet's shielded account does, and a contact request first retries a restoration once without waiting on the store; a private sync does not, and a build without the `shielded` feature never does. A host whose persister declares the private scan state configures the shielded store when it activates the manager, before loading or creating wallets: until it does, and while a failed configure is not retried, 72 holds. `platform_wallet_get_private_contact_readiness` reads whether the payments are restored and whether the last restoration failed (`private_payments_restore_failed`; the wallet's `PrivateContactReadiness::private_payments_restore_failure` holds the reason). Swift and Kotlin typing is added by the FFI PR (#5812) and the Kotlin PR (#5813); hosts treat it as held until the readiness reads restored | -| 73 | `ErrorPrivateContactRecoveryUnsupported` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactRecoveryUnsupported`: the persister does not declare `PRIVATE_CONTACT_REQUEST_SCAN_STATE` (bit 15) together with `ATOMIC_CHANGESETS` (bit 0, with the changeset begin and end callbacks wired), so the private send, the private accept and the in-kind accept's private reply are refused before anything is sealed or paid. The payment's recovery marker could not survive a restart, and a process reopening the wallet without the `shielded` feature, or before the shielded store is configured, could publish the pair while the payment may still execute. Not retryable as it is: a host that persists the private contact request scan state in changesets it commits whole declares both. The FFI constant for bit 15 and the Swift and Kotlin typing are added by the FFI PR (#5812) and the Kotlin PR (#5813) | -| 74 | `ErrorPrivateContactStoreNotRead` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactStoreNotRead`: DashPay's private contact request store was not read to its end for the identity, with the keys Platform proves it holds, before a contact request or acceptance, public or private, was decided (every one reads it from the identity's cursor first). Nothing was reserved, sealed, paid or broadcast; calling again continues the read from where it stopped. A node behind the store already seen, or keys that kept changing, stop it. It was reported as 71 before, which says not to submit again. Mapped by the blanket conversion and kept by the shielded spend contract (`map_spend_result`). Swift and Kotlin typing is added by the FFI PR (#5812) and the Kotlin PR (#5813) | -| 75 | `ErrorSdkPinnedBelowProtocolVersion` | DashPay private contact requests | Proposed. The SDK refused a request without sending it because the SDK itself is pinned below the protocol version the request needs (`dash_sdk::Error::ProtocolVersionNotActive` with `pinned`), whatever the network runs: for example every contact request's private store read with the SDK pinned below protocol version 15 on a network at 15. A network upgrade does not lift it; only raising or removing the pin does. Before, it shared 70 with a network proven below the version, which lifts by itself. Mapped by the blanket conversion. Swift and Kotlin typing is added by the FFI PR (#5812) and the Kotlin PR (#5813) | -| 76 | `ErrorPublicContactRequestUnconfirmed` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PublicContactRequestUnconfirmed`: a public contact request to that identity was broadcast and may have been delivered, and no proof settled its outcome yet, so the wallet holds the pair and signs nothing new to it, public or private. The send or accept that broadcast it reported 20; every later one is refused with 76 until a public contact request sync settles it (its document proved on Platform: recorded as sent; its transition proved unable to write it: the pair freed), broadcasting the same signed bytes again meanwhile. Not a private request pending (71). Mapped by the blanket conversion and by `map_spend_result`. Swift and Kotlin typing is added by the FFI PR (#5812) and the Kotlin PR (#5813) | +| 68 | `ErrorPrivateContactRequestNeedsPrivateReply` | DashPay private contact requests | Proposed. The contact requests with that identity came or went privately (protocol version 15), so a `contactRequest` document to it, in reply or as a rotation, would publish the relationship: the public accept refuses a reply, and the public send refuses a request or a rotation. Nothing was sent; the request goes privately instead, and the in-kind accept picks the private reply itself. The shielded spend contract (`map_spend_result`) keeps the code, as the in-kind accept can raise it. Taken above 61–67, which open branches already hold. Returned by the public send and accept; the host sends with `platform_wallet_manager_send_private_contact_request`, or accepts with `platform_wallet_manager_accept_contact_request_replying_in_kind` (which picks the reply itself, so a host calling it does not route on 68) or `platform_wallet_manager_accept_private_contact_request`. Swift types it (`PlatformWalletError.privateContactRequestNeedsPrivateReply`, `ErrorHandlingTests` pin); Kotlin typing is added by the Kotlin PR (#5813) | +| 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number. Returned by `platform_wallet_manager_accept_contact_request_replying_in_kind`, exported in every build. Swift types it (`PlatformWalletError.shieldedBuildRequired`, `ErrorHandlingTests` pin); Kotlin typing is added by the Kotlin PR (#5813) | +| 70 | `ErrorProtocolVersionNotActive` | DashPay private contact requests | Proposed. The SDK refused a request without sending it (`dash_sdk::Error::ProtocolVersionNotActive`, not pinned) because the network is proven at a protocol version below the one that serves it: for example the private contact request sync on a network before protocol version 15. Expected on such a network, so a host may stay quiet about it; it lifts when the network upgrades. An SDK pinned below the required version has its own code, 75. Mapped by the blanket conversion for every operation that propagates the SDK error. A refusal that may lift sooner (`is_transient_protocol_version_refusal`: the network's version could not be confirmed) keeps the catch-all `ErrorUnknown`, as before. Previously both fell to `ErrorUnknown`. Swift types it (`PlatformWalletError.protocolVersionNotActive`, `ErrorHandlingTests` pin) and SwiftExampleApp keeps a refresh quiet on it; Kotlin typing is added by the Kotlin PR (#5813) | +| 71 | `ErrorPrivateContactRequestPending` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactRequestPending`: a private contact request to that identity is in flight (another private send or reply reserved it before sealing), or was paid for and a short read-back sync did not find the entry in the store yet, or a private payment the shielded store's journal keeps unresolved holds the pair. Nothing new was paid; a later private contact request sync settles it once the entry is read back, and the shielded sync once the payment provably never executes. Pending, not failed: the host must not submit it again. A private store read that did not finish before the request was decided is 74, not 71. The shielded spend contract (`map_spend_result`) keeps the code rather than flattening it to `ErrorWalletOperation`. Returned by the private send, the private accept and the in-kind accept, and by a public send or accept the pair holds; `platform_wallet_get_private_pair_held` reads one pair's hold as a send decides it. Swift types it (`PlatformWalletError.privateContactRequestPending`, `ErrorHandlingTests` pin; `ManagedPlatformWallet.privatePairHeld`), and SwiftExampleApp keeps the pair pending until that read says free; Kotlin typing is added by the Kotlin PR (#5813) | +| 72 | `ErrorPrivateContactPaymentsNotRestored` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactPaymentsNotRestored`: wallet readiness, not one contact's pending request (71). The wallet's unconfirmed private payments may hold pairs no reservation shows yet, which only a restoration from the shielded store's journal shows. In a build with the `shielded` feature: the wallet was published (created or loaded) while no shielded store was configured, its persister declaring the private scan state (bit 15), which holds a wallet removed and registered again from the same seed, in this process or a new one; it was loaded after binding a shielded account in an earlier process; or its last restoration failed, or waits for a busy store. In every build: the identity was loaded with its private scan state marking a private payment that may be unresolved, or was added to a wallet whose backend kept its record marked after an earlier wallet under the id was removed (`ClientStartState::retained_private_contact_scan_states`). Contact requests and acceptances, public and private, are refused with nothing read, signed or broadcast until they are restored: configuring the shielded store restores them with no keys, as binding the wallet's shielded account does, and a contact request first retries a restoration once without waiting on the store; a private sync does not, and a build without the `shielded` feature never does. A host whose persister declares the private scan state configures the shielded store when it activates the manager, before loading or creating wallets: until it does, and while a failed configure is not retried, 72 holds. `platform_wallet_get_private_contact_readiness` reads whether the payments are restored and whether the last restoration failed (`private_payments_restore_failed`; the wallet's `PrivateContactReadiness::private_payments_restore_failure` holds the reason). `platform_wallet_get_private_payments_restore_failure` gives that reason. Swift types it (`PlatformWalletError.privateContactPaymentsNotRestored`, `ErrorHandlingTests` pin) and binds both reads (`ManagedPlatformWallet.privateContactReadiness`, `privatePaymentsRestoreFailure`); SwiftExampleApp configures the shielded store when it activates a manager, before loading wallets; on each DashPay refresh while the store did not open or the readiness reads not restored, it configures the store again (on a store already open, the wallet's own retry of every wallet still held, a restoration that failed after the open included) and reads the readiness after that, refreshing again on a timer (every 3 s for a minute, then every 15 s) for as long as the view is shown and the payments stay unrestored, and when a shielded sync pass ends; it shows "setting up" or the failure's reason until the readiness reads restored. Kotlin typing is added by the Kotlin PR (#5813) | +| 73 | `ErrorPrivateContactRecoveryUnsupported` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactRecoveryUnsupported`: the persister does not declare `PRIVATE_CONTACT_REQUEST_SCAN_STATE` (bit 15) together with `ATOMIC_CHANGESETS` (bit 0, with the changeset begin and end callbacks wired), so the private send, the private accept and the in-kind accept's private reply are refused before anything is sealed or paid. The payment's recovery marker could not survive a restart, and a process reopening the wallet without the `shielded` feature, or before the shielded store is configured, could publish the pair while the payment may still execute. Not retryable as it is: a host that persists the private contact request scan state in changesets it commits whole declares both. The FFI constant is `PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE` (`1 << 15`). Swift types it (`PlatformWalletError.privateContactRecoveryUnsupported`, `ErrorHandlingTests` pin), SwiftExampleApp shows it as a storage configuration error, and the SwiftData handler declares bit 0 and bit 15 with the begin and end callbacks wired; Kotlin typing is added by the Kotlin PR (#5813) | +| 74 | `ErrorPrivateContactStoreNotRead` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactStoreNotRead`: DashPay's private contact request store was not read to its end for the identity, with the keys Platform proves it holds, before a contact request or acceptance, public or private, was decided (every one reads it from the identity's cursor first). Nothing was reserved, sealed, paid or broadcast; calling again continues the read from where it stopped. A node behind the store already seen, or keys that kept changing, stop it. It was reported as 71 before, which says not to submit again. Mapped by the blanket conversion and kept by the shielded spend contract (`map_spend_result`). Swift types it (`PlatformWalletError.privateContactStoreNotRead`, `ErrorHandlingTests` pin) and SwiftExampleApp offers a retry with no pending row; Kotlin typing is added by the Kotlin PR (#5813) | +| 75 | `ErrorSdkPinnedBelowProtocolVersion` | DashPay private contact requests | Proposed. The SDK refused a request without sending it because the SDK itself is pinned below the protocol version the request needs (`dash_sdk::Error::ProtocolVersionNotActive` with `pinned`), whatever the network runs: for example every contact request's private store read with the SDK pinned below protocol version 15 on a network at 15. A network upgrade does not lift it; only raising or removing the pin does. Before, it shared 70 with a network proven below the version, which lifts by itself. Mapped by the blanket conversion. Swift types it (`PlatformWalletError.sdkPinnedBelowProtocolVersion`, `ErrorHandlingTests` pin) and SwiftExampleApp shows a developer-facing message; Kotlin typing is added by the Kotlin PR (#5813) | +| 76 | `ErrorPublicContactRequestUnconfirmed` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PublicContactRequestUnconfirmed`: a public contact request to that identity was broadcast and may have been delivered, and no proof settled its outcome yet, so the wallet holds the pair and signs nothing new to it, public or private. The send or accept that broadcast it reported 20; every later one is refused with 76 until a public contact request sync settles it (its document proved on Platform: recorded as sent; its transition proved unable to write it: the pair freed), broadcasting the same signed bytes again meanwhile. Not a private request pending (71). Mapped by the blanket conversion and by `map_spend_result`. `platform_wallet_get_public_contact_request_unconfirmed` reads the hold per pair (`DashPayView::public_contact_request_unconfirmed`; 7 for a sender the wallet does not hold). Swift types it (`PlatformWalletError.publicContactRequestUnconfirmed`, `ErrorHandlingTests` pin) and wraps the read (`ManagedPlatformWallet.publicContactRequestUnconfirmed`); SwiftExampleApp shows the pair as being checked, with no request or accept offered, until the read says settled, and its refreshes run the DashPay sync that settles it; Kotlin typing is added by the Kotlin PR (#5813) | **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/contact_persistence.rs b/packages/rs-platform-wallet-ffi/src/contact_persistence.rs index 416e82870dc..2c23c31439d 100644 --- a/packages/rs-platform-wallet-ffi/src/contact_persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/contact_persistence.rs @@ -214,6 +214,51 @@ pub struct ContactIgnoredSenderFFI { pub is_ignored: bool, } +/// One identity's read position in DashPay's private contact request store +/// ([`ContactChangeSet::private_contact_requests_positions`]), for the +/// private contact request scan state callbacks on +/// [`PersistenceCallbacksExtension`](crate::persistence::PersistenceCallbacksExtension). +/// +/// Flat POD. The host stores one row per `(wallet_id, identity_id)`, +/// replacing the previous one, and hands it back unchanged at load: a lower +/// `position` than the stored one is a rewind, not a stale write. +/// +/// [`ContactChangeSet::private_contact_requests_positions`]: platform_wallet::changeset::ContactChangeSet::private_contact_requests_positions +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PrivateContactRequestsPositionFFI { + /// The wallet-owned identity reading the store. + pub identity_id: [u8; 32], + /// The store position the identity reads from next. + pub position: u64, + /// The fingerprint of the scanning keys `position` holds for. Opaque + /// to the host: store it and return it as it came. + pub key_fingerprint: [u8; 32], + /// Whether a private contact request the identity paid for may still + /// be unresolved. Store it and return it as it came: loaded set, it + /// holds the identity's public contact requests until its private + /// payments are restored from the shielded store. + pub private_payments_unresolved: bool, +} + +/// The shielded address `contact_id`'s tracked private request to +/// `owner_id` carries ([`ContactChangeSet::private_shielded_addresses`]). +/// +/// Flat POD. The host stores one row per `(wallet_id, owner_id, +/// contact_id)`, replacing the previous one. +/// +/// [`ContactChangeSet::private_shielded_addresses`]: platform_wallet::changeset::ContactChangeSet::private_shielded_addresses +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PrivateShieldedAddressFFI { + /// The wallet-owned identity the request is to. + pub owner_id: [u8; 32], + /// The contact who sent the request. + pub contact_id: [u8; 32], + /// The raw 43-byte Orchard payment address. + pub address: [u8; 43], +} + // Compile-time guards. Pin the expected layouts so any reshape on // the Rust side fails the cargo build before it can ship a dylib // the Swift side will mis-parse at runtime. @@ -268,6 +313,39 @@ const _: [u8; 1] = [0u8; std::mem::align_of::()]; const _: [u8; 65] = [0u8; std::mem::size_of::()]; const _: [u8; 1] = [0u8; std::mem::align_of::()]; +// Expected `PrivateContactRequestsPositionFFI` layout on 64-bit targets: +// +// 0..=31 identity_id [u8; 32] +// 32..=39 position u64 +// 40..=71 key_fingerprint [u8; 32] +// 72 private_payments_unresolved bool +// 73..=79 (tail padding to 8) +// +// Total size = 80, alignment = 8 (from the u64). +const _: [u8; 80] = [0u8; std::mem::size_of::()]; +const _: [u8; 8] = [0u8; std::mem::align_of::()]; +const _: () = assert!(std::mem::offset_of!(PrivateContactRequestsPositionFFI, position) == 32); +const _: () = + assert!(std::mem::offset_of!(PrivateContactRequestsPositionFFI, key_fingerprint) == 40); +const _: () = assert!( + std::mem::offset_of!( + PrivateContactRequestsPositionFFI, + private_payments_unresolved + ) == 72 +); + +// Expected `PrivateShieldedAddressFFI` layout on all targets: +// +// 0..=31 owner_id [u8; 32] +// 32..=63 contact_id [u8; 32] +// 64..=106 address [u8; 43] +// +// Total size = 107, alignment = 1 (all-byte fields). +const _: [u8; 107] = [0u8; std::mem::size_of::()]; +const _: [u8; 1] = [0u8; std::mem::align_of::()]; +const _: () = assert!(std::mem::offset_of!(PrivateShieldedAddressFFI, contact_id) == 32); +const _: () = assert!(std::mem::offset_of!(PrivateShieldedAddressFFI, address) == 64); + impl ContactIgnoredSenderFFI { /// Project an `(owner, sender)` ignore key onto its flat C mirror. /// `is_ignored` distinguishes an ignore (persist the row) from an diff --git a/packages/rs-platform-wallet-ffi/src/contact_request.rs b/packages/rs-platform-wallet-ffi/src/contact_request.rs index c61c43577ee..dbbb65e8938 100644 --- a/packages/rs-platform-wallet-ffi/src/contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/contact_request.rs @@ -254,8 +254,8 @@ pub struct PrivateContactReadinessFFI { pub unresolved_private_payment: bool, /// Whether the last restoration of the wallet's private payments failed, /// while `private_payments_restored` is false for it: then 72 holds until - /// a restoration succeeds, not only until one runs. The reason is in the - /// wallet's log; an export for it is left to the FFI PR. + /// a restoration succeeds, not only until one runs. The reason is + /// `platform_wallet_get_private_payments_restore_failure`. pub private_payments_restore_failed: bool, } diff --git a/packages/rs-platform-wallet-ffi/src/dashpay.rs b/packages/rs-platform-wallet-ffi/src/dashpay.rs index fc04b02c647..72c795781f2 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay.rs @@ -190,7 +190,7 @@ impl ContactRequestHandleArray { } /// Copy a slice of contact requests into the global handle storage. - fn from_requests(requests: Vec) -> Self { + pub(crate) fn from_requests(requests: Vec) -> Self { if requests.is_empty() { return Self::empty(); } @@ -325,22 +325,9 @@ pub unsafe extern "C" fn platform_wallet_send_contact_request_with_signer( } else { Some(unwrap_result_or_return!(CStr::from_ptr(account_label).to_str()).to_string()) }; - let proof: Option> = if auto_accept_proof.is_null() || auto_accept_proof_len == 0 { - None - } else { - // Defense-in-depth: bound the copy at the DIP-15 auto-accept proof - // ceiling (102 bytes) BEFORE allocating, so a malformed binding or a - // hostile (ptr, len) pair can't force an oversized allocation. The SDK - // re-validates the exact 38..=102 range after this. - if auto_accept_proof_len > 102 { - return crate::error::PlatformWalletFFIResult::err( - crate::error::PlatformWalletFFIResultCode::ErrorInvalidParameter, - format!( - "auto_accept_proof length {auto_accept_proof_len} exceeds the DIP-15 maximum of 102 bytes" - ), - ); - } - Some(std::slice::from_raw_parts(auto_accept_proof, auto_accept_proof_len).to_vec()) + let proof = match read_auto_accept_proof(auto_accept_proof, auto_accept_proof_len) { + Ok(proof) => proof, + Err(result) => return result, }; let signer_addr = signer_handle as usize; @@ -380,6 +367,31 @@ pub unsafe extern "C" fn platform_wallet_send_contact_request_with_signer( PlatformWalletFFIResult::ok() } +/// Copy an optional auto-accept proof from `(ptr, len)`; `(null, 0)` omits it. +/// +/// Defense-in-depth: the copy is bounded at the DIP-15 auto-accept proof +/// ceiling (102 bytes) BEFORE allocating, so a malformed binding or a hostile +/// (ptr, len) pair can't force an oversized allocation. The SDK re-validates +/// the exact 38..=102 range after this. +/// +/// # Safety +/// A non-null `ptr` must point to `len` readable bytes. +pub(crate) unsafe fn read_auto_accept_proof( + ptr: *const u8, + len: usize, +) -> Result>, PlatformWalletFFIResult> { + if ptr.is_null() || len == 0 { + return Ok(None); + } + if len > 102 { + return Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + format!("auto_accept_proof length {len} exceeds the DIP-15 maximum of 102 bytes"), + )); + } + Ok(Some(std::slice::from_raw_parts(ptr, len).to_vec())) +} + /// Send a contact request from a scanned DIP-15 auto-accept QR /// (`dash:?du=&dapk=`). Resolves the QR's username to the /// owner's identity, decodes the handed auto-accept key, signs the proof over @@ -1755,6 +1767,84 @@ pub unsafe extern "C" fn platform_wallet_drainable_contact_crypto_count( mod tests { use super::*; + mod private_store_scan_errors { + use super::*; + use platform_wallet::ContactCryptoProvider; + use rs_sdk_ffi::{ + dash_sdk_mnemonic_resolver_create, dash_sdk_mnemonic_resolver_destroy, + mnemonic_resolver_result, + }; + use std::ffi::c_void; + use std::str::FromStr; + + unsafe extern "C" fn no_mnemonic( + _ctx: *const c_void, + _wallet_id_bytes: *const u8, + _out_buf: *mut c_char, + _out_capacity: usize, + _out_len: *mut usize, + ) -> i32 { + mnemonic_resolver_result::NOT_FOUND + } + + unsafe extern "C" fn noop_destroy(_ctx: *mut c_void) {} + + /// A scan of the private store whose resolver holds no mnemonic for the + /// wallet reaches the host as the key-unavailable outcome (code 31), as + /// a signer's missing key does, so the host routes it to key repair + /// instead of reading a generic failure. + #[test] + fn should_report_a_missing_mnemonic_while_scanning_as_key_unavailable() { + let resolver = unsafe { + dash_sdk_mnemonic_resolver_create(std::ptr::null_mut(), no_mnemonic, noop_destroy) + }; + let provider = unsafe { + resolver_contact_crypto_provider(resolver, [0u8; 32], key_wallet::Network::Testnet) + }; + let keys = PrivateDocumentKeyPaths { + recipients: vec![( + Identifier::from([0xB0; 32]), + vec![( + 2, + key_wallet::bip32::DerivationPath::from_str("m/9'/1'/5'/0'/0'/1'/2'") + .expect("valid path"), + )], + )], + senders: Vec::new(), + }; + let page = PrivateDocumentEntries { + chunk_power: None, + entries: Vec::new(), + total_count: 0, + }; + let error = runtime() + .block_on(provider.scan_private_document_page( + &keys, + Identifier::from([0xD0; 32]), + "privateContactRequest", + 0, + &page, + )) + .expect_err("no mnemonic, no keys"); + let result = PlatformWalletFFIResult::from(error); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorSigningKeyUnavailable + ); + + // Another resolver failure keeps the code it had. + let other = PlatformWalletFFIResult::from(private_document_signer_error( + MnemonicResolverSignerError::BufferTooSmall, + )); + assert_ne!( + other.code, + PlatformWalletFFIResultCode::ErrorSigningKeyUnavailable + ); + + unsafe { dash_sdk_mnemonic_resolver_destroy(resolver) }; + } + } + /// A test wallet's mnemonic, counting how often the resolver reads it. unsafe extern "C" fn counting_resolve( ctx: *const std::ffi::c_void, diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index f6fa401a553..fbd1b5b2b37 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -663,15 +663,18 @@ pub enum PlatformWalletFFIResultCode { /// public accept refuse it, and nothing was sent: the request goes /// privately instead, and the in-kind accept picks the private reply /// itself. The shielded spend contract (`map_spend_result`) keeps the code, - /// as the in-kind accept can raise it. The exports that send and accept - /// contact requests are added by the FFI PR. 62 to 67 are claimed by open - /// branches, so this takes 68. + /// as the in-kind accept can raise it. Send it with + /// `platform_wallet_manager_send_private_contact_request`, or accept it + /// with `platform_wallet_manager_accept_contact_request_replying_in_kind` + /// or `platform_wallet_manager_accept_private_contact_request`. 62 to 67 + /// are claimed by open branches, so this takes 68. ErrorPrivateContactRequestNeedsPrivateReply = 68, /// The operation needs the shielded pool, and this library was built /// without the `shielded` feature: accepting a contact request that came - /// privately in kind, whose private reply is paid from the pool (the - /// export is added by the FFI PR; no export in this crate returns it yet). + /// privately with + /// `platform_wallet_manager_accept_contact_request_replying_in_kind` + /// (exported in every build), whose private reply is paid from the pool. /// Nothing was sent. Not retryable on this build; a build with shielded /// support accepts it. ErrorShieldedBuildRequired = 69, diff --git a/packages/rs-platform-wallet-ffi/src/lib.rs b/packages/rs-platform-wallet-ffi/src/lib.rs index 4734b414279..2e50b07c8e7 100644 --- a/packages/rs-platform-wallet-ffi/src/lib.rs +++ b/packages/rs-platform-wallet-ffi/src/lib.rs @@ -71,6 +71,7 @@ pub mod platform_address_sync; pub mod platform_address_types; pub mod platform_addresses; pub mod platform_wallet_info; +pub mod private_contact_request; pub mod provider_key_at_index; mod runtime; pub mod secp256k1_primitives; @@ -156,6 +157,7 @@ pub use platform_address_sync::*; pub use platform_address_types::*; pub use platform_addresses::*; pub use platform_wallet_info::*; +pub use private_contact_request::*; pub use provider_key_at_index::*; pub use secp256k1_primitives::*; #[cfg(feature = "shielded")] diff --git a/packages/rs-platform-wallet-ffi/src/manager.rs b/packages/rs-platform-wallet-ffi/src/manager.rs index 0723585c6e2..20748b92714 100644 --- a/packages/rs-platform-wallet-ffi/src/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/manager.rs @@ -8,13 +8,16 @@ use crate::event_handler::{ }; use crate::handle::*; use crate::persistence::{ - FFIPersister, FreeTrackedMasternodesFn, LoadAssetLockOperationIdFn, - LoadAssetLockShieldedRecipientFn, LoadIdentityBalanceBlockTimeFn, LoadTrackedMasternodesFn, - PersistAssetLockOperationIdFn, PersistAssetLockShieldedRecipientFn, PersistDpnsNameStatesFn, - PersistIdentityBalanceBlockTimeFn, PersistTrackedMasternodesFn, - PersistWalletChangesetChainLockHeightFn, PersistWalletChangesetSweepsFn, - PersistWalletChangesetUtxoVerdictsFn, PersistWalletDashPayBackfillFn, PersistenceCallbacks, - PersistenceCallbacksExtension, PersistenceCapabilitiesFFI, PersistenceExtensionCallbacks, + FFIPersister, FreePrivateContactScanStateFn, FreePrivateContactScanStateWalletsFn, + FreeTrackedMasternodesFn, LoadAssetLockOperationIdFn, LoadAssetLockShieldedRecipientFn, + LoadIdentityBalanceBlockTimeFn, LoadPrivateContactScanStateFn, + LoadPrivateContactScanStateWalletsFn, LoadTrackedMasternodesFn, PersistAssetLockOperationIdFn, + PersistAssetLockShieldedRecipientFn, PersistDpnsNameStatesFn, + PersistIdentityBalanceBlockTimeFn, PersistPrivateContactScanStateFn, + PersistTrackedMasternodesFn, PersistWalletChangesetChainLockHeightFn, + PersistWalletChangesetSweepsFn, PersistWalletChangesetUtxoVerdictsFn, + PersistWalletDashPayBackfillFn, PersistenceCallbacks, PersistenceCallbacksExtension, + PersistenceCapabilitiesFFI, PersistenceExtensionCallbacks, PLATFORM_WALLET_PERSISTENCE_CALLBACKS_EXTENSION_VERSION, }; use crate::runtime::runtime; @@ -23,6 +26,7 @@ use crate::{unwrap_option_or_return, unwrap_result_or_return}; use dash_sdk::Sdk; use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use platform_wallet::changeset::PlatformWalletPersistence; use platform_wallet::PlatformWalletManager; use platform_wallet::{PersistenceCapabilities, PERSISTENCE_CAPABILITIES_VERSION}; use std::os::raw::c_void; @@ -176,6 +180,32 @@ pub unsafe extern "C" fn platform_wallet_manager_create_with_extensions( ) } +/// The persistence capabilities a manager created from these callbacks +/// would attest, without creating one: the declaration intersected with what +/// the vtable and the extension structurally carry, as +/// [`platform_wallet_manager_create_with_extensions`] computes them. For a +/// host adapter's own tests, such as the JNI layer checking which bridge +/// overrides keep a capability. `persistence` is consumed: its `release_fn` +/// runs before this returns. +/// +/// # Safety +/// As for [`platform_wallet_manager_create_with_extensions`]: `extension` +/// must point to a readable [`PersistenceCallbacksExtension`] of at least +/// its declared `struct_size`, and `persistence`'s context must be valid +/// for its `release_fn`. +pub unsafe fn effective_persistence_capabilities( + persistence: PersistenceCallbacks, + declared: &PersistenceCapabilitiesFFI, + extension: *const PersistenceCallbacksExtension, +) -> PersistenceCapabilities { + FFIPersister::new_with_persistence_capabilities_and_extensions( + persistence, + persistence_capabilities_declaration(declared), + persistence_extension_callbacks(extension), + ) + .persistence_capabilities() +} + /// Read one negotiated slot out of a size/version-tagged extension struct /// — the single authority for the gate every reader below applies. A slot /// is read only when the host's declared `struct_size` proves it was @@ -299,6 +329,26 @@ unsafe fn persistence_extension_callbacks( on_load_asset_lock_shielded_recipient_fn, LoadAssetLockShieldedRecipientFn ), + persist_private_contact_scan_state: slot!( + on_persist_private_contact_scan_state_fn, + PersistPrivateContactScanStateFn + ), + load_private_contact_scan_state: slot!( + on_load_private_contact_scan_state_fn, + LoadPrivateContactScanStateFn + ), + load_private_contact_scan_state_free: slot!( + on_load_private_contact_scan_state_free_fn, + FreePrivateContactScanStateFn + ), + load_private_contact_scan_state_wallets: slot!( + on_load_private_contact_scan_state_wallets_fn, + LoadPrivateContactScanStateWalletsFn + ), + load_private_contact_scan_state_wallets_free: slot!( + on_load_private_contact_scan_state_wallets_free_fn, + FreePrivateContactScanStateWalletsFn + ), } } @@ -876,6 +926,9 @@ pub unsafe extern "C" fn platform_wallet_manager_remove_wallet( #[cfg(test)] mod tests { use super::*; + use crate::contact_persistence::{ + ContactRequestRemovalFFI, PrivateContactRequestsPositionFFI, PrivateShieldedAddressFFI, + }; unsafe extern "C" fn begin_changeset(_context: *mut c_void, _wallet_id: *const u8) -> i32 { 0 @@ -1381,6 +1434,137 @@ mod tests { assert!(parsed.load_identity_balance_block_time.is_none()); } + /// The effective capabilities are the declaration intersected with what + /// the callbacks carry, and the vtable's `release_fn` runs once. + #[test] + fn should_compute_the_effective_persistence_capabilities_without_a_manager() { + use std::sync::atomic::{AtomicUsize, Ordering}; + static RELEASES: AtomicUsize = AtomicUsize::new(0); + unsafe extern "C" fn release(_: *mut c_void) { + RELEASES.fetch_add(1, Ordering::SeqCst); + } + let declared = PersistenceCapabilitiesFFI { + version: PERSISTENCE_CAPABILITIES_VERSION, + reserved: 0, + bits: PersistenceCapabilities::ATOMIC_CHANGESETS + .union(PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE) + .bits(), + }; + let extension = PersistenceCallbacksExtension::default(); + let effective = unsafe { + effective_persistence_capabilities( + PersistenceCallbacks { + context: std::ptr::NonNull::::dangling().as_ptr().cast(), + release_fn: Some(release), + on_changeset_begin_fn: Some(begin_changeset), + on_changeset_end_fn: Some(end_changeset), + ..PersistenceCallbacks::default() + }, + &declared, + &extension, + ) + }; + assert!(effective.contains(PersistenceCapabilities::ATOMIC_CHANGESETS)); + assert!( + !effective.contains(PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE), + "declared without the callbacks it needs" + ); + assert_eq!(RELEASES.load(Ordering::SeqCst), 1); + } + + #[test] + fn should_size_gate_private_contact_scan_state_slots_independently() { + #[allow(clippy::too_many_arguments)] + unsafe extern "C" fn persist( + _: *mut c_void, + _: *const u8, + _: *const PrivateContactRequestsPositionFFI, + _: usize, + _: *const PrivateShieldedAddressFFI, + _: usize, + _: *const ContactRequestRemovalFFI, + _: usize, + _: *const [u8; 32], + _: usize, + ) -> i32 { + 0 + } + unsafe extern "C" fn load( + _: *mut c_void, + _: *const u8, + _: *mut *const PrivateContactRequestsPositionFFI, + _: *mut usize, + _: *mut *const PrivateShieldedAddressFFI, + _: *mut usize, + ) -> i32 { + 0 + } + unsafe extern "C" fn free( + _: *mut c_void, + _: *const PrivateContactRequestsPositionFFI, + _: usize, + _: *const PrivateShieldedAddressFFI, + _: usize, + ) { + } + unsafe extern "C" fn list(_: *mut c_void, _: *mut *const [u8; 32], _: *mut usize) -> i32 { + 0 + } + unsafe extern "C" fn free_list(_: *mut c_void, _: *const [u8; 32], _: usize) {} + let mut ext = PersistenceCallbacksExtension { + on_persist_private_contact_scan_state_fn: Some(persist), + on_load_private_contact_scan_state_fn: Some(load), + on_load_private_contact_scan_state_free_fn: Some(free), + on_load_private_contact_scan_state_wallets_fn: Some(list), + on_load_private_contact_scan_state_wallets_free_fn: Some(free_list), + ..Default::default() + }; + let parsed = unsafe { persistence_extension_callbacks(&ext) }; + assert!(parsed.persist_private_contact_scan_state.is_some()); + assert!(parsed.load_private_contact_scan_state.is_some()); + assert!(parsed.load_private_contact_scan_state_free.is_some()); + assert!(parsed.load_private_contact_scan_state_wallets.is_some()); + assert!(parsed + .load_private_contact_scan_state_wallets_free + .is_some()); + // An extension sized before the wallet list leaves both list slots + // unread. + ext.struct_size = std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_wallets_fn + ); + let parsed = unsafe { persistence_extension_callbacks(&ext) }; + assert!(parsed.load_private_contact_scan_state_free.is_some()); + assert!(parsed.load_private_contact_scan_state_wallets.is_none()); + assert!(parsed + .load_private_contact_scan_state_wallets_free + .is_none()); + ext.struct_size = std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_wallets_free_fn + ); + let parsed = unsafe { persistence_extension_callbacks(&ext) }; + assert!(parsed.load_private_contact_scan_state_wallets.is_some()); + assert!(parsed + .load_private_contact_scan_state_wallets_free + .is_none()); + ext.struct_size = std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_free_fn + ); + let parsed = unsafe { persistence_extension_callbacks(&ext) }; + assert!(parsed.load_private_contact_scan_state.is_some()); + assert!(parsed.load_private_contact_scan_state_free.is_none()); + ext.struct_size = std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_private_contact_scan_state_fn + ); + let parsed = unsafe { persistence_extension_callbacks(&ext) }; + assert!(parsed.persist_private_contact_scan_state.is_none()); + assert!(parsed.load_private_contact_scan_state.is_none()); + assert!(parsed.load_private_contact_scan_state_free.is_none()); + } + #[test] fn should_size_gate_asset_lock_operation_id_slots_independently() { unsafe extern "C" fn persist( diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index c1a86ac0a98..37bcecc9f82 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -32,9 +32,10 @@ use platform_wallet::changeset::provider_key_account::{ }; use platform_wallet::changeset::{ AccountAddressPoolEntry, AccountRegistrationEntry, ClientStartState, ClientWalletStartState, - ListedCoreTxid, PersistenceCapabilities, PersistenceError, PersistenceErrorKind, - PlatformWalletChangeSet, PlatformWalletPersistence, ProviderKeyAccountEntry, - ProviderKeyExtendedPubKey, PERSISTENCE_CAPABILITIES_VERSION, + ContactChangeSet, ListedCoreTxid, PersistenceCapabilities, PersistenceError, + PersistenceErrorKind, PlatformWalletChangeSet, PlatformWalletPersistence, + PrivateContactRequestsPosition, ProviderKeyAccountEntry, ProviderKeyExtendedPubKey, + PERSISTENCE_CAPABILITIES_VERSION, }; use platform_wallet::wallet::asset_lock::restored_record::held_output_details; use platform_wallet::wallet::core::stored_coin::{reconcile_with_parent, StoredParentState}; @@ -53,7 +54,8 @@ use crate::asset_lock_persistence::{ build_asset_lock_entries, outpoint_to_bytes, AssetLockEntryFFI, }; use crate::contact_persistence::{ - free_contact_requests_ffi, ContactIgnoredSenderFFI, ContactRequestFFI, ContactRequestRemovalFFI, + free_contact_requests_ffi, ContactIgnoredSenderFFI, ContactRequestFFI, + ContactRequestRemovalFFI, PrivateContactRequestsPositionFFI, PrivateShieldedAddressFFI, }; use crate::core_address_types::{AddressPoolTypeTagFFI, CoreAddressEntryFFI, KeyTypeTagFFI}; use crate::core_wallet_types::{ @@ -168,6 +170,34 @@ pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_OPERATION_IDS: u64 = /// 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; +/// The private contact request sync's scan state (each identity's read +/// position and its private contacts' shielded addresses) is persisted AND +/// restored across restarts. Requires the extension slots +/// `on_persist_private_contact_scan_state_fn` + +/// `on_load_private_contact_scan_state_fn` + +/// `on_load_private_contact_scan_state_free_fn` + +/// `on_load_private_contact_scan_state_wallets_fn` + +/// `on_load_private_contact_scan_state_wallets_free_fn`, the wallet-list +/// restore callbacks, `on_persist_contacts_fn` (a read position vouches for +/// the contact requests read before it), and the host declaring the bit. +/// +/// A host declaring it keeps a position record whose +/// `private_payments_unresolved` is set through the removal of its wallet +/// and any purge of that wallet's rows, until a record stored cleared for +/// the same wallet and owner replaces it, and lists that wallet's id from +/// `on_load_private_contact_scan_state_wallets_fn`. The marker stands for a +/// private payment that may still execute: the load hands such records +/// (those of a wallet it does not return, or of an identity it does not +/// restore) to the wallet as `ClientStartState::retained_private_contact_scan_states`, +/// and a wallet registered or loaded under the id holds the identity they +/// name. The +/// wallet keeps the state only together with +/// [`PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ATOMIC_CHANGESETS`] +/// (`PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART`), which +/// needs the declaration and the changeset begin and end callbacks: an +/// un-ignore stores the sender's removal and the read-position rewind it +/// brings in one changeset. +pub const PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE: u64 = 1 << 15; /// Version of [`PersistenceCallbacksExtension`]. The extension is deliberately /// separate from [`PersistenceCallbacks`]: existing hosts pass the latter by @@ -352,6 +382,80 @@ pub type LoadAssetLockShieldedRecipientFn = unsafe extern "C" fn( out_recipient_raw_43: *mut u8, ) -> i32; +/// Store a round's private contact request scan state for `wallet_id` +/// (see [`PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE`]), +/// inside the round's begin/end bracket, after the contacts callback: +/// +/// - `positions`: replace the identity's stored read position. +/// - `addresses`: replace the stored address for `(owner_id, contact_id)`. +/// - `removed_addresses`: delete the stored address for `(owner_id, +/// contact_id)` (`ContactRequestRemovalFFI::contact_id` names the contact). +/// - `cleared_identities`: 32-byte ids of identities the round removed from +/// the wallet. Delete each one's position and every address it owns, so +/// an identity added back later reads the store from its start. +/// +/// Every pointer is null when its count is 0 and valid only for the +/// duration of the call. A host without the slot never has the state +/// written, and each launch reads the store from its start. +pub type PersistPrivateContactScanStateFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, + removed_addresses: *const ContactRequestRemovalFFI, + removed_addresses_count: usize, + cleared_identities: *const [u8; 32], + cleared_identities_count: usize, +) -> i32; + +/// Return every stored private contact request read position and shielded +/// address for `wallet_id`. The host allocates both arrays and keeps them +/// valid until Rust hands them back through +/// [`FreePrivateContactScanStateFn`]; a null array with a zero count is an +/// empty one. An unreadable store must return an error, not empty arrays. +pub type LoadPrivateContactScanStateFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_positions: *mut *const PrivateContactRequestsPositionFFI, + out_positions_count: *mut usize, + out_addresses: *mut *const PrivateShieldedAddressFFI, + out_addresses_count: *mut usize, +) -> i32; + +/// Release the arrays a [`LoadPrivateContactScanStateFn`] returned. +pub type FreePrivateContactScanStateFn = unsafe extern "C" fn( + context: *mut c_void, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, +); + +/// Return the ids of every wallet the host keeps private contact request +/// scan state for, those of wallets it no longer holds included: a removed +/// wallet whose position records it kept marked (see +/// [`PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE`]). +/// Rust reads each id the wallet-list load does not return through +/// [`LoadPrivateContactScanStateFn`]. The host allocates the array and keeps +/// it valid until Rust hands it back through +/// [`FreePrivateContactScanStateWalletsFn`]; a null array with a zero count is +/// an empty one. An unreadable store must return an error, not an empty +/// array. +pub type LoadPrivateContactScanStateWalletsFn = unsafe extern "C" fn( + context: *mut c_void, + out_wallet_ids: *mut *const [u8; 32], + out_wallet_ids_count: *mut usize, +) -> i32; + +/// Release the array a [`LoadPrivateContactScanStateWalletsFn`] returned. +pub type FreePrivateContactScanStateWalletsFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_ids: *const [u8; 32], + wallet_ids_count: usize, +); + /// Size- and version-tagged additive persistence callbacks. /// /// `context` is the context in the accompanying [`PersistenceCallbacks`] @@ -541,6 +645,70 @@ pub struct PersistenceCallbacksExtension { out_recipient_raw_43: *mut u8, ) -> i32, >, + /// The private contact request scan state a round writes (see + /// [`PersistPrivateContactScanStateFn`]). Appended under the same + /// version for the same reason as the slots above. Wired together with + /// the load + free pair and the wallet-list pair below: + /// `PRIVATE_CONTACT_REQUEST_SCAN_STATE` is attested only when all five + /// are present (and declared). + #[allow(clippy::type_complexity)] + pub on_persist_private_contact_scan_state_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, + removed_addresses: *const ContactRequestRemovalFFI, + removed_addresses_count: usize, + cleared_identities: *const [u8; 32], + cleared_identities_count: usize, + ) -> i32, + >, + /// Return the stored scan state for a wallet (see + /// [`LoadPrivateContactScanStateFn`]). + pub on_load_private_contact_scan_state_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + out_positions: *mut *const PrivateContactRequestsPositionFFI, + out_positions_count: *mut usize, + out_addresses: *mut *const PrivateShieldedAddressFFI, + out_addresses_count: *mut usize, + ) -> i32, + >, + /// Release the arrays `on_load_private_contact_scan_state_fn` returned. + pub on_load_private_contact_scan_state_free_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, + ), + >, + /// The ids of every wallet the host keeps scan state for (see + /// [`LoadPrivateContactScanStateWalletsFn`]). Appended under the same + /// version; wired with the free slot below and the three slots above, + /// `PRIVATE_CONTACT_REQUEST_SCAN_STATE` is attested only when all five + /// are present (and declared). + pub on_load_private_contact_scan_state_wallets_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + out_wallet_ids: *mut *const [u8; 32], + out_wallet_ids_count: *mut usize, + ) -> i32, + >, + /// Release the array `on_load_private_contact_scan_state_wallets_fn` + /// returned. + pub on_load_private_contact_scan_state_wallets_free_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_ids: *const [u8; 32], + wallet_ids_count: usize, + ), + >, } impl Default for PersistenceCallbacksExtension { @@ -563,6 +731,11 @@ impl Default for PersistenceCallbacksExtension { on_load_asset_lock_operation_id_fn: None, on_persist_asset_lock_shielded_recipient_fn: None, on_load_asset_lock_shielded_recipient_fn: None, + on_persist_private_contact_scan_state_fn: None, + on_load_private_contact_scan_state_fn: None, + on_load_private_contact_scan_state_free_fn: None, + on_load_private_contact_scan_state_wallets_fn: None, + on_load_private_contact_scan_state_wallets_free_fn: None, } } } @@ -586,6 +759,11 @@ pub struct PersistenceExtensionCallbacks { pub load_asset_lock_operation_id: Option, pub persist_asset_lock_shielded_recipient: Option, pub load_asset_lock_shielded_recipient: Option, + pub persist_private_contact_scan_state: Option, + pub load_private_contact_scan_state: Option, + pub load_private_contact_scan_state_free: Option, + pub load_private_contact_scan_state_wallets: Option, + pub load_private_contact_scan_state_wallets_free: Option, } /// Return value by which a persistence callback reports a **retryable** @@ -1755,6 +1933,40 @@ impl FFIPersister { if self.callbacks.on_persist_token_balances_fn.is_some() { capabilities = capabilities.union(PersistenceCapabilities::UNSIGNED_TOKEN_STORAGE); } + // The scan state is restored per wallet during the wallet-list load, + // so that load is required alongside the extension slots. So is the + // contacts callback: a read position vouches for the contact + // requests read before it, and without that callback `store` skips + // them, so a restored position would skip entries whose requests + // were never kept. + if wallet_restore + && self.callbacks.on_persist_contacts_fn.is_some() + && self + .tracked_masternodes_callbacks + .persist_private_contact_scan_state + .is_some() + && self + .tracked_masternodes_callbacks + .load_private_contact_scan_state + .is_some() + && self + .tracked_masternodes_callbacks + .load_private_contact_scan_state_free + .is_some() + // A host that keeps marked records past their wallet's removal + // must also hand them back. + && self + .tracked_masternodes_callbacks + .load_private_contact_scan_state_wallets + .is_some() + && self + .tracked_masternodes_callbacks + .load_private_contact_scan_state_wallets_free + .is_some() + { + capabilities = + capabilities.union(PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE); + } // The dashpay-payments slot is what the sweep's Failed flip rides // (`dashpay_payments_overlay` on the store round). A host that // never wired it — Android deliberately keeps payment recording @@ -1814,6 +2026,53 @@ impl FFIPersister { } } +impl FFIPersister { + /// Hand the wallet the marked private contact request scan state records + /// no restored identity took: `retained` holds those of the wallets the + /// load returned, and the records of every other wallet the host keeps + /// scan state for are read here + /// (`ClientStartState::retained_private_contact_scan_states`). Read only + /// for a host whose capabilities meet the wallet's rule for keeping the + /// state; another host's records reach nothing. + fn load_retained_private_contact_scan_states( + &self, + out: &mut ClientStartState, + mut retained: BTreeMap>, + ) -> Result<(), PersistenceError> { + let callbacks = &self.tracked_masternodes_callbacks; + if let (Some(list), Some(list_free), Some(load), Some(free)) = ( + callbacks.load_private_contact_scan_state_wallets, + callbacks.load_private_contact_scan_state_wallets_free, + callbacks.load_private_contact_scan_state, + callbacks.load_private_contact_scan_state_free, + ) { + if self + .persistence_capabilities() + .contains(PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART) + { + let context = self.callbacks.context; + for wallet_id in load_private_contact_scan_state_wallets(list, list_free, context)? + { + if out.wallets.contains_key(&wallet_id) { + continue; + } + // A wallet the host no longer holds restores no + // identity: every marked record it kept is retained. + let mut none = IdentityManagerStartState::default(); + let unapplied = load_private_contact_scan_state( + load, free, context, &wallet_id, &mut none, + )?; + if !unapplied.is_empty() { + retained.insert(wallet_id, unapplied); + } + } + } + } + out.retained_private_contact_scan_states = retained; + Ok(()) + } +} + impl PlatformWalletPersistence for FFIPersister { /// A host attests `ATOMIC_CHANGESETS` for a round it commits or rolls back /// whole; nothing of a rolled-back round survives on this side either, so @@ -3047,6 +3306,28 @@ impl PlatformWalletPersistence for FFIPersister { } } + // The private contact request scan state, after the contacts it was + // read with. Identities the round removed take theirs with them. + if let Some(cb) = self + .tracked_masternodes_callbacks + .persist_private_contact_scan_state + { + let rows = PrivateContactScanStateRows::new( + changeset.contacts.as_ref(), + changeset.identities.as_ref().map(|id_cs| &id_cs.removed), + ); + if !rows.is_empty() { + let rc = unsafe { rows.persist(cb, self.callbacks.context, &wallet_id) }; + if rc != 0 { + eprintln!( + "Private contact request scan state persistence callback returned error code {}", + rc + ); + outcome.record(rc); + } + } + } + // Send sync state updates. if let Some(ref addr_cs) = changeset.platform_addresses { if let Some(cb) = self.callbacks.on_persist_sync_state_fn { @@ -3558,7 +3839,11 @@ impl PlatformWalletPersistence for FFIPersister { "wallet restore: missing row buffer", )); } + // The marked scan state records no restored identity takes, by wallet: + // a wallet the host no longer holds keeps them too. + let mut retained = BTreeMap::new(); if count == 0 { + self.load_retained_private_contact_scan_states(&mut out, retained)?; return Ok(out); } @@ -3596,6 +3881,32 @@ impl PlatformWalletPersistence for FFIPersister { &mut wallet_state.unused_asset_locks, )?; } + if let (Some(load), Some(free)) = ( + self.tracked_masternodes_callbacks + .load_private_contact_scan_state, + self.tracked_masternodes_callbacks + .load_private_contact_scan_state_free, + ) { + // Read only for a host whose capabilities meet the wallet's + // rule for keeping the state (`PRIVATE_CONTACT_SCAN_STATE_RESTART`: + // the state with atomic changesets); the manager drops any + // other host's copy at load. + if self + .persistence_capabilities() + .contains(PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART) + { + let unapplied = load_private_contact_scan_state( + load, + free, + self.callbacks.context, + &entry.wallet_id, + &mut wallet_state.identity_manager, + )?; + if !unapplied.is_empty() { + retained.insert(entry.wallet_id, unapplied); + } + } + } 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() { @@ -3630,6 +3941,7 @@ impl PlatformWalletPersistence for FFIPersister { .insert(entry.wallet_id, platform_address_state); } } + self.load_retained_private_contact_scan_states(&mut out, retained)?; // Restore shielded sub-wallet state if the host has wired // up the optional callbacks. Notes and per-subwallet sync @@ -6393,6 +6705,261 @@ fn load_asset_lock_shielded_recipients( Ok(()) } +/// One round's private contact request scan state in its FFI shape (see +/// [`PersistPrivateContactScanStateFn`]). +struct PrivateContactScanStateRows { + positions: Vec, + addresses: Vec, + removed_addresses: Vec, + cleared_identities: Vec<[u8; 32]>, +} + +impl PrivateContactScanStateRows { + fn new( + contacts: Option<&ContactChangeSet>, + removed_identities: Option<&BTreeSet>, + ) -> Self { + let mut rows = Self { + positions: Vec::new(), + addresses: Vec::new(), + removed_addresses: Vec::new(), + cleared_identities: removed_identities + .into_iter() + .flatten() + .map(|id| id.to_buffer()) + .collect(), + }; + if let Some(contacts) = contacts { + rows.positions = contacts + .private_contact_requests_positions + .iter() + .map( + |(identity_id, position)| PrivateContactRequestsPositionFFI { + identity_id: identity_id.to_buffer(), + position: position.position, + key_fingerprint: position.key_fingerprint, + private_payments_unresolved: position.private_payments_unresolved, + }, + ) + .collect(); + rows.addresses = contacts + .private_shielded_addresses + .iter() + .map( + |((owner_id, contact_id), address)| PrivateShieldedAddressFFI { + owner_id: owner_id.to_buffer(), + contact_id: contact_id.to_buffer(), + address: *address, + }, + ) + .collect(); + rows.removed_addresses = contacts + .removed_private_shielded_addresses + .iter() + .map(|(owner_id, contact_id)| ContactRequestRemovalFFI { + owner_id: owner_id.to_buffer(), + contact_id: contact_id.to_buffer(), + }) + .collect(); + } + rows + } + + fn is_empty(&self) -> bool { + self.positions.is_empty() + && self.addresses.is_empty() + && self.removed_addresses.is_empty() + && self.cleared_identities.is_empty() + } + + /// # Safety + /// `callback` must be a valid [`PersistPrivateContactScanStateFn`] for + /// `context`. + unsafe fn persist( + &self, + callback: PersistPrivateContactScanStateFn, + context: *mut c_void, + wallet_id: &WalletId, + ) -> i32 { + fn ptr(rows: &[T]) -> *const T { + if rows.is_empty() { + std::ptr::null() + } else { + rows.as_ptr() + } + } + callback( + context, + wallet_id.as_ptr(), + ptr(&self.positions), + self.positions.len(), + ptr(&self.addresses), + self.addresses.len(), + ptr(&self.removed_addresses), + self.removed_addresses.len(), + ptr(&self.cleared_identities), + self.cleared_identities.len(), + ) + } +} + +/// Restore a wallet's private contact request scan state onto the identities +/// its load restored. Rows for an identity the load did not restore are +/// passed over. An error from the host, or a missing buffer, fails the load. +fn load_private_contact_scan_state( + load: LoadPrivateContactScanStateFn, + free: FreePrivateContactScanStateFn, + context: *mut c_void, + wallet_id: &WalletId, + identity_manager: &mut IdentityManagerStartState, +) -> Result, PersistenceError> { + struct Guard { + free: FreePrivateContactScanStateFn, + context: *mut c_void, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, + } + impl Drop for Guard { + fn drop(&mut self) { + if self.positions.is_null() && self.addresses.is_null() { + return; + } + unsafe { + (self.free)( + self.context, + self.positions, + self.positions_count, + self.addresses, + self.addresses_count, + ) + }; + } + } + + let mut guard = Guard { + free, + context, + positions: std::ptr::null(), + positions_count: 0, + addresses: std::ptr::null(), + addresses_count: 0, + }; + let rc = unsafe { + load( + context, + wallet_id.as_ptr(), + &mut guard.positions, + &mut guard.positions_count, + &mut guard.addresses, + &mut guard.addresses_count, + ) + }; + if rc != 0 { + return Err(persist_callback_error( + rc, + format!("on_load_private_contact_scan_state_fn returned error code {rc}"), + )); + } + if (guard.positions.is_null() && guard.positions_count != 0) + || (guard.addresses.is_null() && guard.addresses_count != 0) + { + return Err(PersistenceError::backend( + "private contact request scan state: missing row buffer", + )); + } + let positions: &[PrivateContactRequestsPositionFFI] = if guard.positions_count == 0 { + &[] + } else { + unsafe { slice::from_raw_parts(guard.positions, guard.positions_count) } + }; + let addresses: &[PrivateShieldedAddressFFI] = if guard.addresses_count == 0 { + &[] + } else { + unsafe { slice::from_raw_parts(guard.addresses, guard.addresses_count) } + }; + + let mut identities: BTreeMap = identity_manager + .wallet_identities + .values_mut() + .flat_map(BTreeMap::values_mut) + .map(|managed| (managed.id(), managed)) + .collect(); + // A marked record of an identity not restored here still stands for a + // private payment that may execute: it is returned, so the wallet holds + // the identity when it is added. An unmarked one has nothing to hold. + let mut unapplied = BTreeMap::new(); + for row in positions { + let record = PrivateContactRequestsPosition { + position: row.position, + key_fingerprint: row.key_fingerprint, + private_payments_unresolved: row.private_payments_unresolved, + }; + match identities.get_mut(&Identifier::new(row.identity_id)) { + Some(managed) => managed.apply_private_contact_requests_position(record), + None if record.private_payments_unresolved => { + unapplied.insert(Identifier::new(row.identity_id), record); + } + None => {} + } + } + for row in addresses { + if let Some(managed) = identities.get_mut(&Identifier::new(row.owner_id)) { + managed.apply_private_shielded_address(Identifier::new(row.contact_id), row.address); + } + } + Ok(unapplied) +} + +/// The ids of every wallet the host keeps private contact request scan state +/// for ([`LoadPrivateContactScanStateWalletsFn`]), the host's array released +/// before this returns. +fn load_private_contact_scan_state_wallets( + load: LoadPrivateContactScanStateWalletsFn, + free: FreePrivateContactScanStateWalletsFn, + context: *mut c_void, +) -> Result, PersistenceError> { + struct Guard { + free: FreePrivateContactScanStateWalletsFn, + context: *mut c_void, + wallet_ids: *const [u8; 32], + count: usize, + } + impl Drop for Guard { + fn drop(&mut self) { + if !self.wallet_ids.is_null() { + unsafe { (self.free)(self.context, self.wallet_ids, self.count) }; + } + } + } + + let mut guard = Guard { + free, + context, + wallet_ids: std::ptr::null(), + count: 0, + }; + let rc = unsafe { load(context, &mut guard.wallet_ids, &mut guard.count) }; + if rc != 0 { + return Err(persist_callback_error( + rc, + format!("on_load_private_contact_scan_state_wallets_fn returned error code {rc}"), + )); + } + if guard.wallet_ids.is_null() && guard.count != 0 { + return Err(PersistenceError::backend( + "private contact request scan state wallets: missing row buffer", + )); + } + if guard.count == 0 { + return Ok(Vec::new()); + } + // SAFETY: the host keeps `count` contiguous ids valid until `guard` + // hands them back. + Ok(unsafe { slice::from_raw_parts(guard.wallet_ids, guard.count) }.to_vec()) +} + /// 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 @@ -7829,6 +8396,930 @@ mod tests { ); } + /// What a scan-state host received, by callback. + #[derive(Default)] + struct ScanStateHost { + positions: std::sync::Mutex>, + addresses: std::sync::Mutex>, + removed: std::sync::Mutex>, + cleared: std::sync::Mutex>, + /// What `load_scan_state` answers: 0 rows as stored, 1 an error, + /// 2 a count without a buffer. + load_mode: u8, + loads: std::sync::atomic::AtomicUsize, + frees: std::sync::atomic::AtomicUsize, + /// What `load_scan_state_wallets` lists. + wallet_ids: std::sync::Mutex>, + } + + unsafe extern "C" fn load_scan_state_wallets( + ctx: *mut c_void, + out_wallet_ids: *mut *const [u8; 32], + out_count: *mut usize, + ) -> i32 { + let host = &*(ctx as *const ScanStateHost); + let ids = host.wallet_ids.lock().unwrap().clone(); + *out_count = ids.len(); + *out_wallet_ids = if ids.is_empty() { + std::ptr::null() + } else { + Box::into_raw(ids.into_boxed_slice()).cast() + }; + 0 + } + + unsafe extern "C" fn free_scan_state_wallets( + _: *mut c_void, + wallet_ids: *const [u8; 32], + count: usize, + ) { + if !wallet_ids.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + wallet_ids.cast_mut(), + count, + ))); + } + } + + #[allow(clippy::too_many_arguments)] + unsafe extern "C" fn persist_scan_state( + ctx: *mut c_void, + wallet: *const u8, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, + removed: *const ContactRequestRemovalFFI, + removed_count: usize, + cleared: *const [u8; 32], + cleared_count: usize, + ) -> i32 { + unsafe fn rows<'a, T>(ptr: *const T, count: usize) -> &'a [T] { + if count == 0 { + assert!(ptr.is_null(), "an empty array crosses as null"); + &[] + } else { + std::slice::from_raw_parts(ptr, count) + } + } + assert_eq!(std::slice::from_raw_parts(wallet, 32), &[42; 32]); + let host = &*(ctx as *const ScanStateHost); + host.positions + .lock() + .unwrap() + .extend_from_slice(rows(positions, positions_count)); + host.addresses + .lock() + .unwrap() + .extend_from_slice(rows(addresses, addresses_count)); + host.removed.lock().unwrap().extend( + rows(removed, removed_count) + .iter() + .map(|row| (row.owner_id, row.contact_id)), + ); + host.cleared + .lock() + .unwrap() + .extend_from_slice(rows(cleared, cleared_count)); + 0 + } + + unsafe extern "C" fn load_scan_state( + ctx: *mut c_void, + wallet: *const u8, + out_positions: *mut *const PrivateContactRequestsPositionFFI, + out_positions_count: *mut usize, + out_addresses: *mut *const PrivateShieldedAddressFFI, + out_addresses_count: *mut usize, + ) -> i32 { + assert_eq!(std::slice::from_raw_parts(wallet, 32), &[42; 32]); + let host = &*(ctx as *const ScanStateHost); + host.loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + match host.load_mode { + 1 => return -1, + 2 => { + *out_positions = std::ptr::null(); + *out_positions_count = 1; + return 0; + } + _ => {} + } + let positions = host.positions.lock().unwrap().clone(); + let addresses = host.addresses.lock().unwrap().clone(); + *out_positions_count = positions.len(); + *out_positions = Box::into_raw(positions.into_boxed_slice()).cast(); + *out_addresses_count = addresses.len(); + *out_addresses = Box::into_raw(addresses.into_boxed_slice()).cast(); + 0 + } + + unsafe extern "C" fn free_scan_state( + ctx: *mut c_void, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + addresses: *const PrivateShieldedAddressFFI, + addresses_count: usize, + ) { + let host = &*(ctx as *const ScanStateHost); + host.frees.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if !positions.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + positions.cast_mut(), + positions_count, + ))); + } + if !addresses.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + addresses.cast_mut(), + addresses_count, + ))); + } + } + + unsafe extern "C" fn load_one_identity( + _: *mut c_void, + entries: *mut *const WalletRestoreEntryFFI, + count: *mut usize, + ) -> i32 { + let mut identity: IdentityRestoreEntryFFI = std::mem::zeroed(); + identity.identity_id = [7; 32]; + *entries = Box::into_raw(Box::new(WalletRestoreEntryFFI { + wallet_id: [42; 32], + identities: Box::into_raw(Box::new(identity)), + identities_count: 1, + ..Default::default() + })); + *count = 1; + 0 + } + + unsafe extern "C" fn free_one_identity( + _: *mut c_void, + entries: *const WalletRestoreEntryFFI, + _: usize, + ) { + let row = Box::from_raw(entries.cast_mut()); + drop(Box::from_raw(row.identities.cast_mut())); + } + + #[allow(clippy::too_many_arguments)] + unsafe extern "C" fn keep_scan_state_contacts( + _: *mut c_void, + _: *const u8, + _: *const ContactRequestFFI, + _: usize, + _: *const ContactRequestRemovalFFI, + _: usize, + _: *const ContactRequestRemovalFFI, + _: usize, + _: *const ContactIgnoredSenderFFI, + _: usize, + ) -> i32 { + 0 + } + + fn scan_state_persister( + host: &ScanStateHost, + declared: PersistenceCapabilities, + extensions: PersistenceExtensionCallbacks, + ) -> FFIPersister { + scan_state_persister_with_contacts(host, declared, extensions, true) + } + + fn scan_state_persister_with_contacts( + host: &ScanStateHost, + declared: PersistenceCapabilities, + extensions: PersistenceExtensionCallbacks, + persists_contacts: bool, + ) -> FFIPersister { + scan_state_persister_with(host, declared, extensions, persists_contacts, true) + } + + fn scan_state_persister_with( + host: &ScanStateHost, + declared: PersistenceCapabilities, + extensions: PersistenceExtensionCallbacks, + persists_contacts: bool, + brackets_rounds: bool, + ) -> FFIPersister { + FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (host as *const ScanStateHost).cast_mut().cast(), + on_changeset_begin_fn: brackets_rounds.then_some(noop_begin), + on_changeset_end_fn: brackets_rounds.then_some(noop_end), + on_load_wallet_list_fn: Some(load_one_identity), + on_load_wallet_list_free_fn: Some(free_one_identity), + on_persist_contacts_fn: persists_contacts.then_some(keep_scan_state_contacts), + ..Default::default() + }, + declared, + extensions, + ) + } + + fn scan_state_trio() -> PersistenceExtensionCallbacks { + PersistenceExtensionCallbacks { + persist_private_contact_scan_state: Some(persist_scan_state), + load_private_contact_scan_state: Some(load_scan_state), + load_private_contact_scan_state_free: Some(free_scan_state), + load_private_contact_scan_state_wallets: Some(load_scan_state_wallets), + load_private_contact_scan_state_wallets_free: Some(free_scan_state_wallets), + ..Default::default() + } + } + + /// A round carrying a read position, an address, an address removal and + /// a removed identity reaches the host as those four arrays. + #[test] + fn should_persist_the_private_contact_request_scan_state_of_a_round() { + use platform_wallet::changeset::IdentityChangeSet; + + let host = ScanStateHost::default(); + let persister = scan_state_persister( + &host, + PersistenceCapabilities::ATOMIC_CHANGESETS + .union(PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE), + scan_state_trio(), + ); + assert!(persister + .persistence_capabilities() + .contains(PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART)); + + let owner = Identifier::from([7; 32]); + let mut contacts = ContactChangeSet::default(); + contacts.private_contact_requests_positions.insert( + owner, + PrivateContactRequestsPosition { + position: 12, + key_fingerprint: [3; 32], + private_payments_unresolved: true, + }, + ); + contacts + .private_shielded_addresses + .insert((owner, Identifier::from([5; 32])), [9; 43]); + contacts + .removed_private_shielded_addresses + .insert((owner, Identifier::from([6; 32]))); + let identities = IdentityChangeSet { + removed: BTreeSet::from([Identifier::from([8; 32])]), + ..Default::default() + }; + persister + .store( + [42; 32], + PlatformWalletChangeSet { + contacts: Some(contacts), + identities: Some(identities), + ..Default::default() + }, + ) + .expect("store the scan state"); + + assert_eq!( + *host.positions.lock().unwrap(), + vec![PrivateContactRequestsPositionFFI { + identity_id: [7; 32], + position: 12, + key_fingerprint: [3; 32], + private_payments_unresolved: true, + }] + ); + assert_eq!( + *host.addresses.lock().unwrap(), + vec![PrivateShieldedAddressFFI { + owner_id: [7; 32], + contact_id: [5; 32], + address: [9; 43], + }] + ); + assert_eq!(*host.removed.lock().unwrap(), vec![([7; 32], [6; 32])]); + assert_eq!(*host.cleared.lock().unwrap(), vec![[8; 32]]); + } + + /// A contact request the host cannot stage fails the whole round: the + /// round carrying it and the read position read past it ends + /// unsuccessfully, so an atomic host keeps neither and the wallet's + /// ingest, which advances only once its round reached disk, leaves the + /// position where it was. + #[test] + fn should_fail_the_round_when_the_host_cannot_stage_a_contact_request() { + use platform_wallet::changeset::SentContactRequestKey; + use platform_wallet::wallet::identity::ContactRequest; + use std::sync::atomic::{AtomicBool, Ordering}; + + static ENDED_SUCCESSFULLY: AtomicBool = AtomicBool::new(true); + unsafe extern "C" fn record_end(_: *mut c_void, _: *const u8, success: bool) -> i32 { + ENDED_SUCCESSFULLY.store(success, Ordering::SeqCst); + 0 + } + #[allow(clippy::too_many_arguments)] + unsafe extern "C" fn refuse_contacts( + _: *mut c_void, + _: *const u8, + _: *const ContactRequestFFI, + _: usize, + _: *const ContactRequestRemovalFFI, + _: usize, + _: *const ContactRequestRemovalFFI, + _: usize, + _: *const ContactIgnoredSenderFFI, + _: usize, + ) -> i32 { + -1 + } + + let host = ScanStateHost::default(); + let persister = FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (&host as *const ScanStateHost).cast_mut().cast(), + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(record_end), + on_load_wallet_list_fn: Some(load_one_identity), + on_load_wallet_list_free_fn: Some(free_one_identity), + on_persist_contacts_fn: Some(refuse_contacts), + ..Default::default() + }, + PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART, + scan_state_trio(), + ); + let owner = Identifier::from([7; 32]); + let sender = Identifier::from([5; 32]); + let mut contacts = ContactChangeSet::default(); + contacts.sent_requests.insert( + SentContactRequestKey { + owner_id: owner, + recipient_id: sender, + }, + platform_wallet::changeset::ContactRequestEntry { + request: ContactRequest::new(owner, sender, 0, 0, 0, vec![0u8; 96], 0, 0), + }, + ); + contacts.private_contact_requests_positions.insert( + owner, + PrivateContactRequestsPosition { + position: 12, + key_fingerprint: [3; 32], + private_payments_unresolved: false, + }, + ); + assert!(persister + .store( + [42; 32], + PlatformWalletChangeSet { + contacts: Some(contacts), + ..Default::default() + }, + ) + .is_err()); + assert!( + !ENDED_SUCCESSFULLY.load(Ordering::SeqCst), + "the round ends unsuccessfully, so an atomic host keeps none of it" + ); + } + + /// A load hands the stored position and address back to the identity + /// they belong to, passes over rows of an identity it did not restore, + /// returns the host's arrays, and fails on a host error or a count + /// without a buffer. + #[test] + fn should_restore_the_private_contact_request_scan_state_onto_its_identity() { + use platform_wallet::wallet::identity::ContactRequest; + + let declared = PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART; + let host = ScanStateHost::default(); + host.positions.lock().unwrap().extend([ + PrivateContactRequestsPositionFFI { + identity_id: [7; 32], + position: 12, + key_fingerprint: [3; 32], + private_payments_unresolved: true, + }, + PrivateContactRequestsPositionFFI { + identity_id: [8; 32], + position: 99, + key_fingerprint: [4; 32], + private_payments_unresolved: false, + }, + ]); + host.addresses.lock().unwrap().extend([ + PrivateShieldedAddressFFI { + owner_id: [7; 32], + contact_id: [5; 32], + address: [9; 43], + }, + PrivateShieldedAddressFFI { + owner_id: [8; 32], + contact_id: [5; 32], + address: [1; 43], + }, + ]); + let mut restored = scan_state_persister(&host, declared, scan_state_trio()) + .load() + .expect("restore the scan state"); + assert_eq!(host.loads.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(host.frees.load(std::sync::atomic::Ordering::SeqCst), 1); + let wallet = restored.wallets.get_mut(&[42; 32]).expect("wallet"); + let identities = &mut wallet.identity_manager.wallet_identities; + assert_eq!(identities[&[42; 32]].len(), 1, "no identity is invented"); + let managed = identities + .get_mut(&[42; 32]) + .and_then(|identities| identities.get_mut(&0)) + .expect("identity"); + assert_eq!(managed.dashpay().private_contact_requests_position(), 12); + assert!( + managed.dashpay().private_payments_unresolved(), + "the unresolved-payment marker is restored with the position" + ); + // The address shows once the contact's request to us came privately + // (a private request carries no core height). + let owner = Identifier::from([7; 32]); + let contact = Identifier::from([5; 32]); + managed.apply_incoming_contact_request(ContactRequest::new( + contact, + owner, + 0, + 0, + 0, + vec![0; 96], + 0, + 0, + )); + assert_eq!( + managed + .dashpay() + .private_contact(&contact) + .and_then(|private| private.shielded_address), + Some([9; 43]) + ); + + for (mode, what) in [(1, "a host error"), (2, "a count without a buffer")] { + let failing = ScanStateHost { + load_mode: mode, + ..Default::default() + }; + assert!( + scan_state_persister(&failing, declared, scan_state_trio()) + .load() + .is_err(), + "{what} fails the load" + ); + } + } + + /// A host that does not declare the capability, wires only part of the + /// slots (the wallet list included), keeps no contact requests, or has no atomic changesets (no + /// begin and end callbacks, or no declaration) does not meet the + /// wallet's rule for keeping the scan state, has nothing read at load, + /// and still stores and loads everything else. A host without the slots + /// stores a round carrying scan state without error. + #[test] + fn should_leave_hosts_without_the_scan_state_capability_unchanged() { + let host = ScanStateHost::default(); + host.positions + .lock() + .unwrap() + .push(PrivateContactRequestsPositionFFI { + identity_id: [7; 32], + position: 12, + key_fingerprint: [3; 32], + private_payments_unresolved: true, + }); + let undeclared = + scan_state_persister(&host, PersistenceCapabilities::NONE, scan_state_trio()); + let half_wired = scan_state_persister( + &host, + PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE, + PersistenceExtensionCallbacks { + persist_private_contact_scan_state: Some(persist_scan_state), + load_private_contact_scan_state: Some(load_scan_state), + ..Default::default() + }, + ); + // A host that cannot list the wallets it keeps marked records for + // could not hand back a removed wallet's. + let without_wallet_list = scan_state_persister( + &host, + PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART, + PersistenceExtensionCallbacks { + load_private_contact_scan_state_wallets: None, + load_private_contact_scan_state_wallets_free: None, + ..scan_state_trio() + }, + ); + let unwired = scan_state_persister( + &host, + PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE, + PersistenceExtensionCallbacks::default(), + ); + // A read position vouches for the requests read before it, which a + // host without the contacts callback never keeps. + let without_contacts = scan_state_persister_with_contacts( + &host, + PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART, + scan_state_trio(), + false, + ); + // The state is kept only with atomic changesets: a host declaring + // both, with every slot, but no changeset begin and end callbacks, and + // a host bracketing its rounds but not declaring them atomic. + let without_brackets = scan_state_persister_with( + &host, + PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART, + scan_state_trio(), + true, + false, + ); + let not_atomic = scan_state_persister( + &host, + PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE, + scan_state_trio(), + ); + for persister in [ + &undeclared, + &half_wired, + &without_wallet_list, + &unwired, + &without_contacts, + &without_brackets, + ¬_atomic, + ] { + assert!(!persister + .persistence_capabilities() + .contains(PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART)); + let restored = persister.load().expect("the rest still restores"); + assert_eq!( + restored.wallets[&[42; 32]] + .identity_manager + .wallet_identities[&[42; 32]][&0] + .dashpay() + .private_contact_requests_position(), + 0 + ); + } + assert_eq!( + host.loads.load(std::sync::atomic::Ordering::SeqCst), + 0, + "nothing is read from a host that does not attest the state" + ); + + let mut contacts = ContactChangeSet::default(); + contacts.private_contact_requests_positions.insert( + Identifier::from([7; 32]), + PrivateContactRequestsPosition { + position: 1, + key_fingerprint: [0; 32], + private_payments_unresolved: false, + }, + ); + unwired + .store( + [42; 32], + PlatformWalletChangeSet { + contacts: Some(contacts), + ..Default::default() + }, + ) + .expect("a host without the slots stores the round"); + } + + /// A host keeping marked scan state records: the per-wallet rows of + /// several wallets, the wallets listed, the wallet-list load returning + /// some of them. + #[derive(Default)] + struct RetainedHost { + rows: std::sync::Mutex>>, + wallets_returned: Vec<([u8; 32], [u8; 32])>, + list_fails: bool, + list_frees: std::sync::atomic::AtomicUsize, + } + + unsafe extern "C" fn retained_load_rows( + ctx: *mut c_void, + wallet: *const u8, + out_positions: *mut *const PrivateContactRequestsPositionFFI, + out_positions_count: *mut usize, + out_addresses: *mut *const PrivateShieldedAddressFFI, + out_addresses_count: *mut usize, + ) -> i32 { + let host = &*(ctx as *const RetainedHost); + let wallet: [u8; 32] = std::slice::from_raw_parts(wallet, 32).try_into().unwrap(); + let rows = host + .rows + .lock() + .unwrap() + .get(&wallet) + .cloned() + .unwrap_or_default(); + *out_positions_count = rows.len(); + *out_positions = if rows.is_empty() { + std::ptr::null() + } else { + Box::into_raw(rows.into_boxed_slice()).cast() + }; + *out_addresses = std::ptr::null(); + *out_addresses_count = 0; + 0 + } + + /// Stores nothing: these tests load what the host kept. + #[allow(clippy::too_many_arguments)] + unsafe extern "C" fn retained_persist_rows( + _: *mut c_void, + _: *const u8, + _: *const PrivateContactRequestsPositionFFI, + _: usize, + _: *const PrivateShieldedAddressFFI, + _: usize, + _: *const ContactRequestRemovalFFI, + _: usize, + _: *const [u8; 32], + _: usize, + ) -> i32 { + 0 + } + + unsafe extern "C" fn retained_free_rows( + _: *mut c_void, + positions: *const PrivateContactRequestsPositionFFI, + positions_count: usize, + _: *const PrivateShieldedAddressFFI, + _: usize, + ) { + if !positions.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + positions.cast_mut(), + positions_count, + ))); + } + } + + unsafe extern "C" fn retained_list_wallets( + ctx: *mut c_void, + out_wallet_ids: *mut *const [u8; 32], + out_count: *mut usize, + ) -> i32 { + let host = &*(ctx as *const RetainedHost); + if host.list_fails { + return -1; + } + let ids: Vec<[u8; 32]> = host.rows.lock().unwrap().keys().copied().collect(); + *out_count = ids.len(); + *out_wallet_ids = if ids.is_empty() { + std::ptr::null() + } else { + Box::into_raw(ids.into_boxed_slice()).cast() + }; + 0 + } + + unsafe extern "C" fn retained_free_wallets( + ctx: *mut c_void, + wallet_ids: *const [u8; 32], + count: usize, + ) { + let host = &*(ctx as *const RetainedHost); + host.list_frees + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if !wallet_ids.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + wallet_ids.cast_mut(), + count, + ))); + } + } + + unsafe extern "C" fn retained_load_wallets( + ctx: *mut c_void, + entries: *mut *const WalletRestoreEntryFFI, + count: *mut usize, + ) -> i32 { + let host = &*(ctx as *const RetainedHost); + let rows: Vec = host + .wallets_returned + .iter() + .map(|(wallet_id, identity_id)| { + let mut identity: IdentityRestoreEntryFFI = std::mem::zeroed(); + identity.identity_id = *identity_id; + WalletRestoreEntryFFI { + wallet_id: *wallet_id, + identities: Box::into_raw(Box::new(identity)), + identities_count: 1, + ..Default::default() + } + }) + .collect(); + *count = rows.len(); + *entries = if rows.is_empty() { + std::ptr::null() + } else { + Box::into_raw(rows.into_boxed_slice()).cast() + }; + 0 + } + + unsafe extern "C" fn retained_free_loaded_wallets( + _: *mut c_void, + entries: *const WalletRestoreEntryFFI, + count: usize, + ) { + if entries.is_null() { + return; + } + let rows = Box::from_raw(std::ptr::slice_from_raw_parts_mut( + entries.cast_mut(), + count, + )); + for row in rows.iter() { + drop(Box::from_raw(row.identities.cast_mut())); + } + } + + fn retained_persister(host: &RetainedHost) -> FFIPersister { + FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (host as *const RetainedHost).cast_mut().cast(), + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(noop_end), + on_load_wallet_list_fn: Some(retained_load_wallets), + on_load_wallet_list_free_fn: Some(retained_free_loaded_wallets), + on_persist_contacts_fn: Some(keep_scan_state_contacts), + ..Default::default() + }, + PersistenceCapabilities::PRIVATE_CONTACT_SCAN_STATE_RESTART, + PersistenceExtensionCallbacks { + persist_private_contact_scan_state: Some(retained_persist_rows), + load_private_contact_scan_state: Some(retained_load_rows), + load_private_contact_scan_state_free: Some(retained_free_rows), + load_private_contact_scan_state_wallets: Some(retained_list_wallets), + load_private_contact_scan_state_wallets_free: Some(retained_free_wallets), + ..Default::default() + }, + ) + } + + fn position_row( + identity: u8, + position: u64, + marked: bool, + ) -> PrivateContactRequestsPositionFFI { + PrivateContactRequestsPositionFFI { + identity_id: [identity; 32], + position, + key_fingerprint: [identity; 32], + private_payments_unresolved: marked, + } + } + + /// A load hands the wallet every marked record no restored identity + /// takes, as `retained_private_contact_scan_states`: a removed wallet's, + /// which the host lists but no longer returns, and a returned wallet's + /// for an identity it did not restore. A record a restored identity takes + /// is applied to it instead, an unmarked record of an absent identity is + /// passed over, and a host holding no wallet still hands back what it + /// kept. A host that cannot list its wallets fails the load. + #[test] + fn should_hand_back_the_marked_records_no_restored_identity_takes() { + let host = RetainedHost { + wallets_returned: vec![([42; 32], [7; 32])], + ..Default::default() + }; + host.rows.lock().unwrap().extend([ + ( + [42; 32], + vec![ + position_row(7, 12, true), + position_row(9, 13, true), + position_row(10, 14, false), + ], + ), + ( + [43; 32], + vec![position_row(11, 15, true), position_row(12, 16, false)], + ), + ]); + let restored = retained_persister(&host).load().expect("the load"); + let managed = &restored.wallets[&[42; 32]] + .identity_manager + .wallet_identities[&[42; 32]][&0]; + assert!( + managed.dashpay().private_payments_unresolved(), + "a restored identity takes its own record" + ); + let retained = &restored.retained_private_contact_scan_states; + assert_eq!( + retained.keys().copied().collect::>(), + vec![[42; 32], [43; 32]] + ); + assert_eq!( + retained[&[42; 32]].keys().copied().collect::>(), + vec![Identifier::from([9; 32])], + "only the marked record of an identity the load did not restore" + ); + assert_eq!( + retained[&[43; 32]], + BTreeMap::from([( + Identifier::from([11; 32]), + PrivateContactRequestsPosition { + position: 15, + key_fingerprint: [11; 32], + private_payments_unresolved: true, + }, + )]), + "a removed wallet's marked record, as stored" + ); + assert_eq!( + host.list_frees.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the listed ids are handed back" + ); + + let no_wallets = RetainedHost::default(); + no_wallets + .rows + .lock() + .unwrap() + .insert([43; 32], vec![position_row(11, 15, true)]); + let restored = retained_persister(&no_wallets).load().expect("the load"); + assert!(restored.wallets.is_empty()); + assert!(restored.retained_private_contact_scan_states[&[43; 32]] + .contains_key(&Identifier::from([11; 32]))); + + let failing = RetainedHost { + list_fails: true, + ..Default::default() + }; + assert!( + retained_persister(&failing).load().is_err(), + "a host that cannot list its wallets fails the load" + ); + } + + /// A wallet registered under an id whose record the host kept marked + /// after the wallet was removed holds the identity the record names as it + /// is added, and no other. + #[test] + fn should_hold_an_identity_a_kept_marked_record_names_when_its_wallet_is_registered_again() { + use crate::runtime::runtime; + use crate::test_fixtures::{mock_manager, mock_manager_with}; + use dpp::identity::{Identity, IdentityV0}; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + let seed = [21u8; 64]; + let create = |manager: &platform_wallet::PlatformWalletManager| { + runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &seed, + WalletAccountCreationOptions::Default, + Some(0), + )) + .expect("a wallet") + }; + let wallet_id = create(&mock_manager()).wallet_id(); + + let marked = Identifier::from([31; 32]); + let other = Identifier::from([32; 32]); + let host = RetainedHost::default(); + host.rows + .lock() + .unwrap() + .insert(wallet_id, vec![position_row(31, 5, true)]); + let manager = mock_manager_with(retained_persister(&host)); + let wallet = create(&manager); + assert_eq!(wallet.wallet_id(), wallet_id); + + let held = |id: Identifier| { + runtime().block_on(async { + let mut wm = wallet.wallet_manager().write().await; + let identities = &mut wm + .get_wallet_info_mut(&wallet.wallet_id()) + .expect("the wallet's info") + .identity_manager; + identities + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: Default::default(), + balance: 0, + revision: 0, + }), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .expect("the identity"); + identities + .managed_identity(&id) + .expect("the identity") + .dashpay() + .private_payments_unrestored() + }) + }; + assert!(held(marked), "the identity the kept record names is held"); + assert!(!held(other), "an identity no kept record names is not"); + } + #[test] fn should_persist_balance_watermarks_only_for_the_owning_wallet() { use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry}; @@ -10583,6 +12074,56 @@ mod tests { PersistenceCallbacksExtension, on_load_asset_lock_shielded_recipient_fn ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_private_contact_scan_state_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_private_contact_scan_state_fn + ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_fn + ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_free_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_free_fn + ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_wallets_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_wallets_fn + ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_wallets_free_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_load_private_contact_scan_state_wallets_free_fn + ) + std::mem::size_of::>(), std::mem::size_of::() ); assert_eq!( @@ -10649,6 +12190,10 @@ mod tests { PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS, PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS.bits() ); + assert_eq!( + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE, + PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE.bits() + ); assert_eq!( PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ACCOUNT_ADDRESS_POOLS, PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_FUNDING_INDICES diff --git a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs new file mode 100644 index 00000000000..a9940b6ecc6 --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs @@ -0,0 +1,2031 @@ +//! FFI bindings for DashPay private contact requests (protocol version 15). +//! +//! A private contact request is an entry of DashPay's `privateContactRequest` +//! store, sealed to one of the recipient's DashPay keys and paid for from the +//! shielded pool, so nothing on chain names either side. The wallet keeps a +//! private request as it keeps a public one, an ordinary +//! [`ContactRequest`](platform_wallet::ContactRequest), so the existing +//! contact-request rows and accessors read it. +//! +//! - [`platform_wallet_sync_private_contact_requests`]: read the store for the +//! wallet's identities and ingest what it holds for them. The store is +//! opened with keys that stay in the resolver-backed signer; each request's +//! signature is checked against its sender's keys, which needs no secret. +//! - [`platform_wallet_manager_send_private_contact_request`] / +//! [`platform_wallet_manager_accept_private_contact_request`]: send, or +//! accept with a private reply, paying from an account's shielded notes. +//! The request is signed by the identity signer the public send and accept +//! take, and sealed in the resolver-backed signer. Built with the +//! `shielded` feature only. +//! - [`platform_wallet_manager_accept_contact_request_replying_in_kind`]: +//! the one accept a host calls. The wallet replies privately to a request +//! that came privately, and with a document otherwise. Exported in every +//! build; without the `shielded` feature a private reply fails with +//! `ErrorShieldedBuildRequired`. +//! - [`managed_identity_get_private_contact`]: what a contact's private +//! requests carry beyond the `ContactRequest`: whether they came or went +//! privately, and the contact's shielded address. +//! - [`platform_wallet_get_private_pair_held`]: whether a contact request +//! from one of the wallet's identities to a contact is held for a private +//! one, as a send decides it, so a host offers no second send or reply. +//! - [`platform_wallet_get_public_contact_request_unconfirmed`]: whether a +//! public contact request from one of the wallet's identities to a contact +//! was broadcast and its outcome is not proved yet, which holds the pair +//! as a private request pending does. +//! - [`platform_wallet_get_private_payments_restore_failure`]: why the last +//! restoration of the wallet's private payments failed, which +//! `platform_wallet_get_private_contact_readiness` reports only as a flag. +//! +//! The explicitly public send and accept refuse a contact whose requests came +//! or went privately with `ErrorPrivateContactRequestNeedsPrivateReply`. + +use std::ffi::CString; +use std::os::raw::c_char; +use std::sync::{Arc, Mutex}; + +use platform_wallet::{PlatformWalletError, PrivateContact}; +use rs_sdk_ffi::{MnemonicResolverHandle, SignerHandle, VTableSigner}; + +use crate::contact_request::CONTACT_REQUEST_STORAGE; +use crate::dashpay::{resolver_contact_crypto_provider, ContactRequestHandleArray}; +use crate::error::*; +use crate::established_contact::ESTABLISHED_CONTACT_STORAGE; +use crate::handle::*; +use crate::runtime::block_on_worker; +use crate::types::*; +use crate::{check_ptr, unwrap_option_or_return, unwrap_result_or_return}; + +#[cfg(not(feature = "shielded"))] +use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; + +#[cfg(feature = "shielded")] +use std::ffi::CStr; +#[cfg(feature = "shielded")] +use std::sync::atomic::{AtomicBool, Ordering}; + +#[cfg(feature = "shielded")] +use platform_wallet::wallet::shielded::{CachedOrchardProver, NetworkShieldedCoordinator}; +#[cfg(feature = "shielded")] +use platform_wallet::{AutoAcceptProofSource, PrivateReplyPayment}; +#[cfg(feature = "shielded")] +use zeroize::Zeroizing; + +#[cfg(feature = "shielded")] +use crate::dashpay::read_auto_accept_proof; +#[cfg(feature = "shielded")] +use crate::identity_keys_from_mnemonic::resolve_seed_from_resolver; +#[cfg(feature = "shielded")] +use crate::shielded_send::{ + catch_spend_panic, map_spend_result, poke_sync_on_unconfirmed, resolve_shielded_coordinator, + resolve_wallet_and_coordinator, +}; + +/// The bytes of an Orchard payment address: an 11-byte diversifier and a +/// 32-byte transmission key. +const SHIELDED_ADDRESS_LEN: usize = 43; + +/// A private sync, and the store read a send or accept makes first, check +/// that the resolver's seed is the wallet's before reading anything. A +/// mismatch takes the code every DashPay export gives it, and the seed +/// check reports (`ErrorInvalidParameter`); any other error is handed back. +fn seed_mismatch_result( + error: PlatformWalletError, +) -> Result { + match error { + error @ PlatformWalletError::SeedMismatch { .. } => Ok(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + error.to_string(), + )), + error => Err(error), + } +} + +/// What a pass over DashPay's private contact request store did +/// (`PrivateContactSyncReport`). Counts above `u32::MAX` saturate. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PrivateContactSyncReportFFI { + /// The store position the pass stopped at. + pub next_position: u64, + /// The store pages read. + pub pages_read: u32, + /// Entries that opened for one of the wallet's identities but were + /// refused. + pub rejected_count: u32, + /// Identities whose ingest did not reach disk: their entries are read + /// again by the next pass. + pub unpersisted_identity_count: u32, + /// Whether the pass read to the store's last entry. When false, call + /// again to read on. + pub complete: bool, +} + +// Expected `PrivateContactSyncReportFFI` layout on 64-bit targets: +// +// 0..=7 next_position u64 +// 8..=11 pages_read u32 +// 12..=15 rejected_count u32 +// 16..=19 unpersisted_identity_count u32 +// 20 complete bool +// 21..=23 (tail padding to 8) +// +// Total size = 24, alignment = 8 (from the u64). +const _: [u8; 24] = [0u8; std::mem::size_of::()]; +const _: [u8; 8] = [0u8; std::mem::align_of::()]; +const _: () = assert!(std::mem::offset_of!(PrivateContactSyncReportFFI, pages_read) == 8); +const _: () = assert!(std::mem::offset_of!(PrivateContactSyncReportFFI, rejected_count) == 12); +const _: () = + assert!(std::mem::offset_of!(PrivateContactSyncReportFFI, unpersisted_identity_count) == 16); +const _: () = assert!(std::mem::offset_of!(PrivateContactSyncReportFFI, complete) == 20); + +fn saturating_count(count: usize) -> u32 { + u32::try_from(count).unwrap_or(u32::MAX) +} + +/// Read DashPay's private contact request store for every identity of the +/// wallet, at most `max_pages` pages from the earliest of their cursors, and +/// ingest what it holds for them: requests to them, each sender checked, and +/// requests they sent, recovered from the store alone. Contacts establish and +/// their DashPay accounts are queued as the document sync does. +/// +/// `core_signer_handle` is the wallet-HD resolver signer: the store is opened +/// with keys derived inside it. Each request's signature is checked against +/// its sender's keys, which needs no secret. Each identity's cursor is stored +/// with the requests read before it and restored at load when the persister +/// attests `PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE` +/// with atomic changesets; otherwise the first pass of a process reads the +/// store from its start. +/// +/// Writes the requests the pass ingested, received and sent (including ones +/// already held), to `out_requests` (release with +/// `platform_wallet_contact_request_handle_array_free`, each handle with +/// `contact_request_destroy`) and the pass's counters to `out_report`. +/// +/// # Safety +/// - `core_signer_handle` must be a valid, non-destroyed +/// `*mut MnemonicResolverHandle`; the caller pins it for the call. +/// - `out_requests` and `out_report` must be valid, writable pointers. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_sync_private_contact_requests( + wallet_handle: Handle, + core_signer_handle: *mut MnemonicResolverHandle, + max_pages: u32, + out_requests: *mut ContactRequestHandleArray, + out_report: *mut PrivateContactSyncReportFFI, +) -> PlatformWalletFFIResult { + check_ptr!(core_signer_handle); + check_ptr!(out_requests); + check_ptr!(out_report); + // Publish FFI-safe sentinels before any fallible work, so every early + // return leaves both out-params well-defined. + unsafe { + *out_requests = ContactRequestHandleArray::empty(); + *out_report = PrivateContactSyncReportFFI::default(); + } + + // Look the wallet up under the registry guard, but run the pass outside + // it: a pass reads many pages, and a registry read guard held across + // that wait would stall `platform_wallet_destroy` and, through + // parking_lot's writer preference, every other registry reader. + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + ( + wallet.identity().clone(), + wallet.wallet_id(), + wallet.network(), + ) + }); + let (identity, wallet_id, network) = unwrap_option_or_return!(option); + // SAFETY: the caller pins the resolver handle for the duration of this + // call. + let provider = + unsafe { resolver_contact_crypto_provider(core_signer_handle, wallet_id, network) }; + let result = block_on_worker(async move { + identity + .dashpay() + .sync_private_contact_requests(&provider, max_pages as usize) + .await + }); + let report = match result { + Ok(report) => report, + Err(error) => return seed_mismatch_result(error).unwrap_or_else(|error| error.into()), + }; + unsafe { + *out_report = PrivateContactSyncReportFFI { + next_position: report.next_position, + pages_read: saturating_count(report.pages_read), + rejected_count: saturating_count(report.rejected.len()), + unpersisted_identity_count: saturating_count(report.unpersisted_identities.len()), + complete: report.complete, + }; + *out_requests = ContactRequestHandleArray::from_requests(report.requests); + } + PlatformWalletFFIResult::ok() +} + +/// What an identity's private contact requests with one contact carry beyond +/// the `ContactRequest` (`PrivateContact`). +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PrivateContactFFI { + /// The contact's request came privately: accepting it replies privately. + pub received_privately: bool, + /// This identity's request to the contact went privately. + pub sent_privately: bool, + /// Whether `shielded_address` holds the contact's address. + pub has_shielded_address: bool, + /// The Orchard address the contact asked to be paid at privately, when + /// `has_shielded_address`; zeros otherwise. + pub shielded_address: [u8; 43], +} + +// Expected `PrivateContactFFI` layout on all targets: +// +// 0 received_privately bool +// 1 sent_privately bool +// 2 has_shielded_address bool +// 3..=45 shielded_address [u8; 43] +// +// Total size = 46, alignment = 1 (all-byte fields). +const _: [u8; 46] = [0u8; std::mem::size_of::()]; +const _: [u8; 1] = [0u8; std::mem::align_of::()]; +const _: () = assert!(std::mem::offset_of!(PrivateContactFFI, sent_privately) == 1); +const _: () = assert!(std::mem::offset_of!(PrivateContactFFI, has_shielded_address) == 2); +const _: () = assert!(std::mem::offset_of!(PrivateContactFFI, shielded_address) == 3); + +impl PrivateContactFFI { + fn empty() -> Self { + Self { + received_privately: false, + sent_privately: false, + has_shielded_address: false, + shielded_address: [0; SHIELDED_ADDRESS_LEN], + } + } +} + +impl From for PrivateContactFFI { + fn from(contact: PrivateContact) -> Self { + Self { + received_privately: contact.received_privately, + sent_privately: contact.sent_privately, + has_shielded_address: contact.shielded_address.is_some(), + shielded_address: contact + .shielded_address + .unwrap_or([0; SHIELDED_ADDRESS_LEN]), + } + } +} + +/// Read what this identity's private contact requests with `contact_id` +/// carry into `out_contact`. Returns `NotFound` when neither tracked request +/// between them came or went privately. Whether one did is the stored +/// request's own, so it holds across restarts; the contact's shielded address +/// is kept in memory only and rebuilt by +/// `platform_wallet_sync_private_contact_requests`, so until a pass has run +/// it is absent. +/// +/// # Safety +/// - `contact_id` must point to 32 readable bytes. +/// - `out_contact` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn managed_identity_get_private_contact( + identity_handle: Handle, + contact_id: *const u8, + out_contact: *mut PrivateContactFFI, +) -> PlatformWalletFFIResult { + check_ptr!(out_contact); + unsafe { *out_contact = PrivateContactFFI::empty() }; + let contact_id = unwrap_result_or_return!(unsafe { read_identifier(contact_id) }); + + let option = MANAGED_IDENTITY_STORAGE.with_item(identity_handle, |identity| { + identity + .dashpay() + .private_contact(&contact_id) + .map(PrivateContactFFI::from) + }); + let inner = unwrap_option_or_return!(option); + let contact = unwrap_option_or_return!(inner); + unsafe { *out_contact = contact }; + PlatformWalletFFIResult::ok() +} + +/// Whether a contact request from `sender_id`, one of the wallet's +/// identities, to `recipient_id`, public or private, is held for a private +/// one, as a send decides it (`DashPayView::private_pair_held`), into +/// `out_held`: a private request to the recipient is being paid for, or was +/// paid for and is not yet read back from the store, or a private payment the +/// shielded store's journal keeps unresolved holds the pair, also after the +/// sender identity was removed and added again. While it is, a private send +/// or reply to the recipient is refused with `ErrorPrivateContactRequestPending` +/// (71) and a public one is held, so a host shows the pair as pending and +/// offers neither. The entry read back +/// (`platform_wallet_sync_private_contact_requests`) frees it, as does the +/// payment proven never to execute (its anchor pruned, which the shielded +/// sync judges); an endpoint's refusal of the payment does not. Not a pure +/// read: a journal record discharged since is applied first, briefly taking +/// the wallet's write lock, so a discharge reads as freed with no send or +/// sync in between. +/// +/// `out_held` is reset to false first. An unknown `wallet_handle` is +/// `NotFound`; a sender the wallet does not hold is `ErrorIdentityNotFound` +/// (7). +/// +/// # Safety +/// - `sender_id` and `recipient_id` must each point to 32 readable bytes. +/// - `out_held` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_get_private_pair_held( + wallet_handle: Handle, + sender_id: *const u8, + recipient_id: *const u8, + out_held: *mut bool, +) -> PlatformWalletFFIResult { + check_ptr!(out_held); + unsafe { *out_held = false }; + let sender_id = unwrap_result_or_return!(unsafe { read_identifier(sender_id) }); + let recipient_id = unwrap_result_or_return!(unsafe { read_identifier(recipient_id) }); + // Look the wallet up under the registry guard, but read outside it: the + // read may wait on the wallet's write lock, and a registry guard held + // across that wait would stall `platform_wallet_destroy`. + let option = + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()); + let identity = unwrap_option_or_return!(option); + let result = block_on_worker(async move { + identity + .dashpay() + .private_pair_held(&sender_id, &recipient_id) + .await + }); + let held = unwrap_result_or_return!(result); + unsafe { *out_held = held }; + PlatformWalletFFIResult::ok() +} + +/// Whether a public contact request from `sender_id`, one of the wallet's +/// identities, to `recipient_id` was broadcast and may have been delivered, +/// with no proof settling its outcome yet +/// (`DashPayView::public_contact_request_unconfirmed`), into +/// `out_unconfirmed`. The send or accept that broadcast it reported +/// `ErrorTransactionBroadcastUnconfirmed` (20); while it stands, every +/// contact request or acceptance to the recipient, public or private, is +/// refused with `ErrorPublicContactRequestUnconfirmed` (76), nothing signed, +/// so a host shows the pair as unconfirmed and offers neither. A public +/// contact request sync settles it: the request proved on Platform is +/// recorded as sent, and one proved unable to write it frees the pair. The +/// per-contact read beside `platform_wallet_get_private_pair_held`, so a +/// host tells a public request awaiting its outcome from a private one +/// pending. +/// +/// `out_unconfirmed` is reset to false first. An unknown `wallet_handle` is +/// `NotFound`; a sender the wallet does not hold is `ErrorIdentityNotFound` +/// (7). +/// +/// # Safety +/// - `sender_id` and `recipient_id` must each point to 32 readable bytes. +/// - `out_unconfirmed` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_get_public_contact_request_unconfirmed( + wallet_handle: Handle, + sender_id: *const u8, + recipient_id: *const u8, + out_unconfirmed: *mut bool, +) -> PlatformWalletFFIResult { + check_ptr!(out_unconfirmed); + unsafe { *out_unconfirmed = false }; + let sender_id = unwrap_result_or_return!(unsafe { read_identifier(sender_id) }); + let recipient_id = unwrap_result_or_return!(unsafe { read_identifier(recipient_id) }); + // Look the wallet up under the registry guard, but read outside it: the + // read waits on the wallet's lock, and a registry guard held across that + // wait would stall `platform_wallet_destroy`. + let option = + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()); + let identity = unwrap_option_or_return!(option); + let result = block_on_worker(async move { + identity + .dashpay() + .public_contact_request_unconfirmed(&sender_id, &recipient_id) + .await + }); + let unconfirmed = unwrap_result_or_return!(result); + unsafe { *out_unconfirmed = unconfirmed }; + PlatformWalletFFIResult::ok() +} + +/// Why the last restoration of the wallet's private payments failed, while +/// they are not restored for `identity_id` and none succeeded since +/// (`PrivateContactReadiness::private_payments_restore_failure`, which +/// `platform_wallet_get_private_contact_readiness` reports as +/// `private_payments_restore_failed`), into `out_reason`: a NUL-terminated +/// UTF-8 string the caller releases with `platform_wallet_string_free`, or +/// null when none failed (the payments are restored, or only not restored +/// yet). It reads the readiness, so a journal record discharged since is +/// applied first, as there. +/// +/// `out_reason` is reset to null first. An unknown `wallet_handle` is +/// `NotFound`; an identity the wallet does not hold is +/// `ErrorIdentityNotFound` (7). +/// +/// # Safety +/// - `identity_id` must point to 32 readable bytes. +/// - `out_reason` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_get_private_payments_restore_failure( + wallet_handle: Handle, + identity_id: *const u8, + out_reason: *mut *mut c_char, +) -> PlatformWalletFFIResult { + check_ptr!(out_reason); + unsafe { *out_reason = std::ptr::null_mut() }; + let identity_id = unwrap_result_or_return!(unsafe { read_identifier(identity_id) }); + // Look the wallet up under the registry guard, but read outside it: the + // read may wait on the wallet's write lock, and a registry guard held + // across that wait would stall `platform_wallet_destroy`. + let option = + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()); + let identity = unwrap_option_or_return!(option); + let result = block_on_worker(async move { + identity + .dashpay() + .private_contact_readiness(&identity_id) + .await + }); + let readiness = unwrap_result_or_return!(result); + if let Some(reason) = readiness.private_payments_restore_failure { + let reason = unwrap_result_or_return!(CString::new(reason)); + unsafe { *out_reason = reason.into_raw() }; + } + PlatformWalletFFIResult::ok() +} + +/// Copy an optional Orchard address: null means none. +/// +/// # Safety +/// A non-null `ptr` must point to [`SHIELDED_ADDRESS_LEN`] readable bytes. +unsafe fn read_shielded_address(ptr: *const u8) -> Option<[u8; SHIELDED_ADDRESS_LEN]> { + if ptr.is_null() { + return None; + } + let mut address = [0u8; SHIELDED_ADDRESS_LEN]; + std::ptr::copy_nonoverlapping(ptr, address.as_mut_ptr(), SHIELDED_ADDRESS_LEN); + Some(address) +} + +/// Send a DashPay private contact request from `sender_identity_id` to +/// `recipient_identity_id`, paying for it from `account`'s shielded notes, so +/// nothing on chain names either identity. The request carries our receiving +/// xpub for the contact, the masked account reference, `account_label`, +/// `auto_accept_proof`, and `shielded_address`, the Orchard address the +/// contact may pay us at privately. It is sealed to the recipient's DashPay +/// key inside the resolver-backed signer. +/// +/// `mnemonic_resolver_handle` supplies both the transient Orchard spend +/// authority and the DashPay keys. `signer_handle` is the identity signer +/// the public send takes (`platform_wallet_send_contact_request_with_signer`): +/// it signs the request with one of the sender's authentication keys, as it +/// signs a transition. Writes a handle into `CONTACT_REQUEST_STORAGE` to +/// `out_request_handle` (release with `contact_request_destroy`). +/// +/// Errors follow the shielded spend contract: `ErrorShieldedSpendUnconfirmed` +/// means the payment may already be on chain; do not send again. +/// +/// # Safety +/// - `wallet_id_bytes`, `sender_identity_id` and `recipient_identity_id` must +/// each point to 32 readable bytes. +/// - `mnemonic_resolver_handle` must be a valid, non-destroyed handle; the +/// caller retains ownership and pins it for the call. +/// - `account_label`, when non-null, must be a valid NUL-terminated UTF-8 C +/// string. +/// - `auto_accept_proof`, when non-null, must point to +/// `auto_accept_proof_len` readable bytes; `(null, 0)` omits it. +/// - `shielded_address`, when non-null, must point to 43 readable bytes; +/// null omits it. +/// - `signer_handle` must be a valid, non-destroyed `*mut SignerHandle` +/// produced by `dash_sdk_signer_create_with_ctx`; the caller retains +/// ownership and pins it for the call. +/// - `out_request_handle` must be a valid, writable pointer. +#[cfg(feature = "shielded")] +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_manager_send_private_contact_request( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + sender_identity_id: *const u8, + recipient_identity_id: *const u8, + account_label: *const c_char, + auto_accept_proof: *const u8, + auto_accept_proof_len: usize, + shielded_address: *const u8, + signer_handle: *mut SignerHandle, + out_request_handle: *mut Handle, +) -> PlatformWalletFFIResult { + // A panic in the proving task must not reach this `extern "C"` frame; the + // notes may already be spent when it strikes, so the ambiguous + // spend-unconfirmed contract applies (see `catch_spend_panic`). + catch_spend_panic("private contact request", || { + send_private_contact_request_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + sender_identity_id, + recipient_identity_id, + account_label, + auto_accept_proof, + auto_accept_proof_len, + shielded_address, + signer_handle, + out_request_handle, + ) + }) +} + +/// Body of [`platform_wallet_manager_send_private_contact_request`], as an +/// ordinary Rust function so a panic unwinds into [`catch_spend_panic`]. +/// +/// # Safety +/// Identical contract to the export that calls it. +#[cfg(feature = "shielded")] +#[allow(clippy::too_many_arguments)] +unsafe fn send_private_contact_request_inner( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + sender_identity_id: *const u8, + recipient_identity_id: *const u8, + account_label: *const c_char, + auto_accept_proof: *const u8, + auto_accept_proof_len: usize, + shielded_address: *const u8, + signer_handle: *mut SignerHandle, + out_request_handle: *mut Handle, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(signer_handle); + check_ptr!(out_request_handle); + unsafe { *out_request_handle = NULL_HANDLE }; + + let mut wallet_id = [0u8; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + let sender = unwrap_result_or_return!(read_identifier(sender_identity_id)); + let recipient = unwrap_result_or_return!(read_identifier(recipient_identity_id)); + let label = if account_label.is_null() { + None + } else { + Some(unwrap_result_or_return!(CStr::from_ptr(account_label).to_str()).to_string()) + }; + let proof = match read_auto_accept_proof(auto_accept_proof, auto_accept_proof_len) { + Ok(proof) => proof, + Err(result) => return result, + }; + let shielded_address = read_shielded_address(shielded_address); + + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(pair) => pair, + Err(result) => return result, + }; + let seed = match resolve_seed_from_resolver(mnemonic_resolver_handle, &wallet_id) { + Ok(seed) => seed, + Err(result) => return result, + }; + // SAFETY: the caller pins the resolver handle for the duration of this + // call. + let crypto = unsafe { + resolver_contact_crypto_provider(mnemonic_resolver_handle, wallet_id, wallet.network()) + }; + // The signer pointer crosses into the worker as a plain address and is + // re-materialized there, as the public send does. + let signer_addr = signer_handle as usize; + + // The proof runs on a worker thread: Halo 2 synthesis recurses past the + // iOS dispatch-thread stack. + let result = block_on_worker(async move { + // SAFETY: the caller pins the signer for the duration of this call, + // and `block_on_worker` blocks this frame until the task completes. + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let prover = CachedOrchardProver::new(); + let result = wallet + .send_private_contact_request( + &coordinator, + seed.as_ref(), + account, + &sender, + &recipient, + label, + AutoAcceptProofSource::from_option(proof), + shielded_address, + signer, + &crypto, + &prover, + ) + .await; + poke_sync_on_unconfirmed(&result, handle); + result + }); + match result { + Ok(request) => { + unsafe { *out_request_handle = CONTACT_REQUEST_STORAGE.insert(request) }; + PlatformWalletFFIResult::ok() + } + Err(error) => seed_mismatch_result(error) + .unwrap_or_else(|error| map_spend_result(Err(error), "private contact request")), + } +} + +/// Accept a DashPay contact request that came privately, replying privately +/// and paying for the reply from `account`'s shielded notes, as +/// [`platform_wallet_manager_send_private_contact_request`] pays. +/// `shielded_address` is the Orchard address the contact may pay us at +/// privately; null omits it. +/// +/// `request_handle` is a live `CONTACT_REQUEST_STORAGE` handle of the +/// incoming request. `signer_handle` is the identity signer the public accept +/// takes (`platform_wallet_accept_contact_request_with_signer`); it signs the +/// reply. Writes a handle into `ESTABLISHED_CONTACT_STORAGE` to +/// `out_established_handle` (release with `established_contact_destroy`). +/// +/// # Safety +/// - `wallet_id_bytes` must point to 32 readable bytes. +/// - `mnemonic_resolver_handle` must be a valid, non-destroyed handle; the +/// caller retains ownership and pins it for the call. +/// - `shielded_address`, when non-null, must point to 43 readable bytes. +/// - `signer_handle` must be a valid, non-destroyed `*mut SignerHandle` +/// produced by `dash_sdk_signer_create_with_ctx`; the caller retains +/// ownership and pins it for the call. +/// - `out_established_handle` must be a valid, writable pointer. +#[cfg(feature = "shielded")] +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_manager_accept_private_contact_request( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + request_handle: Handle, + shielded_address: *const u8, + signer_handle: *mut SignerHandle, + out_established_handle: *mut Handle, +) -> PlatformWalletFFIResult { + // Same panic contract as the send: the reply's notes may be spent. + catch_spend_panic("private contact request accept", || { + accept_private_contact_request_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + request_handle, + shielded_address, + signer_handle, + out_established_handle, + ) + }) +} + +/// Body of [`platform_wallet_manager_accept_private_contact_request`], as an +/// ordinary Rust function so a panic unwinds into [`catch_spend_panic`]. +/// +/// # Safety +/// Identical contract to the export that calls it. +#[cfg(feature = "shielded")] +#[allow(clippy::too_many_arguments)] +unsafe fn accept_private_contact_request_inner( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + request_handle: Handle, + shielded_address: *const u8, + signer_handle: *mut SignerHandle, + out_established_handle: *mut Handle, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(signer_handle); + check_ptr!(out_established_handle); + unsafe { *out_established_handle = NULL_HANDLE }; + + let mut wallet_id = [0u8; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + let request = CONTACT_REQUEST_STORAGE.with_item(request_handle, |request| request.clone()); + let request = unwrap_option_or_return!(request); + let shielded_address = read_shielded_address(shielded_address); + + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(pair) => pair, + Err(result) => return result, + }; + let seed = match resolve_seed_from_resolver(mnemonic_resolver_handle, &wallet_id) { + Ok(seed) => seed, + Err(result) => return result, + }; + // SAFETY: the caller pins the resolver handle for the duration of this + // call. + let crypto = unsafe { + resolver_contact_crypto_provider(mnemonic_resolver_handle, wallet_id, wallet.network()) + }; + let signer_addr = signer_handle as usize; + + let result = block_on_worker(async move { + // SAFETY: as in the send, the caller pins the signer for the call. + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let prover = CachedOrchardProver::new(); + let result = wallet + .accept_private_contact_request( + &coordinator, + seed.as_ref(), + account, + &request, + shielded_address, + signer, + &crypto, + &prover, + ) + .await; + poke_sync_on_unconfirmed(&result, handle); + result + }); + match result { + Ok(contact) => { + unsafe { *out_established_handle = ESTABLISHED_CONTACT_STORAGE.insert(contact) }; + PlatformWalletFFIResult::ok() + } + Err(error) => seed_mismatch_result(error) + .unwrap_or_else(|error| map_spend_result(Err(error), "private contact request accept")), + } +} + +/// Accept a DashPay contact request replying the way it came +/// (`accept_contact_request_replying_in_kind`): privately, paid from +/// `account`'s shielded notes, when it came privately and no reply exists +/// yet; otherwise with a `contactRequest` document signed by `signer_handle`, +/// or by adopting the reply already sent. Which reply a request takes is the +/// wallet's decision: this is the one accept a host calls. `shielded_address` +/// is the Orchard address the contact may pay us at privately; null omits it, +/// and a public reply ignores it. Exported in every build. +/// +/// Only a private reply needs shielded support and the spend authority: the +/// shielded coordinator is looked up, and the mnemonic read through +/// `mnemonic_resolver_handle`, when the wallet asks for the payment. A public +/// or adopted reply works on a manager without +/// `platform_wallet_manager_configure_shielded` and reads no mnemonic for the +/// payment (the DashPay keys still come from the resolver). In a build +/// without the `shielded` feature a request that needs a private reply fails +/// with `ErrorShieldedBuildRequired`, and every other accept works as in a +/// shielded build. +/// +/// Errors: a public or adopted reply fails with the codes the public accept +/// returns. Once a private reply's payment is asked for, errors follow the +/// shielded spend contract: `ErrorShieldedSpendUnconfirmed` means the reply +/// may already be on chain; do not accept again. A failed payment lookup +/// returns the code the lookup reported. +/// +/// # Safety +/// - `wallet_id_bytes` must point to 32 readable bytes. +/// - `mnemonic_resolver_handle` must be a valid, non-destroyed handle; the +/// caller retains ownership and pins it for the call. +/// - `shielded_address`, when non-null, must point to 43 readable bytes. +/// - `signer_handle` must be a valid, non-destroyed `*mut SignerHandle` +/// produced by `dash_sdk_signer_create_with_ctx`; the caller retains +/// ownership and pins it for the call. +/// - `out_established_handle` must be a valid, writable pointer. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_manager_accept_contact_request_replying_in_kind( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + request_handle: Handle, + shielded_address: *const u8, + signer_handle: *mut SignerHandle, + out_established_handle: *mut Handle, +) -> PlatformWalletFFIResult { + let accept = || { + accept_contact_request_replying_in_kind_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + request_handle, + shielded_address, + signer_handle, + out_established_handle, + ) + }; + // Same panic contract as the private accept: a private reply's notes may + // be spent when it strikes. A build without shielded support spends none. + #[cfg(feature = "shielded")] + let result = catch_spend_panic("contact request accept", accept); + #[cfg(not(feature = "shielded"))] + let result = accept(); + result +} + +/// Why a private reply could not be paid for, as the FFI reports it: the +/// export returns this code and message rather than the wallet error the +/// payment hands back to the wallet. Kept as owned parts, since a result +/// cannot cross threads. +type PaymentFailure = (PlatformWalletFFIResultCode, String); + +/// The parts of a failed FFI `result`; its message is freed with it. +#[cfg(feature = "shielded")] +fn payment_failure(result: PlatformWalletFFIResult) -> PaymentFailure { + let message = if result.message.is_null() { + String::new() + } else { + // SAFETY: a non-null message is a NUL-terminated string the FFI made. + unsafe { CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned() + }; + (result.code, message) +} + +/// Record `failure` for the export to return, and the wallet error the +/// payment hands back to the wallet in its place. +fn record_payment_failure( + slot: &Mutex>, + failure: PaymentFailure, +) -> PlatformWalletError { + let error = PlatformWalletError::InvalidParameter(failure.1.clone()); + if let Ok(mut recorded) = slot.lock() { + *recorded = Some(failure); + } + error +} + +/// The wallet of `wallet_id` under the manager `handle`, without the +/// shielded coordinator, which only a private reply needs. Wait-free (the +/// manager's wallet map is read without a lock or the runtime), with the +/// errors `resolve_wallet_and_coordinator` reports. +fn resolve_manager_wallet( + handle: Handle, + wallet_id: &[u8; 32], +) -> Result, PlatformWalletFFIResult> { + match PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |manager| manager.get_wallet_blocking(wallet_id)) + { + None => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidHandle, + format!("invalid manager handle: {handle}"), + )), + Some(None) => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + format!("wallet not found: {}", hex::encode(wallet_id)), + )), + Some(Some(wallet)) => Ok(wallet), + } +} + +/// What a private reply is paid with, looked up only when the wallet asks: +/// the shielded coordinator, then the seed read through the resolver at +/// `resolver_addr`. Runs on a blocking thread (the coordinator lookup blocks +/// on the runtime, and the resolver calls into the host). +/// +/// # Safety +/// `resolver_addr` must be the address of a valid `MnemonicResolverHandle` +/// that the export's caller pins for the call. +#[cfg(feature = "shielded")] +unsafe fn private_reply_payment_parts( + handle: Handle, + wallet_id: [u8; 32], + resolver_addr: usize, +) -> Result<(Arc, Zeroizing<[u8; 64]>), PaymentFailure> { + let coordinator = resolve_shielded_coordinator(handle).map_err(payment_failure)?; + let seed = resolve_seed_from_resolver(resolver_addr as *mut MnemonicResolverHandle, &wallet_id) + .map_err(payment_failure)?; + Ok((coordinator, seed)) +} + +/// Body of [`platform_wallet_manager_accept_contact_request_replying_in_kind`], +/// as an ordinary Rust function so a panic unwinds into `catch_spend_panic` +/// in a shielded build. +/// +/// # Safety +/// Identical contract to the export that calls it. +#[allow(clippy::too_many_arguments)] +unsafe fn accept_contact_request_replying_in_kind_inner( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + request_handle: Handle, + shielded_address: *const u8, + signer_handle: *mut SignerHandle, + out_established_handle: *mut Handle, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(signer_handle); + check_ptr!(out_established_handle); + unsafe { *out_established_handle = NULL_HANDLE }; + + let mut wallet_id = [0u8; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + let request = CONTACT_REQUEST_STORAGE.with_item(request_handle, |request| request.clone()); + let request = unwrap_option_or_return!(request); + let shielded_address = read_shielded_address(shielded_address); + + let wallet = match resolve_manager_wallet(handle, &wallet_id) { + Ok(wallet) => wallet, + Err(result) => return result, + }; + // SAFETY: the caller pins the resolver handle for the duration of this + // call. + let crypto = unsafe { + resolver_contact_crypto_provider(mnemonic_resolver_handle, wallet_id, wallet.network()) + }; + let signer_addr = signer_handle as usize; + // Why paying for a private reply failed, when it did: the export returns + // that, not the wallet error standing in for it. + let payment_failure_slot: Arc>> = Arc::new(Mutex::new(None)); + let failure_slot = Arc::clone(&payment_failure_slot); + + #[cfg(feature = "shielded")] + let payment_asked = Arc::new(AtomicBool::new(false)); + #[cfg(feature = "shielded")] + let result = { + let asked = Arc::clone(&payment_asked); + let resolver_addr = mnemonic_resolver_handle as usize; + block_on_worker(async move { + // SAFETY: as in the private accept, the caller pins the signer for + // the call. + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let prover = CachedOrchardProver::new(); + let result = wallet + .accept_contact_request_replying_in_kind( + &request, + shielded_address, + signer, + &crypto, + || async { + asked.store(true, Ordering::SeqCst); + let parts = tokio::task::spawn_blocking(move || { + // SAFETY: the caller pins the resolver for the call, + // and this export blocks until the task completes. + unsafe { private_reply_payment_parts(handle, wallet_id, resolver_addr) } + }) + .await + .unwrap_or_else(|_| { + Err(( + PlatformWalletFFIResultCode::ErrorUnknown, + "the private reply's payment lookup panicked".to_string(), + )) + }); + match parts { + Ok((coordinator, seed)) => Ok(PrivateReplyPayment { + coordinator, + seed, + account, + prover: &prover, + }), + Err(failure) => Err(record_payment_failure(&failure_slot, failure)), + } + }, + ) + .await; + poke_sync_on_unconfirmed(&result, handle); + result + }) + }; + // Without shielded support a private reply cannot be paid for; every + // other reply is the same as in a shielded build. + #[cfg(not(feature = "shielded"))] + let result = { + let _ = account; + let identity = wallet.identity().clone(); + block_on_worker(async move { + // SAFETY: the caller pins the signer for the call. + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + identity + .dashpay() + .accept_contact_request_replying_in_kind( + &request, + shielded_address, + signer, + &crypto, + // Refused before any payment could reach the network, + // so the payment is never marked as started. + |_entry, _started| async move { + Err::(record_payment_failure( + &failure_slot, + ( + PlatformWalletFFIResultCode::ErrorShieldedBuildRequired, + "this contact request needs a private reply, which is paid \ + from the shielded pool; this build has no shielded support" + .to_string(), + ), + )) + }, + ) + .await + }) + }; + + match result { + Ok(contact) => { + unsafe { *out_established_handle = ESTABLISHED_CONTACT_STORAGE.insert(contact) }; + PlatformWalletFFIResult::ok() + } + Err(error) => { + if let Some((code, message)) = payment_failure_slot + .lock() + .ok() + .and_then(|mut slot| slot.take()) + { + return PlatformWalletFFIResult::err(code, message); + } + let error = match seed_mismatch_result(error) { + Ok(result) => return result, + Err(error) => error, + }; + #[cfg(feature = "shielded")] + if payment_asked.load(Ordering::SeqCst) { + return map_spend_result(Err(error), "contact request accept"); + } + // No payment was asked for, so nothing was spent: report the + // reply's failure as the public accept does. + PlatformWalletFFIResult::from(error) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A wrong seed refused by the private sync, or by the store read a send + /// or accept makes first, takes the code every DashPay export gives it; + /// any other error is left to the export's own mapping. + #[test] + fn should_report_a_seed_mismatch_from_the_private_store_by_its_dashpay_code() { + let result = seed_mismatch_result(PlatformWalletError::SeedMismatch { + wallet_id: "ab".to_string(), + }) + .expect("a seed mismatch is mapped here"); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + assert!(matches!( + seed_mismatch_result(PlatformWalletError::PrivateContactPaymentsNotRestored), + Err(PlatformWalletError::PrivateContactPaymentsNotRestored) + )); + } + + #[test] + fn should_clear_both_sync_outputs_on_an_unknown_wallet() { + let mut requests = ContactRequestHandleArray { + handles: std::ptr::NonNull::dangling().as_ptr(), + count: 3, + }; + let mut report = PrivateContactSyncReportFFI { + next_position: 9, + pages_read: 9, + rejected_count: 9, + unpersisted_identity_count: 9, + complete: true, + }; + // A resolver is never called for an unknown wallet; any non-null + // pointer passes the null check. + let resolver = std::ptr::NonNull::::dangling().as_ptr(); + let result = unsafe { + platform_wallet_sync_private_contact_requests( + 0xDEAD_BEEF, + resolver, + 1, + &mut requests, + &mut report, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::NotFound); + assert!(requests.handles.is_null()); + assert_eq!(requests.count, 0); + assert_eq!(report, PrivateContactSyncReportFFI::default()); + } + + #[test] + fn should_reject_a_null_resolver_on_sync() { + let mut requests = ContactRequestHandleArray::empty(); + let mut report = PrivateContactSyncReportFFI::default(); + let result = unsafe { + platform_wallet_sync_private_contact_requests( + 0, + std::ptr::null_mut(), + 1, + &mut requests, + &mut report, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + + /// The request is signed by the identity signer, so the private send + /// refuses to run without one, before it touches the wallet. + #[cfg(feature = "shielded")] + #[test] + fn should_reject_a_null_identity_signer_on_the_private_send() { + let wallet_id = [1u8; 32]; + let sender = [2u8; 32]; + let recipient = [3u8; 32]; + let resolver = std::ptr::NonNull::::dangling().as_ptr(); + let mut out = 0xDEAD_BEEF; + let result = unsafe { + platform_wallet_manager_send_private_contact_request( + 0xDEAD_BEEF, + wallet_id.as_ptr(), + resolver, + 0, + sender.as_ptr(), + recipient.as_ptr(), + std::ptr::null(), + std::ptr::null(), + 0, + std::ptr::null(), + std::ptr::null_mut(), + &mut out, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + + /// As the private send: the reply is signed by the identity signer. + #[cfg(feature = "shielded")] + #[test] + fn should_reject_a_null_identity_signer_on_the_private_accept() { + let wallet_id = [1u8; 32]; + let resolver = std::ptr::NonNull::::dangling().as_ptr(); + let mut out = 0xDEAD_BEEF; + let result = unsafe { + platform_wallet_manager_accept_private_contact_request( + 0xDEAD_BEEF, + wallet_id.as_ptr(), + resolver, + 0, + 0xDEAD_BEEF, + std::ptr::null(), + std::ptr::null_mut(), + &mut out, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + + /// As the private accept: whichever reply the wallet picks is signed by + /// the identity signer. + #[test] + fn should_reject_a_null_identity_signer_on_the_accept_replying_in_kind() { + let wallet_id = [1u8; 32]; + let resolver = std::ptr::NonNull::::dangling().as_ptr(); + let mut out = 0xDEAD_BEEF; + let result = unsafe { + platform_wallet_manager_accept_contact_request_replying_in_kind( + 0xDEAD_BEEF, + wallet_id.as_ptr(), + resolver, + 0, + 0xDEAD_BEEF, + std::ptr::null(), + std::ptr::null_mut(), + &mut out, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + + /// A request that did not come privately is accepted with a document, which + /// needs neither shielded support nor the spend authority: on a manager + /// whose shielded support was never configured (and in a build without + /// it), the accept gets past the lookups to the wallet's own refusal (the + /// recipient is not one of its identities, reported as the public accept + /// reports it), and the resolver is never asked for the mnemonic. + #[test] + fn should_accept_publicly_without_shielded_support_or_a_mnemonic_read() { + use crate::contact_request::contact_request_destroy; + use crate::event_handler::EventHandlerCallbacks; + use crate::manager::{ + platform_wallet_manager_create, platform_wallet_manager_create_wallet_from_mnemonic, + platform_wallet_manager_destroy, + }; + use crate::persistence::PersistenceCallbacks; + use platform_wallet::ContactRequest; + use rs_sdk_ffi::{ + dash_sdk_mnemonic_resolver_create, dash_sdk_mnemonic_resolver_destroy, + dash_sdk_signer_create, dash_sdk_signer_destroy, mnemonic_resolver_result, + SignCompletionCallback, + }; + use std::ffi::{c_void, CStr}; + use std::os::raw::c_char; + use std::sync::atomic::{AtomicUsize, Ordering}; + + unsafe extern "C" fn begin(_: *mut c_void, _: *const u8) -> i32 { + 0 + } + unsafe extern "C" fn end(_: *mut c_void, _: *const u8, _: bool) -> i32 { + 0 + } + unsafe extern "C" fn counting_resolve( + ctx: *const c_void, + _wallet_id: *const u8, + _out: *mut c_char, + _capacity: usize, + _out_len: *mut usize, + ) -> i32 { + (*(ctx as *const AtomicUsize)).fetch_add(1, Ordering::SeqCst); + mnemonic_resolver_result::NOT_FOUND + } + unsafe extern "C" fn noop_destroy(_ctx: *mut c_void) {} + // A public reply to this request is refused before anything is signed; + // a signature request would fail rather than hang. + unsafe extern "C" fn refuse_to_sign( + _signer: *const c_void, + _pubkey: *const u8, + _pubkey_len: usize, + _key_type: u8, + _data: *const u8, + _data_len: usize, + completion_ctx: *mut c_void, + completion: SignCompletionCallback, + ) { + completion( + completion_ctx, + std::ptr::null(), + 0, + 1, + c"no key in this test".as_ptr(), + ); + } + unsafe extern "C" fn cannot_sign( + _signer: *const c_void, + _pubkey: *const u8, + _pubkey_len: usize, + _key_type: u8, + ) -> bool { + false + } + + let sdk = dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk"); + let persistence = PersistenceCallbacks { + on_changeset_begin_fn: Some(begin), + on_changeset_end_fn: Some(end), + ..Default::default() + }; + let events = EventHandlerCallbacks { + context: std::ptr::null_mut(), + on_wallet_event_fn: None, + on_error_fn: None, + on_platform_address_sync_completed_fn: None, + on_shielded_sync_completed_fn: None, + on_shielded_sync_progress_fn: None, + on_shielded_tree_progress_fn: None, + release_fn: None, + }; + let mut manager = NULL_HANDLE; + let created = unsafe { + platform_wallet_manager_create( + &sdk as *const dash_sdk::Sdk as *const c_void, + &persistence, + &events, + &mut manager, + ) + }; + assert_eq!(created.code, PlatformWalletFFIResultCode::Success); + + let mnemonic = c"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + let mut wallet_handle = NULL_HANDLE; + let mut wallet_id = [0u8; 32]; + let added = unsafe { + platform_wallet_manager_create_wallet_from_mnemonic( + manager, + mnemonic.as_ptr(), + FFINetwork::Testnet, + 0, + &mut wallet_handle, + &mut wallet_id, + ) + }; + assert_eq!( + added.code, + PlatformWalletFFIResultCode::Success, + "the wallet is added" + ); + + // A request to an identity the wallet does not manage. + let request = ContactRequest::new( + [0xA0; 32].into(), + [0xB0; 32].into(), + 1, + 2, + 7, + vec![0x33; 96], + 100, + 1_700_000_000_000, + ); + let request_handle = CONTACT_REQUEST_STORAGE.insert(request); + let reads = AtomicUsize::new(0); + let resolver = unsafe { + dash_sdk_mnemonic_resolver_create( + &reads as *const AtomicUsize as *mut c_void, + counting_resolve, + noop_destroy, + ) + }; + let signer = unsafe { dash_sdk_signer_create(refuse_to_sign, cannot_sign, None) }; + + let mut established = 0xDEAD_BEEF; + let result = unsafe { + platform_wallet_manager_accept_contact_request_replying_in_kind( + manager, + wallet_id.as_ptr(), + resolver, + 0, + request_handle, + std::ptr::null(), + signer, + &mut established, + ) + }; + // Exactly what the public accept reports for this refusal (the + // wallet's `IdentityNotFound`), not the missing-coordinator error an + // up-front lookup gave. + let expected = + PlatformWalletFFIResult::from(PlatformWalletError::IdentityNotFound([0xB0; 32].into())); + let message_of = |result: &PlatformWalletFFIResult| { + if result.message.is_null() { + String::new() + } else { + unsafe { CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned() + } + }; + assert_eq!(result.code, expected.code, "{}", message_of(&result)); + assert_eq!(message_of(&result), message_of(&expected)); + assert_eq!(established, NULL_HANDLE); + assert_eq!(reads.load(Ordering::SeqCst), 0, "no mnemonic was read"); + + let _ = contact_request_destroy(request_handle); + unsafe { + dash_sdk_signer_destroy(signer); + dash_sdk_mnemonic_resolver_destroy(resolver); + } + let _ = unsafe { platform_wallet_manager_destroy(manager) }; + } + + /// The accept replying in kind, for an identity the wallet manages, + /// routes a request that came publicly without asking for shielded + /// payment resources, on a manager whose shielded support was never + /// configured (and in a build without it): a request already replied to + /// is adopted, and a fresh one gets a public reply that reaches the + /// identity signer. Payment resources (the shielded coordinator and the + /// spend seed) would fail here with "not configured"; the resolver is + /// still read, for the DashPay crypto (the seed check and the reply's + /// encryption), which is what a public reply legitimately needs. + #[test] + fn should_adopt_or_reply_publicly_for_a_managed_identity_without_payment_resources() { + use crate::contact_request::contact_request_destroy; + use crate::event_handler::EventHandlerCallbacks; + use crate::manager::{ + platform_wallet_manager_create, platform_wallet_manager_create_wallet_from_mnemonic, + platform_wallet_manager_destroy, + }; + use crate::persistence::PersistenceCallbacks; + use crate::runtime::runtime; + use dash_sdk::error::ContextProviderError; + use dash_sdk::platform::dashpay::PRIVATE_CONTACT_REQUEST_DOCUMENT_TYPE_NAME; + use dash_sdk::platform::private_document_entries::{ + PrivateDocumentEntries, PrivateDocumentEntriesQuery, + }; + use dash_sdk::platform::ContextProvider; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contract::{DataContract, TokenConfiguration}; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::v0::IdentityV0; + use dpp::identity::{Identity, IdentityPublicKey, KeyID, KeyType, Purpose, SecurityLevel}; + use dpp::platform_value::BinaryData; + use dpp::prelude::Identifier; + use dpp::version::PlatformVersion; + use key_wallet::bip32::KeyDerivationType; + use key_wallet::mnemonic::Mnemonic; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + use platform_wallet::wallet::identity::network::identity_auth_derivation_path_for_type; + use platform_wallet::ContactRequest; + use rs_sdk_ffi::{ + dash_sdk_mnemonic_resolver_create, dash_sdk_mnemonic_resolver_destroy, + dash_sdk_signer_create, dash_sdk_signer_destroy, mnemonic_resolver_result, + SignCompletionCallback, + }; + use std::ffi::{c_void, CString}; + use std::os::raw::c_char; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + const BOB_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon about"; + const ALICE_PHRASE: &str = + "legal winner thank year wave sausage worth useful legal winner thank yellow"; + const SIGNING_KEY_ID: KeyID = 0; + const ENCRYPTION_KEY_ID: KeyID = 1; + const DECRYPTION_KEY_ID: KeyID = 2; + + struct DashpayProvider(Arc); + impl ContextProvider for DashpayProvider { + fn get_data_contract( + &self, + id: &Identifier, + _platform_version: &PlatformVersion, + ) -> Result>, ContextProviderError> { + Ok((*id == self.0.id()).then(|| Arc::clone(&self.0))) + } + fn get_token_configuration( + &self, + _token_id: &Identifier, + ) -> Result, ContextProviderError> { + Ok(None) + } + fn get_quorum_public_key( + &self, + _quorum_type: u32, + _quorum_hash: [u8; 32], + _core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + Err(ContextProviderError::Config( + "no quorum keys in this test".into(), + )) + } + fn get_platform_activation_height(&self) -> Result { + Ok(1) + } + } + + /// Identity index 0's ECDSA keys of `phrase`, as the wallet derives them. + fn identity(phrase: &str, id: [u8; 32]) -> Identity { + let seed = *Mnemonic::from_phrase(phrase) + .expect("test mnemonic") + .to_seed(""); + let wallet = key_wallet::wallet::Wallet::from_seed_bytes( + seed, + key_wallet::Network::Testnet, + WalletAccountCreationOptions::None, + ) + .expect("test wallet"); + let key = |key_id: KeyID, purpose: Purpose, security_level: SecurityLevel| { + let path = identity_auth_derivation_path_for_type( + key_wallet::Network::Testnet, + KeyDerivationType::ECDSA, + 0, + key_id, + ) + .expect("identity key path"); + let xprv = wallet + .derive_extended_private_key(&path) + .expect("identity key"); + let secret = + dpp::secp256k1::SecretKey::from_secret_bytes(*xprv.private_key.to_bytes()) + .expect("secret key"); + IdentityPublicKey::V0(IdentityPublicKeyV0 { + id: key_id, + purpose, + security_level, + contract_bounds: None, + key_type: KeyType::ECDSA_SECP256K1, + read_only: false, + data: BinaryData::new( + dpp::secp256k1::PublicKey::from_secret_key(&secret) + .serialize() + .to_vec(), + ), + disabled_at: None, + }) + }; + let keys = [ + key(SIGNING_KEY_ID, Purpose::AUTHENTICATION, SecurityLevel::HIGH), + key( + ENCRYPTION_KEY_ID, + Purpose::ENCRYPTION, + SecurityLevel::MEDIUM, + ), + key( + DECRYPTION_KEY_ID, + Purpose::DECRYPTION, + SecurityLevel::MEDIUM, + ), + ]; + Identity::V0(IdentityV0 { + id: Identifier::from(id), + public_keys: keys.into_iter().map(|key| (key.id(), key)).collect(), + balance: 0, + revision: 0, + }) + } + fn public_request(sender: &Identity, recipient: &Identity, account: u32) -> ContactRequest { + ContactRequest::new( + sender.id(), + recipient.id(), + ENCRYPTION_KEY_ID, + DECRYPTION_KEY_ID, + account, + vec![7; 96], + 100, + 1_700_000_000_000, + ) + } + + unsafe extern "C" fn begin(_: *mut c_void, _: *const u8) -> i32 { + 0 + } + unsafe extern "C" fn end(_: *mut c_void, _: *const u8, _: bool) -> i32 { + 0 + } + /// Bob's mnemonic, counting the reads. + unsafe extern "C" fn bob_resolve( + ctx: *const c_void, + _wallet_id: *const u8, + out: *mut c_char, + capacity: usize, + out_len: *mut usize, + ) -> i32 { + (*(ctx as *const AtomicUsize)).fetch_add(1, Ordering::SeqCst); + let phrase = BOB_PHRASE.as_bytes(); + if phrase.len() + 1 > capacity { + return mnemonic_resolver_result::BUFFER_TOO_SMALL; + } + std::ptr::copy_nonoverlapping(phrase.as_ptr() as *const c_char, out, phrase.len()); + *out.add(phrase.len()) = 0; + *out_len = phrase.len(); + mnemonic_resolver_result::SUCCESS + } + unsafe extern "C" fn noop_destroy(_ctx: *mut c_void) {} + static SIGNATURES_ASKED: AtomicUsize = AtomicUsize::new(0); + /// Counts the signature requests and refuses them: the reply is not + /// sent, so the mock needs no broadcast answer. + unsafe extern "C" fn count_and_refuse( + _signer: *const c_void, + _pubkey: *const u8, + _pubkey_len: usize, + _key_type: u8, + _data: *const u8, + _data_len: usize, + completion_ctx: *mut c_void, + completion: SignCompletionCallback, + ) { + SIGNATURES_ASKED.fetch_add(1, Ordering::SeqCst); + completion( + completion_ctx, + std::ptr::null(), + 0, + 1, + c"no signature in this test".as_ptr(), + ); + } + unsafe extern "C" fn can_sign( + _signer: *const c_void, + _pubkey: *const u8, + _pubkey_len: usize, + _key_type: u8, + ) -> bool { + true + } + + let alice = identity(ALICE_PHRASE, [0xA1; 32]); + let bob = identity(BOB_PHRASE, [0xB1; 32]); + let incoming = public_request(&alice, &bob, 3); + + let mut outcomes = Vec::new(); + for adopt in [true, false] { + let platform_version = PlatformVersion::latest(); + let contract = Arc::new( + dpp::system_data_contracts::load_system_data_contract( + dpp::data_contracts::SystemDataContract::Dashpay, + platform_version, + ) + .expect("bundled DashPay"), + ); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(key_wallet::Network::Testnet) + .with_version(platform_version) + .with_context_provider(DashpayProvider(Arc::clone(&contract))) + .build() + .expect("mock sdk"); + runtime().block_on(async { + sdk.mock() + .expect_fetch(contract.id(), Some((*contract).clone())) + .await + .expect("DashPay expectation"); + for known in [&alice, &bob] { + sdk.mock() + .expect_fetch(known.id(), Some((*known).clone())) + .await + .expect("identity expectation"); + } + sdk.mock() + .expect_fetch( + PrivateDocumentEntriesQuery::new( + contract.id(), + PRIVATE_CONTACT_REQUEST_DOCUMENT_TYPE_NAME, + 0, + ), + Some(PrivateDocumentEntries { + chunk_power: None, + entries: Vec::new(), + total_count: 0, + }), + ) + .await + .expect("store page expectation"); + // A public reply takes Bob's DashPay contract nonce before it + // is signed. + sdk.mock() + .expect_fetch::( + (bob.id(), contract.id()), + None, + ) + .await + .expect("contract nonce expectation"); + }); + + let persistence = PersistenceCallbacks { + on_changeset_begin_fn: Some(begin), + on_changeset_end_fn: Some(end), + ..Default::default() + }; + let events = EventHandlerCallbacks { + context: std::ptr::null_mut(), + on_wallet_event_fn: None, + on_error_fn: None, + on_platform_address_sync_completed_fn: None, + on_shielded_sync_completed_fn: None, + on_shielded_sync_progress_fn: None, + on_shielded_tree_progress_fn: None, + release_fn: None, + }; + let mut manager = NULL_HANDLE; + let created = unsafe { + platform_wallet_manager_create( + &sdk as *const dash_sdk::Sdk as *const c_void, + &persistence, + &events, + &mut manager, + ) + }; + assert_eq!(created.code, PlatformWalletFFIResultCode::Success); + let mnemonic = CString::new(BOB_PHRASE).expect("phrase"); + let mut wallet_handle = NULL_HANDLE; + let mut wallet_id = [0u8; 32]; + // Default accounts: the seed check verifies the resolver against + // BIP44 account 0. + let added = unsafe { + platform_wallet_manager_create_wallet_from_mnemonic( + manager, + mnemonic.as_ptr(), + FFINetwork::Testnet, + 1, + &mut wallet_handle, + &mut wallet_id, + ) + }; + assert_eq!(added.code, PlatformWalletFFIResultCode::Success); + + // Bob is the wallet's identity, holding Alice's public request, + // and, to adopt, the reply already sent to her. + let reply = public_request(&bob, &alice, 4); + PLATFORM_WALLET_STORAGE + .with_item(wallet_handle, |wallet| { + runtime().block_on(async { + let mut wm = wallet.wallet_manager().write().await; + let manager = &mut wm + .get_wallet_info_mut(&wallet.wallet_id()) + .expect("the wallet's info") + .identity_manager; + manager + .add_identity(bob.clone(), 0, wallet.wallet_id(), wallet.persister()) + .expect("Bob"); + let managed = manager.managed_identity_mut(&bob.id()).expect("Bob"); + managed + .add_incoming_contact_request(incoming.clone(), wallet.persister()) + .expect("Alice's request"); + if adopt { + managed + .add_sent_contact_request(reply.clone(), wallet.persister()) + .expect("the reply"); + } + }) + }) + .expect("the wallet"); + + let reads = AtomicUsize::new(0); + let resolver = unsafe { + dash_sdk_mnemonic_resolver_create( + &reads as *const AtomicUsize as *mut c_void, + bob_resolve, + noop_destroy, + ) + }; + let signer = unsafe { dash_sdk_signer_create(count_and_refuse, can_sign, None) }; + let request_handle = CONTACT_REQUEST_STORAGE.insert(incoming.clone()); + let signatures_before = SIGNATURES_ASKED.load(Ordering::SeqCst); + let mut established = NULL_HANDLE; + let result = unsafe { + platform_wallet_manager_accept_contact_request_replying_in_kind( + manager, + wallet_id.as_ptr(), + resolver, + 0, + request_handle, + std::ptr::null(), + signer, + &mut established, + ) + }; + let message = if result.message.is_null() { + String::new() + } else { + unsafe { std::ffi::CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned() + }; + outcomes.push(( + adopt, + result.code, + message, + established, + SIGNATURES_ASKED.load(Ordering::SeqCst) - signatures_before, + reads.load(Ordering::SeqCst), + )); + + if established != NULL_HANDLE { + ESTABLISHED_CONTACT_STORAGE.remove(established); + } + let _ = contact_request_destroy(request_handle); + unsafe { + dash_sdk_signer_destroy(signer); + dash_sdk_mnemonic_resolver_destroy(resolver); + } + let _ = unsafe { platform_wallet_manager_destroy(manager) }; + } + + let (_, adopted_code, adopted_message, adopted, adopted_signatures, _) = &outcomes[0]; + assert_eq!( + *adopted_code, + PlatformWalletFFIResultCode::Success, + "the reply already sent is adopted: {adopted_message}" + ); + assert_ne!( + *adopted, NULL_HANDLE, + "an established contact is handed out" + ); + assert_eq!(*adopted_signatures, 0, "nothing is signed to adopt"); + + let (_, replied_code, replied_message, replied, replied_signatures, replied_reads) = + &outcomes[1]; + assert_ne!(*replied_code, PlatformWalletFFIResultCode::Success); + assert_eq!(*replied, NULL_HANDLE); + assert!( + !replied_message.contains("not configured"), + "no payment resource was asked for: {replied_message}" + ); + assert!( + *replied_signatures > 0, + "the public reply reaches the identity signer: {replied_message}" + ); + assert!(*replied_reads > 0, "the DashPay crypto reads the mnemonic"); + } + + /// A wallet whose identity is paying for nothing to a contact reads the + /// pair as free, no public request to it as unconfirmed, and has no + /// restoration failure to give; an unknown wallet + /// is not found and an identity the wallet does not hold is code 7, each + /// leaving the output reset; a null output is refused. Holding a pair is the wallet's own + /// (its tests pin the reservation and the journal mirror), so this pins + /// the reads. + #[test] + fn should_read_a_pair_s_hold_and_the_restore_failure_from_the_wallet() { + use crate::runtime::runtime; + use crate::test_fixtures::mock_manager; + use dpp::identity::{Identity, IdentityV0}; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + let sender_id = [0xB0u8; 32]; + let recipient_id = [0xA0u8; 32]; + let manager = mock_manager(); + let wallet = runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[11; 64], + WalletAccountCreationOptions::Default, + Some(0), + )) + .expect("a wallet"); + let identity = Identity::V0(IdentityV0 { + id: sender_id.into(), + public_keys: Default::default(), + balance: 0, + revision: 0, + }); + runtime().block_on(async { + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .expect("the wallet's info") + .identity_manager + .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) + .expect("the identity"); + }); + let handle = PLATFORM_WALLET_STORAGE.insert(wallet); + + let mut held = true; + let free = unsafe { + platform_wallet_get_private_pair_held( + handle, + sender_id.as_ptr(), + recipient_id.as_ptr(), + &mut held, + ) + }; + assert_eq!(free.code, PlatformWalletFFIResultCode::Success); + assert!(!held, "nothing holds the pair"); + + let mut unconfirmed = true; + let none = unsafe { + platform_wallet_get_public_contact_request_unconfirmed( + handle, + sender_id.as_ptr(), + recipient_id.as_ptr(), + &mut unconfirmed, + ) + }; + assert_eq!(none.code, PlatformWalletFFIResultCode::Success); + assert!( + !unconfirmed, + "no public request to the pair awaits its outcome" + ); + let mut unconfirmed = true; + let unknown_wallet = unsafe { + platform_wallet_get_public_contact_request_unconfirmed( + Handle::MAX, + sender_id.as_ptr(), + recipient_id.as_ptr(), + &mut unconfirmed, + ) + }; + assert_eq!(unknown_wallet.code, PlatformWalletFFIResultCode::NotFound); + assert!(!unconfirmed, "reset"); + let mut unconfirmed = true; + let unknown_sender = unsafe { + platform_wallet_get_public_contact_request_unconfirmed( + handle, + [0xC1u8; 32].as_ptr(), + recipient_id.as_ptr(), + &mut unconfirmed, + ) + }; + assert_eq!( + unknown_sender.code, + PlatformWalletFFIResultCode::ErrorIdentityNotFound + ); + assert!(!unconfirmed); + assert_eq!( + unsafe { + platform_wallet_get_public_contact_request_unconfirmed( + handle, + sender_id.as_ptr(), + recipient_id.as_ptr(), + std::ptr::null_mut(), + ) + } + .code, + PlatformWalletFFIResultCode::ErrorNullPointer + ); + + let mut reason: *mut c_char = std::ptr::dangling_mut(); + let none = unsafe { + platform_wallet_get_private_payments_restore_failure( + handle, + sender_id.as_ptr(), + &mut reason, + ) + }; + assert_eq!(none.code, PlatformWalletFFIResultCode::Success); + assert!(reason.is_null(), "no restoration failed"); + + let mut held = true; + let unknown_wallet = unsafe { + platform_wallet_get_private_pair_held( + Handle::MAX, + sender_id.as_ptr(), + recipient_id.as_ptr(), + &mut held, + ) + }; + assert_eq!(unknown_wallet.code, PlatformWalletFFIResultCode::NotFound); + assert!(!held, "reset"); + let mut reason: *mut c_char = std::ptr::dangling_mut(); + let unknown_wallet = unsafe { + platform_wallet_get_private_payments_restore_failure( + Handle::MAX, + sender_id.as_ptr(), + &mut reason, + ) + }; + assert_eq!(unknown_wallet.code, PlatformWalletFFIResultCode::NotFound); + assert!(reason.is_null(), "reset"); + + let stranger = [0xC0u8; 32]; + let mut held = true; + let unknown_sender = unsafe { + platform_wallet_get_private_pair_held( + handle, + stranger.as_ptr(), + recipient_id.as_ptr(), + &mut held, + ) + }; + assert_eq!( + unknown_sender.code, + PlatformWalletFFIResultCode::ErrorIdentityNotFound + ); + assert!(!held); + let mut reason: *mut c_char = std::ptr::dangling_mut(); + let unknown_identity = unsafe { + platform_wallet_get_private_payments_restore_failure( + handle, + stranger.as_ptr(), + &mut reason, + ) + }; + assert_eq!( + unknown_identity.code, + PlatformWalletFFIResultCode::ErrorIdentityNotFound + ); + assert!(reason.is_null(), "reset"); + + assert_eq!( + unsafe { + platform_wallet_get_private_pair_held( + handle, + sender_id.as_ptr(), + recipient_id.as_ptr(), + std::ptr::null_mut(), + ) + } + .code, + PlatformWalletFFIResultCode::ErrorNullPointer + ); + assert_eq!( + unsafe { + platform_wallet_get_private_payments_restore_failure( + handle, + sender_id.as_ptr(), + std::ptr::null_mut(), + ) + } + .code, + PlatformWalletFFIResultCode::ErrorNullPointer + ); + + let _ = PLATFORM_WALLET_STORAGE.remove(handle); + } + + #[test] + fn should_carry_every_field_of_a_private_contact() { + let address = [0x55; SHIELDED_ADDRESS_LEN]; + let with_address = PrivateContactFFI::from(PrivateContact { + received_privately: true, + sent_privately: false, + shielded_address: Some(address), + }); + assert!(with_address.received_privately); + assert!(!with_address.sent_privately); + assert!(with_address.has_shielded_address); + assert_eq!(with_address.shielded_address, address); + + let without_address = PrivateContactFFI::from(PrivateContact { + received_privately: false, + sent_privately: true, + shielded_address: None, + }); + assert!(without_address.sent_privately); + assert!(!without_address.has_shielded_address); + assert_eq!(without_address.shielded_address, [0; SHIELDED_ADDRESS_LEN]); + } + + #[test] + fn should_report_no_private_contact_for_an_unknown_identity_handle() { + let mut contact = PrivateContactFFI { + received_privately: true, + sent_privately: true, + has_shielded_address: true, + shielded_address: [0x55; SHIELDED_ADDRESS_LEN], + }; + let contact_id = [7u8; 32]; + let result = unsafe { + managed_identity_get_private_contact(0xDEAD_BEEF, contact_id.as_ptr(), &mut contact) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::NotFound); + assert_eq!(contact, PrivateContactFFI::empty()); + } +} diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index df107b89a24..00161411428 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -563,7 +563,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_withdraw( /// prune backstop); the pass outcome is logged, not surfaced. /// /// [`ShieldedSyncManager::sync_now`]: platform_wallet::manager::shielded_sync::ShieldedSyncManager::sync_now -fn poke_sync_on_unconfirmed(result: &Result, handle: Handle) { +pub(crate) fn poke_sync_on_unconfirmed(result: &Result, handle: Handle) { let ambiguous = matches!( result, Err(PlatformWalletError::ShieldedSpendUnconfirmed { .. }) @@ -787,7 +787,7 @@ const SPEND_PANIC_GUIDANCE: &str = "The spend may or may not have been broadcast /// transition was broadcast, so the outcome is genuinely ambiguous. That code's contract is /// exactly the conservative one this needs — the host must not auto-retry, the reservation stays /// in place, and the next nullifier sync reconciles whether the spend landed. -fn catch_spend_panic( +pub(crate) fn catch_spend_panic( operation: &str, body: impl FnOnce() -> PlatformWalletFFIResult, ) -> PlatformWalletFFIResult { @@ -2372,6 +2372,30 @@ pub(crate) fn resolve_wallet_and_coordinator( Ok((wallet, coordinator)) } +/// The coordinator half of [`resolve_wallet_and_coordinator`], with the same +/// errors. It blocks on the runtime, so it must not run on one of its async +/// workers: call it from the export's thread or from `spawn_blocking`. +pub(crate) fn resolve_shielded_coordinator( + handle: Handle, +) -> Result< + std::sync::Arc, + PlatformWalletFFIResult, +> { + match PLATFORM_WALLET_MANAGER_STORAGE.with_item(handle, |manager| { + runtime().block_on(manager.shielded_coordinator()) + }) { + None => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidHandle, + format!("invalid manager handle: {handle}"), + )), + Some(None) => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + "shielded support not configured: call platform_wallet_manager_configure_shielded first", + )), + Some(Some(coordinator)) => Ok(coordinator), + } +} + #[cfg(test)] mod tests { use super::*; @@ -3038,6 +3062,68 @@ mod tests { assert!(message_of(&result).contains("this request was not started")); } + /// A protocol-version refusal from the store read a private send or + /// accept makes before paying keeps the blanket conversion's split: a + /// lasting refusal is code 70, a transient one the catch-all. + #[test] + fn map_spend_result_keeps_a_protocol_version_refusal_typed() { + let refused = |cause: Option>| { + map_spend_result( + Err(PlatformWalletError::Sdk( + dash_sdk::Error::ProtocolVersionNotActive { + method: "get_private_document_entries", + required: 15, + feature: None, + network: 14, + pinned: false, + cause, + }, + )), + "private contact request", + ) + }; + let lasting = refused(None); + assert_eq!( + lasting.code, + PlatformWalletFFIResultCode::ErrorProtocolVersionNotActive + ); + assert_eq!(lasting.code as i32, 70); + let transient = refused(Some(Box::new(dash_sdk::Error::Generic( + "no node answered".to_string(), + )))); + assert_eq!(transient.code, PlatformWalletFFIResultCode::ErrorUnknown); + assert_eq!( + map_spend_result( + Err(PlatformWalletError::PrivateContactPaymentsNotRestored), + "private contact request", + ) + .code, + PlatformWalletFFIResultCode::ErrorPrivateContactPaymentsNotRestored + ); + } + + /// A persister that cannot keep a private payment's recovery state is + /// refused by the explicit private send and accept before anything is + /// sealed or paid; the refusal keeps its own code (73) through the spend + /// mapper they use, as the in-kind accept's blanket conversion does. + #[test] + fn map_spend_result_keeps_the_storage_configuration_refusal_at_73() { + let result = map_spend_result( + Err(PlatformWalletError::PrivateContactRecoveryUnsupported), + "private contact request", + ); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorPrivateContactRecoveryUnsupported + ); + assert_eq!(result.code as i32, 73); + assert_eq!( + result.code, + PlatformWalletFFIResult::from(PlatformWalletError::PrivateContactRecoveryUnsupported) + .code + ); + } + /// A private payment refused because its wallet was removed first keeps /// the lifecycle refusal code, not the generic operation failure. #[test] diff --git a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs index d41459b6586..8e2db501f64 100644 --- a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs +++ b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs @@ -22,11 +22,15 @@ pub(crate) fn mock_manager() -> PlatformWalletManager { unsafe extern "C" fn end(_: *mut std::ffi::c_void, _: *const u8, _: bool) -> i32 { 0 } - let persister = FFIPersister::new(PersistenceCallbacks { + mock_manager_with(FFIPersister::new(PersistenceCallbacks { on_changeset_begin_fn: Some(begin), on_changeset_end_fn: Some(end), ..Default::default() - }); + })) +} + +/// [`mock_manager`] over `persister`. +pub(crate) fn mock_manager_with(persister: FFIPersister) -> PlatformWalletManager { let events = FFIEventHandler::new( EventHandlerCallbacks { context: std::ptr::null_mut(), diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift index e1ba0479049..d41f20aba2a 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift @@ -94,7 +94,9 @@ public enum DashModelContainer { PersistentInvitation.self, PersistentMasternode.self, PersistentTrackedMasternode.self, - PersistentIdentityBalanceMetadata.self + PersistentIdentityBalanceMetadata.self, + PersistentPrivateContactRequestsPosition.self, + PersistentPrivateShieldedAddress.self ] } @@ -394,7 +396,9 @@ public enum DashSchemaV4: VersionedSchema { public static var models: [any PersistentModel.Type] { DashSchemaSnapshotV4.models } } -/// Current schema: an asset lock records the optional Orchard recipient of its shielded funding. +/// Current schema: an asset lock records the optional Orchard recipient of its +/// shielded funding, and the private contact request sync keeps its scan state +/// (each identity's read position and its private contacts' shielded addresses). 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/PersistentPrivateContactRequestsPosition.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateContactRequestsPosition.swift new file mode 100644 index 00000000000..789db14d2cb --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateContactRequestsPosition.swift @@ -0,0 +1,34 @@ +import Foundation +import SwiftData + +/// Where an identity reads DashPay's private contact request store from +/// next, so a relaunch resumes the private contact request sync instead of +/// reading the store from its start. Written in the same changeset round as +/// the contact requests read before it. +@Model +public final class PersistentPrivateContactRequestsPosition { + #Unique([\.networkRaw, \.walletId, \.identityId]) + public var networkRaw: UInt32 + public var walletId: Data + public var identityId: Data + // Bit pattern preserves the full unsigned FFI domain in a SQLite integer. + public var position: Int64 + /// The fingerprint of the scanning keys `position` holds for; opaque + /// here, handed back to the native wallet as it came. + public var keyFingerprint: Data + /// Whether a private contact request the identity paid for may still be + /// unresolved; handed back as it came. Loaded set, Rust holds the + /// identity's public contact requests until its private payments are + /// restored from the shielded store. + public var privatePaymentsUnresolved: Bool = false + + public init(networkRaw: UInt32, walletId: Data, identityId: Data, + position: UInt64, keyFingerprint: Data, privatePaymentsUnresolved: Bool = false) { + self.networkRaw = networkRaw + self.walletId = walletId + self.identityId = identityId + self.position = Int64(bitPattern: position) + self.keyFingerprint = keyFingerprint + self.privatePaymentsUnresolved = privatePaymentsUnresolved + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift new file mode 100644 index 00000000000..6468811ed80 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift @@ -0,0 +1,26 @@ +import Foundation +import SwiftData + +/// The shielded address a private contact's tracked request to one of the +/// wallet's identities carries, kept so a relaunch has it without reading +/// the private contact request store again. +@Model +public final class PersistentPrivateShieldedAddress { + #Unique([\.networkRaw, \.walletId, \.ownerId, \.contactId]) + public var networkRaw: UInt32 + public var walletId: Data + /// The wallet-owned identity the request is to. + public var ownerId: Data + /// The contact who sent the request. + public var contactId: Data + /// The raw 43-byte Orchard payment address. + public var address: Data + + public init(networkRaw: UInt32, walletId: Data, ownerId: Data, contactId: Data, address: Data) { + self.networkRaw = networkRaw + self.walletId = walletId + self.ownerId = ownerId + self.contactId = contactId + self.address = address + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/IdentityManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/IdentityManager.swift index a057c1a9003..0ef387a8d28 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/IdentityManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/IdentityManager.swift @@ -30,7 +30,12 @@ public class IdentityManager { try identity_manager_add_identity(handle, identity.handle).check() } - /// Remove an identity from the manager + /// Remove an identity from the manager. Refused while its contact request + /// channel is held: `PlatformWalletError.privateContactRequestPending` + /// for a request in flight or a private payment that may still execute, + /// `.publicContactRequestUnconfirmed` for a public request whose outcome + /// is not proved yet, `.privateContactPaymentsNotRestored` for payments + /// not restored yet. public func removeIdentity(_ identityId: Identifier) throws { try identityId.withFFIBytes { idPtr in try identity_manager_remove_identity(handle, idPtr).check() diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index 292f790b408..fce0f9505e5 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -114,6 +114,18 @@ public struct PlatformWalletPersistenceCapabilities: Equatable, Sendable { /// 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 + /// The private contact request sync's scan state (each identity's read + /// position in DashPay's private contact request store, and its private + /// contacts' shielded addresses) is stored on its round and restored at + /// load, so a relaunch resumes the sync where it stopped. A store + /// declaring it keeps a position record marked unresolved through its + /// wallet's removal, until a record stored cleared for the same wallet + /// and identity replaces it, and lists that wallet so Rust holds the + /// identity again if the wallet comes back. Mirrors + /// `PersistenceCapabilities::PRIVATE_CONTACT_REQUEST_SCAN_STATE`; Rust + /// only honours the declaration when the extension carries the five + /// scan-state callbacks. + public static let privateContactRequestScanState: UInt64 = 1 << 15 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 7bc7e76188e..9f7f44b0cc5 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3311,6 +3311,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { | PlatformWalletPersistenceCapabilities.dashpayPayments | PlatformWalletPersistenceCapabilities.assetLockOperationIds | PlatformWalletPersistenceCapabilities.assetLockShieldedRecipients + | PlatformWalletPersistenceCapabilities.privateContactRequestScanState ) } @@ -3354,6 +3355,14 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { persistAssetLockShieldedRecipientCallback extensionCallbacks.on_load_asset_lock_shielded_recipient_fn = loadAssetLockShieldedRecipientCallback + extensionCallbacks.on_persist_private_contact_scan_state_fn = persistPrivateContactScanStateCallback + extensionCallbacks.on_load_private_contact_scan_state_fn = loadPrivateContactScanStateCallback + extensionCallbacks.on_load_private_contact_scan_state_free_fn = + loadPrivateContactScanStateFreeCallback + extensionCallbacks.on_load_private_contact_scan_state_wallets_fn = + loadPrivateContactScanStateWalletsCallback + extensionCallbacks.on_load_private_contact_scan_state_wallets_free_fn = + loadPrivateContactScanStateWalletsFreeCallback return extensionCallbacks } @@ -4444,54 +4453,42 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// /// The owner identity is required to exist in SwiftData before /// the row is inserted — the relationship is non-optional and - /// `networkRaw` is read off it. If a flush carries a contact - /// upsert for an owner identity Swift hasn't seen yet (race with - /// a first-time identity flush), the row is skipped; the next - /// flush will replay it after the identity row lands. In - /// practice the changeset is one round, so this only matters - /// for the very first identity registration where the contact - /// changeset and identity changeset arrive in the same store() - /// call — within a round, identities apply before contacts (see - /// the ordering in `FFIPersister::store`), so the lookup here - /// will normally succeed. + /// `networkRaw` is read off it. Within a round identities apply + /// before contacts (see the ordering in `FFIPersister::store`), and + /// the wallet only stores contact requests of the identities it + /// manages, so the owner is there. When it is not, or a fetch fails, + /// this throws, and the callback fails the round: the store declares + /// the private contact request scan state, so a round acknowledged + /// without its contact requests would let the wallet store a read + /// position past a request that was never saved, and no later scan + /// would read it again. A failed round leaves the wallet's read + /// position where it was, so the next scan stores the request. func persistContacts( walletId: Data, upserts: [ContactRequestSnapshot], removedSent: [ContactRequestRemovalSnapshot], removedIncoming: [ContactRequestRemovalSnapshot], ignored: [ContactIgnoredSenderSnapshot] - ) { - onQueue { + ) throws { + try onQueue { for entry in upserts { let ownerId = entry.ownerIdentityId let ownerDescriptor = FetchDescriptor( predicate: #Predicate { $0.identityId == ownerId } ) - guard let owner = try? backgroundContext.fetch(ownerDescriptor).first else { - // Owner identity hasn't landed yet. Within a - // single round identities apply before contacts, - // so we'd only hit this if the FFI changeset - // surfaces a contact for an identity that isn't - // managed by any wallet locally — there's no - // identity row to hang it off, and the contract's - // `ownerId` invariant means the row would be - // orphaned anyway. The recurring sweep replays it - // once the owner row exists; log so a contact that - // is somehow dropped permanently (e.g. an - // out-of-wallet owner with no PersistentIdentity) - // is at least observable rather than vanishing - // silently. + guard let owner = try backgroundContext.fetch(ownerDescriptor).first else { SDKLogger.event( - "persistence_contact_deferred", + "persistence_contact_refused", category: .persistence, - severity: .warning, + severity: .error, fields: [ "identity_reference": .reference(entry.ownerIdentityId), "operation": .publicText("contact_upsert"), "reason": .publicText("identity_missing"), ] ) - continue + throw PlatformWalletError.walletOperation( + "contact request owner identity is not persisted") } let networkRaw = owner.networkRaw @@ -4505,7 +4502,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { && $0.isOutgoing == isOutgoing } ) - if let existing = try? backgroundContext.fetch(descriptor).first { + if let existing = try backgroundContext.fetch(descriptor).first { // Refresh in place — every column is overwritten // because the FFI snapshot is authoritative for // the underlying `ContactRequest` document. This @@ -4558,14 +4555,14 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } for tomb in removedSent { - deleteContactRow( + try deleteContactRow( ownerId: tomb.ownerIdentityId, contactId: tomb.contactIdentityId, isOutgoing: true ) } for tomb in removedIncoming { - deleteContactRow( + try deleteContactRow( ownerId: tomb.ownerIdentityId, contactId: tomb.contactIdentityId, isOutgoing: false @@ -4580,16 +4577,16 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // without (2) the ignored sender resurfaces on the // next post-relaunch sweep. Per-sender (no // accountReference): ALL the sender's incoming rows go. - deleteIgnoredSenderIncomingRows( + try deleteIgnoredSenderIncomingRows( ownerId: row.ownerIdentityId, senderId: row.senderIdentityId ) - upsertIgnoredSender(row) + try upsertIgnoredSender(row) } else { // Un-ignore: delete the ignored-sender row so the // sender's requests resurface on the next sweep (the // Rust side rewinds the cursor to re-fetch them). - deleteIgnoredSender( + try deleteIgnoredSender( ownerId: row.ownerIdentityId, senderId: row.senderIdentityId ) @@ -4607,10 +4604,11 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// identity belongs to exactly one network — so we don't have to /// fan out the predicate across networks. Silent on miss (no /// existing row): the FFI changeset replays tombstones, and an - /// already-removed row is the success state. + /// already-removed row is the success state. A failed fetch throws, + /// failing the round. /// /// Assumes it's already running on `serialQueue`. - private func deleteContactRow(ownerId: Data, contactId: Data, isOutgoing: Bool) { + private func deleteContactRow(ownerId: Data, contactId: Data, isOutgoing: Bool) throws { let direction = isOutgoing let descriptor = FetchDescriptor( predicate: #Predicate { @@ -4619,7 +4617,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { && $0.isOutgoing == direction } ) - if let existing = try? backgroundContext.fetch(descriptor).first { + if let existing = try backgroundContext.fetch(descriptor).first { backgroundContext.delete(existing) } } @@ -4631,7 +4629,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// miss: an already-removed row is the success state. /// /// Assumes it's already running on `serialQueue`. - private func deleteIgnoredSenderIncomingRows(ownerId: Data, senderId: Data) { + private func deleteIgnoredSenderIncomingRows(ownerId: Data, senderId: Data) throws { let descriptor = FetchDescriptor( predicate: #Predicate { $0.ownerIdentityId == ownerId @@ -4639,10 +4637,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { && $0.isOutgoing == false } ) - if let rows = try? backgroundContext.fetch(descriptor) { - for row in rows { - backgroundContext.delete(row) - } + for row in try backgroundContext.fetch(descriptor) { + backgroundContext.delete(row) } } @@ -4656,27 +4652,28 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// Upsert keyed `(networkRaw, ownerIdentityId, ignoredSenderId)` — the /// Rust per-sender suppression key. Idempotent: a replay of the same /// ignore is a no-op. Requires the owner `PersistentIdentity` to exist - /// (the row hangs off it); skipped + logged if it hasn't landed yet — - /// the next sync round replays it. + /// (the row hangs off it); throws, failing the round, when it does not + /// or a fetch fails, as `persistContacts` does for a contact row. /// /// Assumes it's already running on `serialQueue`. - private func upsertIgnoredSender(_ row: ContactIgnoredSenderSnapshot) { + private func upsertIgnoredSender(_ row: ContactIgnoredSenderSnapshot) throws { let ownerId = row.ownerIdentityId let ownerDescriptor = FetchDescriptor( predicate: #Predicate { $0.identityId == ownerId } ) - guard let owner = try? backgroundContext.fetch(ownerDescriptor).first else { + guard let owner = try backgroundContext.fetch(ownerDescriptor).first else { SDKLogger.event( - "persistence_contact_deferred", + "persistence_contact_refused", category: .persistence, - severity: .warning, + severity: .error, fields: [ "identity_reference": .reference(row.ownerIdentityId), "operation": .publicText("ignored_sender"), "reason": .publicText("identity_missing"), ] ) - return + throw PlatformWalletError.walletOperation( + "ignored sender owner identity is not persisted") } let networkRaw = owner.networkRaw @@ -4688,7 +4685,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { && $0.ignoredSenderId == senderId } ) - if (try? backgroundContext.fetch(descriptor).first) == nil { + if try backgroundContext.fetch(descriptor).first == nil { backgroundContext.insert( PersistentDashpayIgnoredSender( owner: owner, @@ -4703,14 +4700,14 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// success state. /// /// Assumes it's already running on `serialQueue`. - private func deleteIgnoredSender(ownerId: Data, senderId: Data) { + private func deleteIgnoredSender(ownerId: Data, senderId: Data) throws { let descriptor = FetchDescriptor( predicate: #Predicate { $0.ownerIdentityId == ownerId && $0.ignoredSenderId == senderId } ) - if let existing = try? backgroundContext.fetch(descriptor).first { + if let existing = try backgroundContext.fetch(descriptor).first { backgroundContext.delete(existing) } } @@ -5172,6 +5169,177 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } } + // MARK: - Private contact request scan state (additive persistence extension) + + /// One identity's read position in DashPay's private contact request store. + struct PrivateContactRequestsPositionRow: Equatable { + let identityId: Data + let position: UInt64 + /// Opaque to this side: stored and handed back as it came. + let keyFingerprint: Data + /// Stored and handed back as it came. + var privatePaymentsUnresolved: Bool = false + } + + /// The shielded address `contactId`'s private request to `ownerId` carries. + struct PrivateShieldedAddressRow: Equatable { + let ownerId: Data + let contactId: Data + let address: Data + } + + /// The `(owner, contact)` pair of a shielded address the round removed. + struct PrivateShieldedAddressKey: Equatable { + let ownerId: Data + let contactId: Data + } + + /// The network the scan state of `walletId` is stored under, as for the + /// identity rows it belongs with: this handler's, else the wallet row's. + /// Nil when neither is known (a handler configured with no network, and + /// the wallet's row already gone). A write then refuses rather than file + /// the state under a guessed network, and a read takes the wallet's rows + /// under every stored network: a position record kept marked for a + /// removed wallet carries the network it was stored under, and guessing + /// one would read a kept record as absent. + private func scanStateNetworkRaw(walletId: Data) -> UInt32? { + (self.network ?? walletNetwork(walletId: walletId))?.rawValue + } + + /// Apply a round's scan state. Identities the round removed lose theirs + /// first, so a new position or address in the same round stands. + func persistPrivateContactScanState( + walletId: Data, + positions: [PrivateContactRequestsPositionRow], + addresses: [PrivateShieldedAddressRow], + removedAddresses: [PrivateShieldedAddressKey], + clearedIdentities: [Data] + ) throws { + try onQueue { + guard inChangeset else { + throw PlatformWalletError.walletOperation( + "Private contact request scan state requires a changeset") + } + guard let networkRaw = scanStateNetworkRaw(walletId: walletId) else { + throw PlatformWalletError.walletOperation( + "No network to store the private contact request scan state under") + } + for identityId in clearedIdentities { + for row in try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { + $0.networkRaw == networkRaw && $0.walletId == walletId && $0.identityId == identityId + })) { + backgroundContext.delete(row) + } + for row in try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { + $0.networkRaw == networkRaw && $0.walletId == walletId && $0.ownerId == identityId + })) { + backgroundContext.delete(row) + } + } + for row in positions { + let identityId = row.identityId + let existing = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { + $0.networkRaw == networkRaw && $0.walletId == walletId && $0.identityId == identityId + })).first + if let existing { + existing.position = Int64(bitPattern: row.position) + existing.keyFingerprint = row.keyFingerprint + existing.privatePaymentsUnresolved = row.privatePaymentsUnresolved + } else { + backgroundContext.insert(PersistentPrivateContactRequestsPosition( + networkRaw: networkRaw, walletId: walletId, identityId: identityId, + position: row.position, keyFingerprint: row.keyFingerprint, + privatePaymentsUnresolved: row.privatePaymentsUnresolved)) + } + } + for row in addresses { + let ownerId = row.ownerId + let contactId = row.contactId + let existing = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { + $0.networkRaw == networkRaw && $0.walletId == walletId + && $0.ownerId == ownerId && $0.contactId == contactId + })).first + if let existing { + existing.address = row.address + } else { + backgroundContext.insert(PersistentPrivateShieldedAddress( + networkRaw: networkRaw, walletId: walletId, ownerId: ownerId, + contactId: contactId, address: row.address)) + } + } + for key in removedAddresses { + let ownerId = key.ownerId + let contactId = key.contactId + for row in try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { + $0.networkRaw == networkRaw && $0.walletId == walletId + && $0.ownerId == ownerId && $0.contactId == contactId + })) { + backgroundContext.delete(row) + } + } + // endChangeset performs the atomic save with the round's contacts. + } + } + + /// The ids of every wallet this handler's network keeps private contact + /// request scan state for, a removed wallet whose marked position + /// records outlived it included. Rust reads each one its wallet-list + /// load does not return and hands its marked records to the wallet as + /// retained. A handler configured with no network lists the wallets of + /// every stored network rather than guess one: a kept record carries the + /// network it was stored under. Throws when the store cannot be read. + func loadPrivateContactScanStateWalletIds() throws -> [Data] { + try onQueue { + let positions: [PersistentPrivateContactRequestsPosition] + if let networkRaw = self.network?.rawValue { + positions = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.networkRaw == networkRaw })) + } else { + positions = try backgroundContext.fetch(FetchDescriptor()) + } + var seen = Set() + return positions.compactMap { seen.insert($0.walletId).inserted ? $0.walletId : nil } + } + } + + /// The stored scan state of `walletId`. Throws when the store cannot be + /// read, so the load fails rather than reading the store from its start. + func loadPrivateContactScanState(walletId: Data) throws + -> (positions: [PrivateContactRequestsPositionRow], addresses: [PrivateShieldedAddressRow]) { + try onQueue { + let positions: [PersistentPrivateContactRequestsPosition] + let addresses: [PersistentPrivateShieldedAddress] + if let networkRaw = scanStateNetworkRaw(walletId: walletId) { + positions = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.networkRaw == networkRaw && $0.walletId == walletId })) + addresses = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.networkRaw == networkRaw && $0.walletId == walletId })) + } else { + // No network known: every stored scope, not a guessed one. + positions = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.walletId == walletId })) + addresses = try backgroundContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.walletId == walletId })) + } + return ( + positions.map { + PrivateContactRequestsPositionRow( + identityId: $0.identityId, position: UInt64(bitPattern: $0.position), + keyFingerprint: $0.keyFingerprint, + privatePaymentsUnresolved: $0.privatePaymentsUnresolved) + }, + addresses.map { + PrivateShieldedAddressRow(ownerId: $0.ownerId, contactId: $0.contactId, address: $0.address) + } + ) + } + } + // MARK: - Identity snapshot structs /// Swift-side snapshot of the Rust `IdentityEntryFFI` with C @@ -6711,6 +6879,35 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { where !claimedNetworks.contains(row.networkRaw) { backgroundContext.delete(row) } + // The private contact request scan state carries the same + // explicit network key, so it is purged by the same rule, + // except a position record whose unresolved-payment marker + // is set: it stands for a private payment that may still + // execute, so it outlives the wallet until a record stored + // cleared for the same wallet and identity replaces it, and + // the next load hands it back as retained + // (`loadPrivateContactScanStateWalletIds`). + let positions: FetchDescriptor + let addresses: FetchDescriptor + if let raw = metadataNetwork?.rawValue { + positions = FetchDescriptor(predicate: #Predicate { + $0.walletId == walletId && $0.networkRaw == raw + }) + addresses = FetchDescriptor(predicate: #Predicate { + $0.walletId == walletId && $0.networkRaw == raw + }) + } else { + positions = FetchDescriptor(predicate: #Predicate { $0.walletId == walletId }) + addresses = FetchDescriptor(predicate: #Predicate { $0.walletId == walletId }) + } + for row in try backgroundContext.fetch(positions) + where !claimedNetworks.contains(row.networkRaw) && !row.privatePaymentsUnresolved { + backgroundContext.delete(row) + } + for row in try backgroundContext.fetch(addresses) + where !claimedNetworks.contains(row.networkRaw) { + backgroundContext.delete(row) + } if let walletRow = walletRow { // Wallet → identities is `.nullify`; this delete @@ -10716,7 +10913,7 @@ private func persistContactsCallback( ) -> Int32 { guard let context = context, let walletIdPtr = walletIdPtr else { - return 0 + return -1 } let handler = Unmanaged .fromOpaque(context) @@ -10824,14 +11021,20 @@ private func persistContactsCallback( } } - handler.persistContacts( - walletId: walletId, - upserts: upserts, - removedSent: removedSent, - removedIncoming: removedIncoming, - ignored: ignored - ) - return 0 + // A contact row that cannot be staged fails the round rather than + // acknowledging it without the row (see `persistContacts`). + do { + try handler.persistContacts( + walletId: walletId, + upserts: upserts, + removedSent: removedSent, + removedIncoming: removedIncoming, + ignored: ignored + ) + return 0 + } catch { + return -1 + } } /// Copy a fixed 32-byte C tuple into an owned `Data`. Used by the @@ -12001,6 +12204,166 @@ private func persistIdentityBalanceBlockTimeCallback( } catch { return -1 } } +/// C shim for `on_persist_private_contact_scan_state_fn`. Copies every row +/// before calling the handler, so Rust can drop its arrays on return. +private func persistPrivateContactScanStateCallback( + context: UnsafeMutableRawPointer?, walletId: UnsafePointer?, + positions: UnsafePointer?, positionsCount: UInt, + addresses: UnsafePointer?, addressesCount: UInt, + removedAddresses: UnsafePointer?, removedAddressesCount: UInt, + clearedIdentities: UnsafePointer?, clearedIdentitiesCount: UInt +) -> Int32 { + guard let context, let walletId else { return -1 } + func rows(_ pointer: UnsafePointer?, _ count: UInt) -> UnsafeBufferPointer? { + guard count > 0 else { return UnsafeBufferPointer(start: nil, count: 0) } + guard let pointer else { return nil } + return UnsafeBufferPointer(start: pointer, count: Int(count)) + } + guard let positionRows = rows(positions, positionsCount), + let addressRows = rows(addresses, addressesCount), + let removedRows = rows(removedAddresses, removedAddressesCount), + let clearedRows = rows(clearedIdentities, clearedIdentitiesCount) else { return -1 } + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + do { + try handler.persistPrivateContactScanState( + walletId: Data(bytes: walletId, count: 32), + positions: positionRows.map { + .init(identityId: dataFromTuple32($0.identity_id), position: $0.position, + keyFingerprint: dataFromTuple32($0.key_fingerprint), + privatePaymentsUnresolved: $0.private_payments_unresolved) + }, + addresses: addressRows.map { + var address = $0.address + return .init(ownerId: dataFromTuple32($0.owner_id), contactId: dataFromTuple32($0.contact_id), + address: Swift.withUnsafeBytes(of: &address) { Data($0) }) + }, + removedAddresses: removedRows.map { + .init(ownerId: dataFromTuple32($0.owner_id), contactId: dataFromTuple32($0.contact_id)) + }, + clearedIdentities: clearedRows.map { dataFromTuple32($0) }) + return 0 + } catch { return -1 } +} + +/// C shim for `on_load_private_contact_scan_state_fn`. Hands Rust two +/// arrays of flat rows, released by the free shim below. A stored row whose +/// bytes have the wrong length cannot cross the ABI: the load fails, as for +/// an unreadable store, rather than handing back the rest without it. +private func loadPrivateContactScanStateCallback( + context: UnsafeMutableRawPointer?, walletId: UnsafePointer?, + outPositions: UnsafeMutablePointer?>?, + outPositionsCount: UnsafeMutablePointer?, + outAddresses: UnsafeMutablePointer?>?, + outAddressesCount: UnsafeMutablePointer? +) -> Int32 { + guard let context, let walletId, let outPositions, let outPositionsCount, + let outAddresses, let outAddressesCount else { return -1 } + outPositions.pointee = nil + outPositionsCount.pointee = 0 + outAddresses.pointee = nil + outAddressesCount.pointee = 0 + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + let stored: (positions: [PlatformWalletPersistenceHandler.PrivateContactRequestsPositionRow], + addresses: [PlatformWalletPersistenceHandler.PrivateShieldedAddressRow]) + do { + stored = try handler.loadPrivateContactScanState(walletId: Data(bytes: walletId, count: 32)) + } catch { return -1 } + // Every row is checked before either output is allocated. + guard stored.positions.allSatisfy({ $0.identityId.count == 32 && $0.keyFingerprint.count == 32 }), + stored.addresses.allSatisfy({ + $0.ownerId.count == 32 && $0.contactId.count == 32 && $0.address.count == 43 + }) else { return -1 } + let positions = stored.positions + let addresses = stored.addresses + if !positions.isEmpty { + let buffer = UnsafeMutablePointer.allocate(capacity: positions.count) + for (index, row) in positions.enumerated() { + var entry = PrivateContactRequestsPositionFFI() + Swift.withUnsafeMutableBytes(of: &entry.identity_id) { _ = row.identityId.copyBytes(to: $0) } + entry.position = row.position + Swift.withUnsafeMutableBytes(of: &entry.key_fingerprint) { _ = row.keyFingerprint.copyBytes(to: $0) } + entry.private_payments_unresolved = row.privatePaymentsUnresolved + (buffer + index).initialize(to: entry) + } + outPositions.pointee = UnsafePointer(buffer) + outPositionsCount.pointee = UInt(positions.count) + } + if !addresses.isEmpty { + let buffer = UnsafeMutablePointer.allocate(capacity: addresses.count) + for (index, row) in addresses.enumerated() { + var entry = PrivateShieldedAddressFFI() + Swift.withUnsafeMutableBytes(of: &entry.owner_id) { _ = row.ownerId.copyBytes(to: $0) } + Swift.withUnsafeMutableBytes(of: &entry.contact_id) { _ = row.contactId.copyBytes(to: $0) } + Swift.withUnsafeMutableBytes(of: &entry.address) { _ = row.address.copyBytes(to: $0) } + (buffer + index).initialize(to: entry) + } + outAddresses.pointee = UnsafePointer(buffer) + outAddressesCount.pointee = UInt(addresses.count) + } + return 0 +} + +/// C shim for `on_load_private_contact_scan_state_free_fn`: the rows are +/// flat, so releasing the two arrays is all there is to it. +private func loadPrivateContactScanStateFreeCallback( + context: UnsafeMutableRawPointer?, + positions: UnsafePointer?, positionsCount: UInt, + addresses: UnsafePointer?, addressesCount: UInt +) { + if let positions { + let buffer = UnsafeMutablePointer(mutating: positions) + buffer.deinitialize(count: Int(positionsCount)) + buffer.deallocate() + } + if let addresses { + let buffer = UnsafeMutablePointer(mutating: addresses) + buffer.deinitialize(count: Int(addressesCount)) + buffer.deallocate() + } +} + +/// C shim for `on_load_private_contact_scan_state_wallets_fn`: the ids of +/// the wallets the handler keeps scan state for, as one array of 32-byte ids +/// released by the free shim below. A stored id that is not 32 bytes cannot +/// cross: the load fails, as for an unreadable store. +private func loadPrivateContactScanStateWalletsCallback( + context: UnsafeMutableRawPointer?, + outWalletIds: UnsafeMutablePointer?>?, + outWalletIdsCount: UnsafeMutablePointer? +) -> Int32 { + guard let context, let outWalletIds, let outWalletIdsCount else { return -1 } + outWalletIds.pointee = nil + outWalletIdsCount.pointee = 0 + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + let ids: [Data] + do { + ids = try handler.loadPrivateContactScanStateWalletIds() + } catch { return -1 } + guard ids.allSatisfy({ $0.count == 32 }) else { return -1 } + guard !ids.isEmpty else { return 0 } + let buffer = UnsafeMutablePointer.allocate(capacity: ids.count) + for (index, id) in ids.enumerated() { + var tuple: FFIByteTuple32 = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + Swift.withUnsafeMutableBytes(of: &tuple) { _ = id.copyBytes(to: $0) } + (buffer + index).initialize(to: tuple) + } + outWalletIds.pointee = UnsafePointer(buffer) + outWalletIdsCount.pointee = UInt(ids.count) + return 0 +} + +/// C shim for `on_load_private_contact_scan_state_wallets_free_fn`. +private func loadPrivateContactScanStateWalletsFreeCallback( + context: UnsafeMutableRawPointer?, + walletIds: UnsafePointer?, walletIdsCount: UInt +) { + guard let walletIds else { return } + let buffer = UnsafeMutablePointer(mutating: walletIds) + buffer.deinitialize(count: Int(walletIdsCount)) + buffer.deallocate() +} + private func loadIdentityBalanceBlockTimeCallback( context: UnsafeMutableRawPointer?, walletId: UnsafePointer?, identityId: UnsafePointer?, outFound: UnsafeMutablePointer?, outBlockTime: UnsafeMutablePointer? diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index 6df07747d37..ee130585d2d 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -270,6 +270,58 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// 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 contact requests with that identity came or went privately, so a + /// public request to it, in reply or as a rotation, would publish the + /// relationship. Nothing was sent; accept or send it privately. + case errorPrivateContactRequestNeedsPrivateReply = 68 + /// The operation needs the shielded pool, and the native library was + /// built without shielded support. Nothing was sent; not retryable on + /// this build. + case errorShieldedBuildRequired = 69 + /// The network is proven at a protocol version below the one that + /// serves the request (for example the private contact request store + /// before protocol version 15), so the SDK did not send it. Expected on + /// such a network; it lifts when the network upgrades. An SDK pinned + /// below the version is `errorSdkPinnedBelowProtocolVersion` (75). + case errorProtocolVersionNotActive = 70 + /// A private contact request to that identity is pending: in flight, or + /// paid for and not yet read back from the store, or a private payment + /// the shielded store's journal keeps unresolved holds the pair. Nothing + /// new was paid. Do not submit it again: the entry read back by a private + /// sync, or the payment proven never to execute, frees it. An unfinished + /// private store read is `errorPrivateContactStoreNotRead` (74), not this. + case errorPrivateContactRequestPending = 71 + /// The wallet, not one contact, is held: its private payments are not + /// restored from the shielded store's journal, so no contact request, + /// public or private, is sent or accepted. The wallet was published + /// with no shielded store configured (configure it when the manager is + /// activated, before loading or creating wallets), it bound a shielded + /// account in an earlier process, its last restoration failed or waits + /// for a busy store, or the identity was loaded marking a private payment + /// that may be unresolved. Configuring the shielded store or binding the + /// wallet's shielded account restores them; a private sync does not. + case errorPrivateContactPaymentsNotRestored = 72 + /// The persister cannot keep a private payment's recovery state across + /// a restart (it does not declare the private contact request scan + /// state with atomic changesets), so a private send or reply is refused + /// before anything is sealed or paid. A configuration error, not + /// retryable as it is. + case errorPrivateContactRecoveryUnsupported = 73 + /// DashPay's private contact request store could not be read to its end + /// for the identity before a contact request or acceptance, public or + /// private, was decided. Nothing was reserved, sent or paid; calling + /// again continues the read. Not a pending request. + case errorPrivateContactStoreNotRead = 74 + /// The SDK is pinned below the protocol version the request needs, so it + /// did not send it, whatever the network runs. A network upgrade does not + /// lift it; only raising or removing the pin does. + case errorSdkPinnedBelowProtocolVersion = 75 + /// A public contact request to that identity was broadcast and may have + /// been delivered (its own send or accept reported + /// `errorTransactionBroadcastUnconfirmed`, 20), and no proof settled its + /// outcome yet. Nothing new was signed. Unconfirmed, not failed: do not + /// submit it again; a public contact request sync settles it. + case errorPublicContactRequestUnconfirmed = 76 /// 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. @@ -403,6 +455,24 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorAssetLockTooManyInputs case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_MISMATCH: self = .errorAssetLockRecipientMismatch + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_REQUEST_NEEDS_PRIVATE_REPLY: + self = .errorPrivateContactRequestNeedsPrivateReply + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_BUILD_REQUIRED: + self = .errorShieldedBuildRequired + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PROTOCOL_VERSION_NOT_ACTIVE: + self = .errorProtocolVersionNotActive + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_REQUEST_PENDING: + self = .errorPrivateContactRequestPending + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_PAYMENTS_NOT_RESTORED: + self = .errorPrivateContactPaymentsNotRestored + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_RECOVERY_UNSUPPORTED: + self = .errorPrivateContactRecoveryUnsupported + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_STORE_NOT_READ: + self = .errorPrivateContactStoreNotRead + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SDK_PINNED_BELOW_PROTOCOL_VERSION: + self = .errorSdkPinnedBelowProtocolVersion + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PUBLIC_CONTACT_REQUEST_UNCONFIRMED: + self = .errorPublicContactRequestUnconfirmed case PLATFORM_WALLET_FFI_RESULT_CODE_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -602,6 +672,77 @@ public enum PlatformWalletError: LocalizedError { /// `TrackedAssetLock.shieldedRecipientRaw43`). Locks tracked before the /// recipient was recorded carry none and accept the caller's. case assetLockRecipientMismatch(String) + /// The contact requests with that identity came or went privately + /// (protocol version 15): a public request to it, in reply or as a + /// rotation, would publish the relationship, so the public accept and + /// send refuse it and nothing was sent. Accept it with + /// `PlatformWalletManager.acceptContactRequestReplyingInKind` (which picks + /// the reply itself) or `acceptPrivateContactRequest`, or send with + /// `PlatformWalletManager.sendPrivateContactRequest`. + case privateContactRequestNeedsPrivateReply(String) + /// The operation needs the shielded pool, and the native library was + /// built without shielded support: today, accepting a contact request + /// that came privately with + /// `PlatformWalletManager.acceptContactRequestReplyingInKind`. Nothing + /// was sent; a public or adopted reply works on such a build. + case shieldedBuildRequired(String) + /// The network does not serve the request yet: it is proven at a protocol + /// version below the one that does, so the SDK did not send it. Expected + /// on such a network (for example the private contact request store before + /// protocol version 15); a host may stay quiet about it. An SDK pinned + /// below the version is `sdkPinnedBelowProtocolVersion` instead. + case protocolVersionNotActive(String) + /// A private contact request to that identity is pending (code 71): in + /// flight (another private send or reply reserved it), or paid for and + /// not yet read back from the store, or a private payment the shielded + /// store's journal keeps unresolved holds the pair. Nothing new was paid. + /// Pending, not failed: do not submit it again. A + /// `ManagedPlatformWallet.syncPrivateContactRequests` that reads the + /// entry back frees it, as does the payment proven never to execute; an + /// endpoint's refusal of the payment does not. + /// `ManagedPlatformWallet.privatePairHeld(senderId:recipientId:)` reads + /// whether the pair is still held. + case privateContactRequestPending(String) + /// The wallet's private payments are not restored from the shielded + /// store's journal, so its contact requests, public or private, sent or + /// accepted, are held (code 72). Nothing was signed or sent. + /// `PlatformWalletManager.configureShielded` (called when the manager is + /// activated, before loading or creating wallets, and again after a + /// failure) or binding the wallet's shielded account restores them; a + /// private sync does not. + /// `ManagedPlatformWallet.privateContactReadiness(identityId:)` reads + /// whether they are restored and whether the last restoration failed, + /// and `privatePaymentsRestoreFailure(identityId:)` why. + case privateContactPaymentsNotRestored(String) + /// The wallet's storage cannot keep a private payment's recovery state + /// across a restart (code 73): it does not declare the private contact + /// request scan state together with atomic changesets. A private send + /// or reply is refused before anything is sealed or paid. A + /// configuration error of the store, not something a retry fixes. + case privateContactRecoveryUnsupported(String) + /// DashPay's private contact request store could not be read to its end + /// for the identity before a contact request or acceptance, public or + /// private, was decided (code 74): a node behind the store already seen, + /// or keys that kept changing, stop the read. Nothing was reserved, sent + /// or paid; calling again continues the read. Not a pending request. + case privateContactStoreNotRead(String) + /// The SDK is pinned below the protocol version the request needs, so it + /// did not send it, whatever the network runs (code 75). Only raising or + /// removing the SDK's protocol version pin lifts it: a developer's + /// setting, not something the user or a network upgrade changes. + case sdkPinnedBelowProtocolVersion(String) + /// A public contact request to that identity was broadcast and may have + /// been delivered, and no proof settled its outcome yet (code 76): the + /// wallet holds the pair, keeping the signed transition, and refuses + /// every contact request or acceptance to it, public or private, with + /// nothing signed. The attempt that broadcast it reported + /// `transactionBroadcastUnconfirmed` (20). Unconfirmed, not failed: do not + /// submit it again. A public contact request sync (the DashPay sync) + /// settles it: the request proved on Platform is recorded as sent, and one + /// proved unable to write it frees the pair. + /// `ManagedPlatformWallet.publicContactRequestUnconfirmed(senderId:recipientId:)` + /// reads whether the pair is still held so. + case publicContactRequestUnconfirmed(String) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition never /// left the wallet (refused before anything was sent), so it cannot @@ -830,6 +971,12 @@ public enum PlatformWalletError: LocalizedError { .assetLockNotTracked(let m), .assetLockAlreadyConsumed(let m), .assetLockFundingMismatch(let m), .assetLockInsufficientFunds(let m), .assetLockTooManyInputs(let m), .assetLockRecipientMismatch(let m), + .privateContactRequestNeedsPrivateReply(let m), + .shieldedBuildRequired(let m), .protocolVersionNotActive(let m), + .privateContactRequestPending(let m), .privateContactPaymentsNotRestored(let m), + .privateContactRecoveryUnsupported(let m), + .privateContactStoreNotRead(let m), .sdkPinnedBelowProtocolVersion(let m), + .publicContactRequestUnconfirmed(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -949,6 +1096,24 @@ public enum PlatformWalletError: LocalizedError { case .errorAssetLockInsufficientFunds: self = .assetLockInsufficientFunds(detail) case .errorAssetLockTooManyInputs: self = .assetLockTooManyInputs(detail) case .errorAssetLockRecipientMismatch: self = .assetLockRecipientMismatch(detail) + case .errorPrivateContactRequestNeedsPrivateReply: + self = .privateContactRequestNeedsPrivateReply(detail) + case .errorShieldedBuildRequired: + self = .shieldedBuildRequired(detail) + case .errorProtocolVersionNotActive: + self = .protocolVersionNotActive(detail) + case .errorPrivateContactRequestPending: + self = .privateContactRequestPending(detail) + case .errorPrivateContactPaymentsNotRestored: + self = .privateContactPaymentsNotRestored(detail) + case .errorPrivateContactRecoveryUnsupported: + self = .privateContactRecoveryUnsupported(detail) + case .errorPrivateContactStoreNotRead: + self = .privateContactStoreNotRead(detail) + case .errorSdkPinnedBelowProtocolVersion: + self = .sdkPinnedBelowProtocolVersion(detail) + case .errorPublicContactRequestUnconfirmed: + self = .publicContactRequestUnconfirmed(detail) case .errorWalletAlreadyExists: self = .walletAlreadyExists(detail) case .errorShieldedBroadcastFailed: self = .shieldedBroadcastFailed(detail) case .errorShieldedBroadcastUnconfirmed: self = .shieldedBroadcastUnconfirmed(detail) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PrivateContactRequests.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PrivateContactRequests.swift new file mode 100644 index 00000000000..3ad72306ab0 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PrivateContactRequests.swift @@ -0,0 +1,521 @@ +import Foundation +import DashSDKFFI + +// MARK: - DashPay private contact requests (protocol version 15) +// +// A private contact request is sealed to one of the recipient's DashPay keys +// and paid for from the shielded pool, so nothing on chain names either side. +// It is signed by the same identity signer as a public request. The wallet +// records it as an ordinary `ContactRequest`; whether it came or went +// privately, and the contact's shielded address, are read with +// `ManagedIdentity.privateContact(contactId:)`. +// +// Accepting: `PlatformWalletManager.acceptContactRequestReplyingInKind` is +// the one accept a host calls; the wallet replies privately to a request that +// came privately, and with a document otherwise. The explicitly public +// `acceptContactRequest` and `sendContactRequest` throw +// `PlatformWalletError.privateContactRequestNeedsPrivateReply` for a contact +// whose requests came or went privately; send to it with +// `PlatformWalletManager.sendPrivateContactRequest` instead. + +/// How an identity and one contact exchanged private contact requests. Rust +/// reads it from the stored requests, so it holds across launches. The +/// contact's shielded address holds across launches too where the store +/// attests `PlatformWalletPersistenceCapabilities.privateContactRequestScanState` +/// (the SwiftData handler does); otherwise it comes back with the next +/// `ManagedPlatformWallet.syncPrivateContactRequests`. +public struct PrivateContactInfo: Sendable, Equatable { + /// The contact's request came privately, so accepting it replies + /// privately. + public let receivedPrivately: Bool + /// This identity's request to the contact went privately. + public let sentPrivately: Bool + /// The 43-byte Orchard address the contact asked to be paid at + /// privately; only when `receivedPrivately`, and only once a sync this + /// launch has read it. + public let shieldedAddress: Data? + + init(ffi: PrivateContactFFI) { + receivedPrivately = ffi.received_privately + sentPrivately = ffi.sent_privately + shieldedAddress = ffi.has_shielded_address + ? withUnsafeBytes(of: ffi.shielded_address) { Data($0) } + : nil + } +} + +/// What a contact request from one of the wallet's identities waits for, as +/// the wallet decides it (`platform_wallet_get_private_contact_readiness`), +/// so a host shows "restoring private payments" apart from "reading the +/// private store" and from a contact's pending request rather than inferring +/// them from the refusals it got. +public struct PrivateContactReadiness: Sendable, Equatable { + /// Whether the wallet's private payments are restored for the identity. + /// While false, its contact requests and acceptances, public or private, + /// are refused with `PlatformWalletError.privateContactPaymentsNotRestored` + /// (72) until the shielded store is configured or the wallet's shielded + /// account bound, or a contact request's own retry of a failed + /// restoration succeeds; no private sync lifts it. + public let privatePaymentsRestored: Bool + /// Whether a private sync read DashPay's private contact request store to + /// its end for the identity with its current keys. Every contact request + /// and acceptance reads it again from the cursor before it is decided, and + /// is refused with `PlatformWalletError.privateContactStoreNotRead` (74) + /// while that read cannot finish. + public let privateStoreRead: Bool + /// Whether a private contact request the identity paid for may still be + /// unresolved: the marker its private scan state stores, or a payment the + /// shielded store's journal keeps unresolved. One pair's hold is + /// `ManagedPlatformWallet.privatePairHeld(senderId:recipientId:)`. + public let unresolvedPrivatePayment: Bool + /// Whether the last restoration of the wallet's private payments failed + /// while `privatePaymentsRestored` is false: 72 then holds until one + /// succeeds, not only until one runs. + /// `ManagedPlatformWallet.privatePaymentsRestoreFailure(identityId:)` reads + /// why. + public let privatePaymentsRestoreFailed: Bool + + public init( + privatePaymentsRestored: Bool, + privateStoreRead: Bool, + unresolvedPrivatePayment: Bool, + privatePaymentsRestoreFailed: Bool = false + ) { + self.privatePaymentsRestored = privatePaymentsRestored + self.privateStoreRead = privateStoreRead + self.unresolvedPrivatePayment = unresolvedPrivatePayment + self.privatePaymentsRestoreFailed = privatePaymentsRestoreFailed + } + + init(ffi: PrivateContactReadinessFFI) { + self.init( + privatePaymentsRestored: ffi.private_payments_restored, + privateStoreRead: ffi.private_store_read, + unresolvedPrivatePayment: ffi.unresolved_private_payment, + privatePaymentsRestoreFailed: ffi.private_payments_restore_failed) + } +} + +/// What one pass over DashPay's private contact request store did. +public struct PrivateContactSyncResult: Sendable { + /// The requests the pass ingested, received and sent, including ones the + /// wallet already held. + public let requests: [ContactRequest] + /// The store pages read. + public let pagesRead: UInt32 + /// Entries that opened for one of the wallet's identities but were + /// refused. + public let rejectedCount: UInt32 + /// The store position the pass stopped at. + public let nextPosition: UInt64 + /// Whether the pass read to the store's last entry. When false, sync + /// again to read on. + public let complete: Bool + /// Identities whose ingest did not reach disk; the next pass reads their + /// entries again. + public let unpersistedIdentityCount: UInt32 +} + +extension ManagedIdentity { + /// How this identity and `contactId` exchanged private contact requests, + /// or `nil` when neither tracked request between them came or went + /// privately. + public func privateContact(contactId: Identifier) throws -> PrivateContactInfo? { + var ffi = PrivateContactFFI() + let result = contactId.withFFIBytes { idPtr in + PlatformWalletResult(managed_identity_get_private_contact(handle, idPtr, &ffi)) + } + if result.code == .notFound { + return nil + } + try result.throwIfError() + return PrivateContactInfo(ffi: ffi) + } +} + +extension ManagedPlatformWallet { + /// What a contact request from `identityId`, one of this wallet's + /// identities, waits for, as the wallet decides it. Not a pure read: a + /// journal record discharged since (a payment proven never to execute) is + /// applied first, briefly taking the wallet's write lock, as a send would + /// see it; then it reads live wallet state. Read it again after the + /// shielded store is configured or the wallet binds its shielded account + /// to see the restore. Throws `PlatformWalletError.identityNotFound` + /// (code 7) for an identity the wallet does not hold. + public func privateContactReadiness(identityId: Identifier) throws -> PrivateContactReadiness { + var ffi = PrivateContactReadinessFFI() + let handle = self.handle + let result = identityId.withFFIBytes { idPtr in + platform_wallet_get_private_contact_readiness(handle, idPtr, &ffi) + } + try result.check() + return PrivateContactReadiness(ffi: ffi) + } + + /// Whether a public contact request from `senderId`, one of this + /// wallet's identities, to `recipientId` was broadcast and may have been + /// delivered, with no proof settling its outcome yet. The send or accept + /// that broadcast it threw `PlatformWalletError.transactionBroadcastUnconfirmed` + /// (20); while it stands, Rust refuses every contact request or + /// acceptance to the recipient, public or private + /// (`PlatformWalletError.publicContactRequestUnconfirmed`, 76), so show the + /// pair as unconfirmed and offer neither. A public contact request sync + /// (the DashPay sync) settles it. Read it beside + /// `privatePairHeld(senderId:recipientId:)`, which reads a private request + /// pending. Throws `PlatformWalletError.identityNotFound` (code 7) for a + /// sender the wallet does not hold. + public func publicContactRequestUnconfirmed(senderId: Identifier, recipientId: Identifier) throws -> Bool { + var unconfirmed = false + let handle = self.handle + let result = senderId.withFFIBytes { senderPtr in + recipientId.withFFIBytes { recipientPtr in + platform_wallet_get_public_contact_request_unconfirmed( + handle, senderPtr, recipientPtr, &unconfirmed) + } + } + try result.check() + return unconfirmed + } + + /// Why the last restoration of this wallet's private payments failed, + /// while they are not restored for `identityId` and none succeeded since, + /// or `nil` when none failed (restored, or only not restored yet). What + /// `PrivateContactReadiness.privatePaymentsRestoreFailed` flags. Throws + /// `PlatformWalletError.identityNotFound` (code 7) for an identity the + /// wallet does not hold. + public func privatePaymentsRestoreFailure(identityId: Identifier) throws -> String? { + var reason: UnsafeMutablePointer? + let handle = self.handle + let result = identityId.withFFIBytes { idPtr in + platform_wallet_get_private_payments_restore_failure(handle, idPtr, &reason) + } + defer { platform_wallet_string_free(reason) } + try result.check() + return reason.map { String(cString: $0) } + } + + /// Whether a contact request from `senderId`, one of this wallet's + /// identities, to `recipientId`, public or private, is held for a + /// private one, as a send decides it: a private request to the recipient + /// is being paid for, or was paid for and is not yet read back from the + /// store, or a private payment the shielded store's journal keeps + /// unresolved holds the pair, also after the sender identity was removed + /// and added again. While it is, Rust refuses another private send or + /// reply to the recipient (`PlatformWalletError.privateContactRequestPending`) + /// and holds a public one, so show the pair as pending and offer + /// neither. A `syncPrivateContactRequests` that reads the entry back + /// frees it, as does the payment proven never to execute (its anchor + /// pruned, which the shielded sync judges); an endpoint's refusal of the + /// payment does not. Not a pure read: a journal record discharged since + /// is applied first, so a discharge reads as freed with no send or sync + /// in between. Throws `PlatformWalletError.identityNotFound` (code 7) + /// for a sender the wallet does not hold. + public func privatePairHeld(senderId: Identifier, recipientId: Identifier) throws -> Bool { + var held = false + let handle = self.handle + let result = senderId.withFFIBytes { senderPtr in + recipientId.withFFIBytes { recipientPtr in + platform_wallet_get_private_pair_held(handle, senderPtr, recipientPtr, &held) + } + } + try result.check() + return held + } + + /// Read DashPay's private contact request store for every identity of + /// this wallet, at most `maxPages` pages (the default reads to the end), + /// and ingest what it holds for them: requests to them, each sender + /// checked, and requests they sent, recovered from the store alone. + /// + /// The store is opened with keys that stay in the Keychain mnemonic + /// resolver Rust-side; each request's signature is checked against its + /// sender's keys. Where the store attests + /// `PlatformWalletPersistenceCapabilities.privateContactRequestScanState` + /// (the SwiftData handler does), each identity's read position is stored + /// with the requests read before it and restored at load, so a pass + /// after launch reads on from there; otherwise the first pass after + /// launch reads the store from its start. A request it ingests is stored + /// as having come privately, which holds across launches. + public func syncPrivateContactRequests( + maxPages: UInt32 = .max + ) async throws -> PrivateContactSyncResult { + let handle = self.handle + let coreSigner = MnemonicResolver() + return try await Task.detached(priority: .userInitiated) { + () -> PrivateContactSyncResult in + var array = ContactRequestHandleArray() + var report = PrivateContactSyncReportFFI() + // Keep the resolver alive across the synchronous FFI call: its + // vtable callback fires during it. + let result = withExtendedLifetime(coreSigner) { + platform_wallet_sync_private_contact_requests( + handle, + coreSigner.handle, + maxPages, + &array, + &report + ) + } + defer { platform_wallet_contact_request_handle_array_free(&array) } + try result.check() + var requests: [ContactRequest] = [] + if let handles = array.handles, array.count > 0 { + requests.reserveCapacity(Int(array.count)) + for i in 0.. ContactRequest { + let handle = try privateContactRequestManagerHandle( + walletId: walletId, + resolver: resolver, + shieldedAddress: shieldedAddress + ) + // Counted as the other native manager operations are, so a teardown + // waits for this call to return before it frees the manager. + try admitNativeOp("sendPrivateContactRequest") + defer { finishNativeOp() } + let signerHandle = signer.handle + let requestHandle: Handle = try await Task.detached(priority: .userInitiated) { + () -> Handle in + var outHandle: Handle = NULL_HANDLE + let resolverHandle = resolver.handle + // Guaranteed keepalive of the resolver and the signer across the + // FFI call, whose vtable callbacks fire during it: same rationale + // as `shieldedTransfer`. + try withExtendedLifetime((resolver, signer)) { + try walletId.withFFIBytes { widPtr in + try senderIdentityId.withFFIBytes { senderPtr in + try recipientIdentityId.withFFIBytes { recipientPtr in + try withOptionalCString(accountLabel) { labelPtr in + try withOptionalBytes(autoAcceptProof) { proofPtr, proofLen in + try withOptionalBytes(shieldedAddress) { addressPtr, _ in + try platform_wallet_manager_send_private_contact_request( + handle, + widPtr, + resolverHandle, + account, + senderPtr, + recipientPtr, + labelPtr, + proofPtr, + proofLen, + addressPtr, + signerHandle, + &outHandle + ).check() + } + } + } + } + } + } + } + return outHandle + }.value + return ContactRequest(handle: requestHandle) + } + + /// Accept a DashPay contact request that came privately, replying + /// privately and paying for the reply from `account`'s shielded notes. + /// `shieldedAddress` is the 43-byte Orchard address the contact may pay + /// us at privately. `signer` is the identity signer + /// `acceptContactRequest` takes; it signs the reply. It throws as + /// `sendPrivateContactRequest` does. + public func acceptPrivateContactRequest( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32 = 0, + request: ContactRequest, + shieldedAddress: Data? = nil, + signer: KeychainSigner + ) async throws -> EstablishedContact { + let handle = try privateContactRequestManagerHandle( + walletId: walletId, + resolver: resolver, + shieldedAddress: shieldedAddress + ) + // Counted as the other native manager operations are, so a teardown + // waits for this call to return before it frees the manager. + try admitNativeOp("acceptPrivateContactRequest") + defer { finishNativeOp() } + let requestHandle = request.handle + let signerHandle = signer.handle + let establishedHandle: Handle = try await Task.detached(priority: .userInitiated) { + () -> Handle in + var outHandle: Handle = NULL_HANDLE + let resolverHandle = resolver.handle + try withExtendedLifetime((resolver, signer, request)) { + try walletId.withFFIBytes { widPtr in + try withOptionalBytes(shieldedAddress) { addressPtr, _ in + try platform_wallet_manager_accept_private_contact_request( + handle, + widPtr, + resolverHandle, + account, + requestHandle, + addressPtr, + signerHandle, + &outHandle + ).check() + } + } + } + return outHandle + }.value + return EstablishedContact(handle: establishedHandle) + } + + /// Accept a DashPay contact request replying the way it came: privately, + /// paid from `account`'s shielded notes, when it came privately and no + /// reply exists yet; otherwise with a `contactRequest` document signed by + /// `signer`, or by adopting the reply already sent. Which reply a request + /// takes is the wallet's decision, so this is the accept a host calls. + /// `shieldedAddress` is the 43-byte Orchard address the contact may pay + /// us at privately; a public reply ignores it. A public or adopted reply + /// needs neither shielded support nor a mnemonic read for the payment. + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` (or + /// `.transactionBroadcastUnconfirmed`) when a private reply may already be + /// on chain, or `.privateContactRequestPending` when + /// the pair is held for one: do not accept again; `.privateContactStoreNotRead` + /// when the private store read every accept runs first did not finish + /// (nothing sent; calling again continues it); and + /// `PlatformWalletError.shieldedBuildRequired` when the request needs a + /// private reply and the native library has no shielded support. + public func acceptContactRequestReplyingInKind( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32 = 0, + request: ContactRequest, + shieldedAddress: Data? = nil, + signer: KeychainSigner + ) async throws -> EstablishedContact { + let handle = try privateContactRequestManagerHandle( + walletId: walletId, + resolver: resolver, + shieldedAddress: shieldedAddress + ) + // Counted as the other native manager operations are, so a teardown + // waits for this call to return before it frees the manager. + try admitNativeOp("acceptContactRequestReplyingInKind") + defer { finishNativeOp() } + let requestHandle = request.handle + let signerHandle = signer.handle + let establishedHandle: Handle = try await Task.detached(priority: .userInitiated) { + () -> Handle in + var outHandle: Handle = NULL_HANDLE + let resolverHandle = resolver.handle + // Keep the resolver, the signer and the request alive across the + // FFI call, whose vtable callbacks fire during it. + try withExtendedLifetime((resolver, signer, request)) { + try walletId.withFFIBytes { widPtr in + try withOptionalBytes(shieldedAddress) { addressPtr, _ in + try platform_wallet_manager_accept_contact_request_replying_in_kind( + handle, + widPtr, + resolverHandle, + account, + requestHandle, + addressPtr, + signerHandle, + &outHandle + ).check() + } + } + } + return outHandle + }.value + return EstablishedContact(handle: establishedHandle) + } + + /// The manager handle of a private contact request call, refused before + /// any FFI call when the arguments cannot be passed: an unconfigured + /// manager, a wallet id that is not 32 bytes, a shielded address that is + /// not the 43 bytes Rust reads, or a resolver without a handle. + private func privateContactRequestManagerHandle( + walletId: Data, + resolver: MnemonicResolver, + shieldedAddress: Data? + ) throws -> Handle { + guard isConfigured, handle != NULL_HANDLE else { + throw PlatformWalletError.invalidHandle("PlatformWalletManager not configured") + } + guard walletId.count == 32 else { + throw PlatformWalletError.invalidParameter("walletId must be exactly 32 bytes") + } + if let shieldedAddress, shieldedAddress.count != 43 { + throw PlatformWalletError.invalidParameter( + "shieldedAddress must be exactly 43 raw Orchard bytes" + ) + } + guard resolver.handle != nil else { + throw PlatformWalletError.invalidParameter("MnemonicResolver has no handle") + } + return handle + } +} + +/// Run `body` with `text` as a C string, or with null when `text` is nil. +private func withOptionalCString( + _ text: String?, + _ body: (UnsafePointer?) throws -> R +) rethrows -> R { + guard let text else { return try body(nil) } + return try text.withCString { try body($0) } +} + +/// Run `body` with a pointer to `data` and its length, or with `(nil, 0)` +/// when `data` is nil or empty. +private func withOptionalBytes( + _ data: Data?, + _ body: (UnsafePointer?, UInt) throws -> R +) rethrows -> R { + guard let data, !data.isEmpty else { return try body(nil, 0) } + return try data.withUnsafeBytes { raw in + try body(raw.bindMemory(to: UInt8.self).baseAddress, UInt(data.count)) + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift index 057fca7a0dd..d76f2fe1745 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift @@ -1153,7 +1153,7 @@ class ShieldedService: ObservableObject { /// store via `SubwalletId`, so multiple wallets cohabiting /// the same SQLite file no longer leak notes across each /// other. (See `wallet/shielded/store.rs` for the trait.) - private static func dbPath(for network: Network) -> String { + static func dbPath(for network: Network) -> String { let docs = FileManager.default .urls(for: .documentDirectory, in: .userDomainMask) .first! diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift index 8304a48e2d1..0ee1ea8c137 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift @@ -829,15 +829,16 @@ class SendViewModel: ObservableObject { + "the recipient's next shielded sync." } - } catch PlatformWalletError.shieldedSpendUnconfirmed { + } catch let unconfirmed as PlatformWalletError where SendViewModel.mayHaveGoneThrough(unconfirmed) { // The shielded operation (shield / unshield / transfer / withdraw) // may have reached a node and its result is not proved (a node's - // refusal or verdict included), so it may already be on chain. Rust - // intentionally KEEPS any spent notes' reservations, so this must - // NOT be presented as a retryable failure: a retry signs a second - // transition. Surface it through the - // non-error (success) path so the UI doesn't invite a retry; the - // next shielded sync reconciles the outcome. + // refusal or verdict included, code 18), or the SDK could not + // confirm a transition it may have accepted (code 20), so it may + // already be on chain. Rust intentionally KEEPS any spent notes' + // reservations, so this must NOT be presented as a retryable + // failure: a retry signs a second transition. Surface it through + // the non-error (success) path so the UI doesn't invite a retry; + // the next shielded sync reconciles the outcome. successMessage = "Transaction may have gone through — waiting for " + "the next shielded sync to confirm. Do not retry." } catch { @@ -845,6 +846,17 @@ class SendViewModel: ObservableObject { } } + /// Whether a shielded operation's error means it may already be on + /// chain, so no retry is offered: a spend whose result is not proved + /// (18) or a state transition the SDK could not confirm after it may + /// have been accepted (20). + nonisolated static func mayHaveGoneThrough(_ error: PlatformWalletError) -> Bool { + switch error { + case .shieldedSpendUnconfirmed, .transactionBroadcastUnconfirmed: return true + default: return false + } + } + /// Apply the authoritative Core broadcast outcome to the send UI. Kept as /// a small pure state transition so rejected/unknown can be regression /// tested without constructing a live wallet or transaction. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/AddContactView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/AddContactView.swift index 7a0f020ff9b..13c981ddf13 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/AddContactView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/AddContactView.swift @@ -18,6 +18,12 @@ struct AddContactView: View { let onSent: (Identifier, String?) -> Void @EnvironmentObject var walletManager: PlatformWalletManager + /// Observed for its bind: binding the shielded account restores the + /// wallet's private payments, so the readiness is read again then. + @EnvironmentObject var shieldedService: ShieldedService + /// Read for why the shielded store could not be opened, which keeps the + /// wallet's private payments waiting. + @EnvironmentObject var walletManagerStore: WalletManagerStore @Environment(\.dismiss) private var dismiss @Environment(\.modelContext) private var modelContext @@ -50,9 +56,43 @@ struct AddContactView: View { /// as the contact's "Their account" hint. @State private var accountLabel = "" + /// Send a private contact request (protocol version 15): paid from the + /// wallet's shielded balance, so nothing on chain names either side. + @State private var sendPrivately = false + @State private var isSending = false @State private var errorMessage: String? + /// Set when a private send or reply may have gone through (its result + /// could not be confirmed): the view only offers to close, never to + /// submit again, as `SendTransactionView` does for an unconfirmed spend. + @State private var unconfirmedNotice: String? + + /// Whether the wallet holds the pair with the resolved recipient for a + /// private request, as a send decides it (in flight, paid and not yet + /// read back, or kept by the shielded store's journal until the payment + /// is proven never to land), or for a public request awaiting its + /// outcome (`contactRequestHolds`). While it does, Send is off and the + /// footer offers the sync that settles it: the private one, which reads a + /// landed request back, or the DashPay one, which settles a public + /// request. Read from the wallet, so reopening this sheet keeps it. A + /// failed read keeps Send off until a read succeeds. + @State private var recipientPending = PrivateRepliesPendingSnapshot() + + /// Why the shielded store could not be opened, as last read with the + /// pending state; nil when it is open. + @State private var shieldedStoreFailure: String? + + /// The automatic refreshes made since the wallet's private payments were + /// last read restored (`PrivatePaymentsRecovery.recheckDelay`). + @State private var readinessRechecks = 0 + + /// A private sync the footer started is running. + @State private var isSyncingPrivate = false + + /// A DashPay sync the footer started is running. + @State private var isCheckingPublic = false + /// Send-collision flow. @State private var showCollisionAlert = false @State private var collisionRecipient: Identifier? @@ -90,6 +130,19 @@ struct AddContactView: View { resolvedRecipient != nil && resolvedRecipient != identity.identityId && !isSending + && unconfirmedNotice == nil + && resolvedRecipient.map(recipientPending.allowsSubmission(to:)) == true + } + + /// Whether the footer shows the recipient's pending state: the wallet's + /// private payments are being restored, a request to them awaits its + /// outcome, a private request to them is pending, or the wallet could + /// not be read. + private var recipientBlocked: Bool { + guard let recipient = resolvedRecipient else { return false } + return recipientPending.isRestoringPrivatePayments + || recipientPending.isAwaitingOutcome(recipient) + || recipientPending.isPending(recipient) || recipientPending.isUnavailable } var body: some View { @@ -114,6 +167,7 @@ struct AddContactView: View { if let recipient = resolvedRecipient { previewSection(recipient: recipient) accountLabelSection + sendPrivatelySection sendSection } @@ -127,6 +181,30 @@ struct AddContactView: View { } } .navigationTitle("Add Contact") + .task(id: resolvedRecipient) { reloadRecipientPending() } + // While the wallet's private payments stay unrestored, refresh + // again after a pause: a restoration the wallet deferred behind a + // busy store completes later and changes nothing this view + // observes. + .task(id: readinessRechecks) { + guard readinessRechecks > 0 else { return } + let due = await PrivatePaymentsRecovery.waitForRecheck( + after: recipientPending.readiness, attempt: readinessRechecks - 1, + sleep: { try await Task.sleep(for: $0) }) + if due { reloadRecipientPending() } + } + // A deferred restoration runs once the shielded scan holding the store + // ends: refresh then too, ahead of the timer. + .onChange(of: shieldedService.isSyncing) { _, syncing in + if !syncing { reloadRecipientPending() } + } + .onChange(of: shieldedService.isBound) { _, _ in reloadRecipientPending() } + // A DashPay sync settles a public request awaiting its outcome: + // read the recipient's holds again when one ends, the background + // pass included. + .onChange(of: walletManager.dashPaySyncIsSyncing) { _, syncing in + if !syncing { reloadRecipientPending() } + } .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarLeading) { @@ -140,14 +218,24 @@ struct AddContactView: View { isPresented: $showCollisionAlert, presenting: collisionRecipient ) { recipient in - Button("Accept") { + Button(CollisionAccept.of(sendPrivately: sendPrivately).buttonTitle) { acceptIncoming(from: recipient) } Button("Continue anyway") { send(to: recipient) } } message: { _ in - Text("This person already sent you a request — accept it instead?") + Text(CollisionAccept.of(sendPrivately: sendPrivately).message) + } + .alert( + "Submitted", + isPresented: .constant(unconfirmedNotice != nil) + ) { + Button("Done") { dismiss() } + } message: { + if let unconfirmedNotice { + Text(unconfirmedNotice) + } } } } @@ -357,6 +445,15 @@ struct AddContactView: View { } } + private var sendPrivatelySection: some View { + Section { + Toggle("Send privately", isOn: $sendPrivately) + .accessibilityIdentifier("dashpay.addContact.sendPrivately") + } footer: { + Text("Paid from this wallet's shielded balance, so nothing on chain names either of you.") + } + } + private var sendSection: some View { Section { Button { @@ -374,6 +471,110 @@ struct AddContactView: View { } .disabled(!canSend) .accessibilityIdentifier("dashpay.addContact.send") + } footer: { + if let recipient = resolvedRecipient, recipientBlocked { + VStack(alignment: .leading, spacing: 6) { + Text(ContactRequestSubmissionOutcome.rowMessage( + pending: recipientPending.isPending(recipient), + awaitingOutcome: recipientPending.isAwaitingOutcome(recipient), + restoring: recipientPending.isRestoringPrivatePayments, + restoreFailure: recipientPending.restoreFailure, + shieldedStoreFailure: shieldedStoreFailure, + unavailable: recipientPending.isUnavailable, + error: nil + ) ?? "") + .accessibilityIdentifier("dashpay.addContact.pending") + // A DashPay sync settles a public request awaiting its + // outcome, and a private sync a pending private request; + // neither restores private payments, so neither is offered + // for that. + if recipientPending.isRestoringPrivatePayments { + EmptyView() + } else if recipientPending.isAwaitingOutcome(recipient) { + Button { + checkPublicRequest() + } label: { + if isCheckingPublic { + ProgressView() + } else { + Text("Check again") + } + } + .disabled(isCheckingPublic) + .accessibilityIdentifier("dashpay.addContact.checkPublic") + } else { + Button { + syncPrivateRequests() + } label: { + if isSyncingPrivate { + ProgressView() + } else { + Text("Sync private requests") + } + } + .disabled(isSyncingPrivate) + .accessibilityIdentifier("dashpay.addContact.syncPrivate") + } + } + } + } + } + + /// Re-read from the wallet its readiness (`PrivatePaymentsRecovery.refresh`: + /// the wallet is asked to retry a restoration first when its payments are + /// not restored, and the readiness shown is read after that), then + /// whether it holds the pair with the resolved recipient for a private + /// request or for a public request awaiting its outcome, and keep + /// refreshing on a timer while the payments stay unrestored. + private func reloadRecipientPending() { + let contactIds = resolvedRecipient.map { [$0] } ?? [] + let wallet = try? requireWallet() + let identityId = identity.identityId + let refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: recipientPending.readiness, + storeFailure: walletManagerStore.shieldedStoreFailure(of: walletManager), + readReadiness: { privateContactReadiness(wallet: wallet, identityId: identityId) }, + configureAgain: { walletManagerStore.configureShieldedAgain(walletManager) } + ) + recipientPending.recordReadiness(refreshed.readiness, restoreFailure: refreshed.restoreFailure) + shieldedStoreFailure = refreshed.storeFailure + recipientPending.record( + contactRequestHolds(wallet: wallet, identityId: identityId, contactIds: contactIds), + for: contactIds + ) + if PrivatePaymentsRecovery.recheckDelay(after: recipientPending.readiness, attempt: readinessRechecks) != nil { + readinessRechecks += 1 + } else if recipientPending.readiness?.privatePaymentsRestored == true { + readinessRechecks = 0 + } + } + + /// Read the private store, which settles a pending private request, then + /// re-read the recipient's pending state: Send comes back once nothing + /// is pending, for the user to try again. + private func syncPrivateRequests() { + isSyncingPrivate = true + Task { @MainActor in + defer { isSyncingPrivate = false } + if let wallet = try? requireWallet() { + if let notice = await syncPrivateContactRequests(wallet) { + errorMessage = notice + } + } + reloadRecipientPending() + } + } + + /// Run a DashPay sync, which settles a public request awaiting its + /// outcome first (attaching to one already running), then re-read the + /// recipient's holds: Send comes back once the wallet frees the pair, + /// and a request found is recorded as sent. + private func checkPublicRequest() { + isCheckingPublic = true + Task { @MainActor in + defer { isCheckingPublic = false } + await attachOrStartSync(walletManager) + reloadRecipientPending() } } @@ -451,19 +652,60 @@ struct AddContactView: View { defer { isSending = false } do { let wallet = try requireWallet() - let signer = KeychainSigner(modelContainer: modelContext.container) let label = accountLabel.trimmingCharacters(in: .whitespacesAndNewlines) - _ = try await wallet.sendContactRequest( - senderIdentityId: identity.identityId, - recipientIdentityId: recipient, - accountLabel: label.isEmpty ? nil : label, - signer: signer - ) + // Both sends sign with the same identity signer. + let signer = KeychainSigner(modelContainer: modelContext.container) + if sendPrivately { + _ = try await walletManager.sendPrivateContactRequest( + walletId: wallet.walletId, + resolver: MnemonicResolver(), + senderIdentityId: identity.identityId, + recipientIdentityId: recipient, + accountLabel: label.isEmpty ? nil : label, + signer: signer + ) + } else { + _ = try await wallet.sendContactRequest( + senderIdentityId: identity.identityId, + recipientIdentityId: recipient, + accountLabel: label.isEmpty ? nil : label, + signer: signer + ) + } onSent(recipient, mode == .dpns ? selectedResult?.fullName : nil) kickDashPaySync(walletManager) dismiss() } catch { - errorMessage = error.localizedDescription + let outcome = ContactRequestSubmissionOutcome.of(error) + recipientPending.recordOutcome(outcome, for: recipient) + switch outcome { + case .mayHaveGoneThrough: + // Pending, not failed: the next sync settles it. + onSent(recipient, mode == .dpns ? selectedResult?.fullName : nil) + kickDashPaySync(walletManager) + unconfirmedNotice = ContactRequestSubmissionOutcome.mayHaveGoneThroughMessage + case .publicRequestUnconfirmed: + // Nothing was signed: an earlier public request to the + // recipient awaits its outcome. The footer shows it being + // checked, with the DashPay sync, never a retry. + kickDashPaySync(walletManager) + case .privateRequestPending: + // Nothing was sent: the wallet holds the pair. The footer + // shows it as pending, with the private sync, until the + // per-contact read says it is free. + break + case .privatePaymentsNotRestored: + // Nothing was sent: the footer shows the wallet setting up + // its private payments until its readiness says restored. + break + case .privateStoreNotRead: + // Nothing was sent and nothing is pending: Send stays on, + // and sending again continues the read. + errorMessage = ContactRequestSubmissionOutcome.privateStoreNotReadMessage + case .failed(let message): + errorMessage = message + } + reloadRecipientPending() } } } @@ -472,6 +714,11 @@ struct AddContactView: View { /// `ContactRequest` and accept it — establishing the contact /// directly instead of sending a redundant request. private func acceptIncoming(from recipient: Identifier) { + // A private request to this contact may be pending in the wallet. + guard recipientPending.allowsSubmission(to: recipient) else { return } + // "Send privately" is the user's choice of a private request, so it + // holds for the accept too (`CollisionAccept`). + let accept = CollisionAccept.of(sendPrivately: sendPrivately) isSending = true errorMessage = nil Task { @MainActor in @@ -486,11 +733,50 @@ struct AddContactView: View { return } let signer = KeychainSigner(modelContainer: modelContext.container) - _ = try await wallet.acceptContactRequest(request, signer: signer) + switch accept { + case .privateReply: + // A private reply, paid from the shielded balance, even to + // a request that came publicly. + _ = try await walletManager.acceptPrivateContactRequest( + walletId: wallet.walletId, + resolver: MnemonicResolver(), + request: request, + signer: signer + ) + case .replyInKind: + // The wallet replies the way the request came: privately + // (paid from the shielded balance) or with a document. + _ = try await walletManager.acceptContactRequestReplyingInKind( + walletId: wallet.walletId, + resolver: MnemonicResolver(), + request: request, + signer: signer + ) + } kickDashPaySync(walletManager) dismiss() } catch { - errorMessage = "Accept failed: \(error.localizedDescription)" + let outcome = ContactRequestSubmissionOutcome.of(error) + recipientPending.recordOutcome(outcome, for: recipient) + switch outcome { + case .mayHaveGoneThrough: + kickDashPaySync(walletManager) + unconfirmedNotice = ContactRequestSubmissionOutcome.mayHaveGoneThroughMessage + case .publicRequestUnconfirmed: + // Nothing was signed: the footer shows the pair being + // checked, with the DashPay sync, never a retry. + kickDashPaySync(walletManager) + case .privateRequestPending: + // Nothing was sent: the footer offers the private sync. + break + case .privatePaymentsNotRestored: + break + case .privateStoreNotRead: + errorMessage = ContactRequestSubmissionOutcome.privateStoreNotReadMessage + case .failed(let message): + errorMessage = "Accept failed: \(message)" + } + reloadRecipientPending() } } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 6953c89e694..a8ccb49c5ba 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -270,9 +270,18 @@ struct ClaimInvitationSheet: View { dismiss() } catch { // The identity is already registered; a failed contact request - // is non-fatal and re-sendable. Surface it but keep the sheet so - // the user sees the outcome. - errorMessage = "Identity claimed, but the contact request failed: \(error.localizedDescription)" + // is non-fatal. Surface it but keep the sheet so the user sees + // the outcome. One that may have gone through (18, 20), or that + // the wallet refused while an earlier one awaits its outcome + // (76), is not a failure: the sync settles it. + switch ContactRequestSubmissionOutcome.of(error) { + case .mayHaveGoneThrough, .publicRequestUnconfirmed: + kickDashPaySync(walletManager) + errorMessage = "Identity claimed. " + + ContactRequestSubmissionOutcome.publicRequestUnconfirmedMessage + default: + errorMessage = "Identity claimed, but the contact request failed: \(error.localizedDescription)" + } } } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestOutcomes.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestOutcomes.swift new file mode 100644 index 00000000000..a1da0f89951 --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestOutcomes.swift @@ -0,0 +1,498 @@ +import Foundation +import SwiftDashSDK + +/// How a contact request send or accept that threw ended, for the DashPay +/// views. Follows `SendViewModel`: a shielded spend whose result could not be +/// confirmed (code 18) may already be on chain (Rust keeps its notes +/// reserved), and so may a state transition the SDK could not confirm after +/// it may have been accepted (code 20), so the view keeps either pending and +/// never offers a fresh submission; the next sync settles it. For a public +/// request the wallet holds the pair itself after a 20, the signed transition +/// kept, until a public contact request sync settles it, and refuses every +/// later request or accept to it with code 76: the view shows "may have gone +/// through; it is being checked" until the wallet's per-contact read says +/// settled. A pair Rust reports as held for a +/// private request (code 71), which a public send or accept can also meet, +/// sent nothing new: the view shows it as pending until the wallet's +/// per-contact read says the pair is free. Unrestored private payments +/// (code 72) hold the wallet, not one contact: the view shows "setting up" +/// until the wallet's readiness reads restored, or why the last restoration +/// failed; no private sync lifts it. A private store read that did not +/// finish (code 74) sent nothing and is not pending: the user may try again. +/// Every other error is an ordinary failure the user may retry; a storage +/// backend that cannot protect private payments (73) and an SDK pinned below +/// the protocol version (75) are shown as configuration problems. +enum ContactRequestSubmissionOutcome: Equatable { + /// The private send or reply may have gone through: do not submit again. + case mayHaveGoneThrough + /// The wallet holds the pair for a private request; nothing was sent. + case privateRequestPending + /// The wallet holds the pair for a public request whose outcome is not + /// proved yet (code 76); nothing was signed. A public contact request + /// sync settles it. + case publicRequestUnconfirmed + /// The wallet's private payments are not restored yet; nothing was sent. + /// Restoring them, not a private sync, lifts it. + case privatePaymentsNotRestored + /// The private store read every contact request runs first did not + /// finish; nothing was sent, and trying again continues it. + case privateStoreNotRead + /// It failed; the message is the error's. + case failed(String) + + static let mayHaveGoneThroughMessage = "This may have gone through. It shows up " + + "after the next sync confirms it; do not submit it again." + + /// A public request or accept that may have gone through, as the + /// wallet holds it until a sync settles its outcome. + static let publicRequestUnconfirmedMessage = "This request may have gone through; " + + "it is being checked. The next sync settles it." + + static let privateRequestPendingMessage = "A private request to this contact is " + + "pending. It clears once the request is read back from the private store, " + + "or once its payment can no longer land, which can take a while. Sync " + + "private requests to check." + + static let settingUpPrivatePaymentsMessage = "Setting up this wallet's private " + + "payments. Contact requests wait until it finishes." + + /// The wallet's last restoration of its private payments failed. + static func restoreFailedMessage(_ reason: String) -> String { + "Restoring this wallet's private payments failed: \(reason). Contact requests " + + "wait until a restore succeeds." + } + + /// The app could not open the shielded store, which restores the + /// wallet's private payments. + static func shieldedStoreFailedMessage(_ reason: String) -> String { + "The shielded store could not be opened: \(reason). Contact requests wait " + + "until it opens." + } + + static let privateStoreNotReadMessage = "Still reading private contact requests. " + + "Nothing was sent; try again in a moment." + + /// Code 73 is a configuration error of the app's storage, which both + /// declares what a private payment needs; shown as such. + static let recoveryUnsupportedMessage = "This storage backend can't protect " + + "private payments, so private contact requests are off." + + /// Code 75 is the developer's setting: only raising or removing the SDK's + /// protocol version pin lifts it. + static let sdkPinnedMessage = "This build's SDK is pinned below the protocol " + + "version private contact requests need. Raise or remove the SDK's protocol " + + "version pin." + + /// The notice shown while the wallet's private payments are not + /// restored: why opening the shielded store failed, why the last + /// restoration failed, or that they are being set up. + static func restoringMessage(restoreFailure: String?, shieldedStoreFailure: String?) -> String { + if let shieldedStoreFailure { return shieldedStoreFailedMessage(shieldedStoreFailure) } + if let restoreFailure { return restoreFailedMessage(restoreFailure) } + return settingUpPrivatePaymentsMessage + } + + /// The message a request row shows: the restoring notice while the + /// wallet's private payments are not restored, the being-checked notice + /// while a request to the contact awaits its outcome, the pending notice + /// while the wallet holds the pair for a private request, the + /// unavailable notice while the wallet could not be read, and whatever + /// error an earlier attempt left otherwise. + static func rowMessage( + pending: Bool, + awaitingOutcome: Bool = false, + restoring: Bool = false, + restoreFailure: String? = nil, + shieldedStoreFailure: String? = nil, + unavailable: Bool = false, + error: String? + ) -> String? { + if restoring { + return restoringMessage( + restoreFailure: restoreFailure, shieldedStoreFailure: shieldedStoreFailure) + } + if awaitingOutcome { return publicRequestUnconfirmedMessage } + if pending { return privateRequestPendingMessage } + if unavailable { return PrivateRepliesPendingSnapshot.unavailableMessage } + return error + } + + static func of(_ error: Error) -> ContactRequestSubmissionOutcome { + if let walletError = error as? PlatformWalletError { + switch walletError { + case .shieldedSpendUnconfirmed, .transactionBroadcastUnconfirmed: + return .mayHaveGoneThrough + case .privateContactRequestPending: + return .privateRequestPending + case .publicContactRequestUnconfirmed: + return .publicRequestUnconfirmed + case .privateContactPaymentsNotRestored: + return .privatePaymentsNotRestored + case .privateContactStoreNotRead: + return .privateStoreNotRead + case .privateContactRecoveryUnsupported: + return .failed(recoveryUnsupportedMessage) + case .sdkPinnedBelowProtocolVersion: + return .failed(sdkPinnedMessage) + default: + break + } + } + return .failed(error.localizedDescription) + } +} + +/// Which contacts the wallet holds a pair with for a private request, and +/// which for a public request awaiting its outcome, as the views last read it +/// (`contactRequestHolds`: per contact, `ManagedPlatformWallet.privatePairHeld`, +/// which answers as a send decides it, and +/// `ManagedPlatformWallet.publicContactRequestUnconfirmed`). While either +/// holds a pair, Rust refuses another send or reply +/// to that contact, so the views turn off what would submit one (Accept, +/// Ignore, Send). A failed read is not "nothing pending": the last +/// successful snapshot stays, and those controls stay off for every contact +/// until a read covering it succeeds. +/// +/// A send or accept Rust refused as pending (code 71) marks the contact +/// pending at once; the next successful read covering it decides, as it +/// reads what the refusal read. Controls for a pair re-enable only when that +/// read says it is free: a payment that will never land frees it only once +/// the wallet proves so, which the read shows. So does a send or accept that +/// may have gone through (18 or 20), or was refused as awaiting a public +/// request's outcome (76): the contact shows "being checked" at once, and a +/// read decides it the same way, so a reload whose sync did not settle the +/// wallet's hold keeps it so. A read always covers both holds: a read of the +/// private hold alone would offer a public request awaiting its outcome +/// again. +/// +/// Whether the wallet's private payments are restored is the wallet's +/// readiness (`ManagedPlatformWallet.privateContactReadiness`), not +/// anything the views conclude: a code 72 refusal, or a readiness read that +/// says not restored, shows "setting up" (or why the last restoration +/// failed) for every contact, and only a readiness read that says restored +/// lifts it. A private sync changes neither on its own. +struct PrivateRepliesPendingSnapshot: Equatable { + static let unavailableMessage = "Could not read whether a private request to " + + "this contact is pending. Sync private requests to check again." + + /// The contacts the last successful read found held for a private + /// request. + private(set) var pending: Set = [] + /// The contacts the last successful read covered. + private(set) var covered: Set = [] + /// False after a failed read, until a read succeeds. + private(set) var available = true + /// Contacts a send or accept was refused for as pending (code 71) since + /// the last successful read covering them. + private(set) var refused: Set = [] + /// The contacts the last successful read found held for a public + /// request awaiting its outcome. + private(set) var publicUnconfirmed: Set = [] + /// Contacts a send or accept may have gone through to (18, 20), or was + /// refused for as awaiting a public request's outcome (76), since the + /// last successful read covering them. + private(set) var awaitingOutcome: Set = [] + /// The wallet's readiness for the identity, as last read; nil until a + /// read succeeds. + private(set) var readiness: PrivateContactReadiness? + /// Why the last restoration failed, as last read with the readiness; + /// nil when none failed or the reason could not be read. + private(set) var restoreFailure: String? + /// Set by a code 72 refusal; cleared only by a readiness read that says + /// the private payments are restored. + private(set) var restoringRefused = false + + /// Record a read of both holds for `contactIds` (`contactRequestHolds`), + /// or nil when it failed. A successful read decides each contact it + /// covered, a refusal or a submission that may have gone through + /// included. + mutating func record(_ read: ContactRequestHolds?, for contactIds: [Data]) { + guard let read else { + available = false + return + } + pending = read.privatelyHeld + publicUnconfirmed = read.publicUnconfirmed + covered = Set(contactIds) + refused.subtract(contactIds) + awaitingOutcome.subtract(contactIds) + available = true + } + + /// Record how a send or accept to `contactId` that threw ended: a 71 + /// refusal marks it pending and a 72 refusal holds every contact, as + /// `recordRefusal(of:)` and `recordRestoringRefusal()` do; one that may + /// have gone through, or a 76 refusal, marks it awaiting its outcome. + /// Nothing else changes a hold. + mutating func recordOutcome(_ outcome: ContactRequestSubmissionOutcome, for contactId: Data) { + switch outcome { + case .privateRequestPending: + recordRefusal(of: contactId) + case .mayHaveGoneThrough, .publicRequestUnconfirmed: + awaitingOutcome.insert(contactId) + case .privatePaymentsNotRestored: + recordRestoringRefusal() + case .privateStoreNotRead, .failed: + break + } + } + + /// Record that a send or accept to `contactId` was refused as pending + /// (code 71). + mutating func recordRefusal(of contactId: Data) { + refused.insert(contactId) + } + + /// Record a send or accept refused because the wallet's private payments + /// are not restored (code 72). + mutating func recordRestoringRefusal() { + restoringRefused = true + } + + /// Record a read of the wallet's readiness and, when it flags a failed + /// restoration, the reason read with it; a nil readiness (the read + /// failed) keeps what the last read said. A readiness that says restored + /// lifts a code 72 refusal and its failure. + mutating func recordReadiness(_ read: PrivateContactReadiness?, restoreFailure: String? = nil) { + guard let read else { return } + readiness = read + self.restoreFailure = read.privatePaymentsRestoreFailed ? restoreFailure : nil + if read.privatePaymentsRestored { + restoringRefused = false + } + } + + /// Whether the wallet's private payments are being restored: a send or + /// accept was refused with code 72, or the last readiness read says they + /// are not restored. Every contact waits while they are. + var isRestoringPrivatePayments: Bool { + restoringRefused || readiness?.privatePaymentsRestored == false + } + + /// Whether `contactId` is pending: the last successful read found the + /// pair held, or a send or accept to it was refused as pending since. + func isPending(_ contactId: Data) -> Bool { + pending.contains(contactId) || refused.contains(contactId) + } + + /// Whether a request to `contactId` awaits its outcome: the last + /// successful read found the pair held for a public request awaiting + /// it, or a send or accept to the contact may have gone through, or was + /// refused so (76), since. + func isAwaitingOutcome(_ contactId: Data) -> Bool { + publicUnconfirmed.contains(contactId) || awaitingOutcome.contains(contactId) + } + + /// Whether the last read failed. + var isUnavailable: Bool { !available } + + /// Whether a send or reply to `contactId` may be offered: a successful + /// read covered it and found the pair free of both holds. + func allowsSubmission(to contactId: Data) -> Bool { + available && covered.contains(contactId) && !isPending(contactId) + && !isAwaitingOutcome(contactId) && !isRestoringPrivatePayments + } +} + +/// One read of the wallet's two per-contact holds. +struct ContactRequestHolds: Equatable { + /// The contacts whose pair the wallet holds for a private request. + var privatelyHeld: Set = [] + /// The contacts whose pair the wallet holds for a public request + /// awaiting its outcome. + var publicUnconfirmed: Set = [] +} + +/// Read the wallet's two holds for each of `contactIds`: whether the pair is +/// held for a private request (`privatePairHeld`) and whether for a public +/// request awaiting its outcome (`publicUnconfirmed`). Empty when the wallet +/// does not manage the identity (code 7), as it then holds nothing for it; +/// nil when a read failed otherwise, which the views keep apart from +/// "nothing held" (`PrivateRepliesPendingSnapshot`). +func contactRequestHolds( + contactIds: [Data], + privatePairHeld: (Data) throws -> Bool, + publicUnconfirmed: (Data) throws -> Bool +) -> ContactRequestHolds? { + do { + var holds = ContactRequestHolds() + for contactId in contactIds { + if try privatePairHeld(contactId) { + holds.privatelyHeld.insert(contactId) + } + if try publicUnconfirmed(contactId) { + holds.publicUnconfirmed.insert(contactId) + } + } + return holds + } catch PlatformWalletError.identityNotFound(_) { + return ContactRequestHolds() + } catch { + return nil + } +} + +/// The DashPay views' readiness refresh, one flow for the request list and +/// Add Contact. The wallet owns the recovery: on a store already open, a +/// repeat `configureShielded` retries restoring every wallet whose private +/// payments are still held, a restoration that failed after the store +/// opened included, and defers it to a task while a scan holds the store. +/// So a refresh asks for it whenever the payments are not restored, or the +/// store did not open, and only then reads the readiness it shows: the +/// readiness is read after the attempt, never cached from before it. While +/// the payments stay unrestored (a deferred restoration completes later, +/// changing nothing a view observes but the end of the shielded scan that +/// held the store), the view keeps refreshing on a timer for as long as it +/// is shown, and again when a shielded sync pass ends, so the gate lifts +/// without a bind, a restart or a submitted request. The views change no +/// hold themselves. +enum PrivatePaymentsRecovery { + /// The cadence of the automatic refreshes while the payments stay + /// unrestored: every `fastRecheckInterval` for the first `fastRechecks` + /// of them (a minute), then every `slowRecheckInterval`, for as long as + /// the view is shown. It never stops on a count: a shielded scan can hold + /// the store for minutes, and the wallet runs a restoration it deferred + /// only once the scan frees it. Each refresh is local and cheap, reads of + /// in-memory wallet state and a repeat `configureShielded` that checks + /// which wallets are still held and queues at most one deferred + /// restoration per wallet, with no network call, so an open-ended poll at + /// this cadence costs little. It stops when the readiness reads restored + /// or the view goes away; a view for another identity starts its own. + static let fastRechecks = 20 + static let fastRecheckInterval: Duration = .seconds(3) + static let slowRecheckInterval: Duration = .seconds(15) + + /// Whether a refresh asks the wallet to retry before it reads the + /// readiness it shows: the store did not open last time, or the last + /// readiness read says the payments are not restored. + static func retries(readiness: PrivateContactReadiness?, storeFailure: String?) -> Bool { + storeFailure != nil || readiness?.privatePaymentsRestored == false + } + + /// The pause before the next automatic refresh after `attempt` of them, + /// or nil when there is none: the readiness reads restored, or no read + /// succeeded yet (left to the refresh the view makes anyway). + static func recheckDelay(after readiness: PrivateContactReadiness?, attempt: Int) -> Duration? { + guard readiness?.privatePaymentsRestored == false else { return nil } + return attempt < fastRechecks ? fastRecheckInterval : slowRecheckInterval + } + + /// Wait for the next automatic refresh and say whether to make it: false + /// at once when none is due (`recheckDelay`), false when the wait is cut + /// short (`sleep` throws, as the view's task does when the view goes + /// away), true otherwise. The views pass `Task.sleep`. + @MainActor + static func waitForRecheck( + after readiness: PrivateContactReadiness?, + attempt: Int, + sleep: (Duration) async throws -> Void + ) async -> Bool { + guard let delay = recheckDelay(after: readiness, attempt: attempt) else { return false } + do { + try await sleep(delay) + } catch { + return false + } + return !Task.isCancelled + } + + /// One refresh. `lastReadiness` is the readiness the view shows now; + /// `readReadiness` reads the wallet's (with the reason a restoration + /// failed); `configureAgain` asks the wallet to retry and returns why the + /// store did not open, or nil. When `retries` says so, the wallet is asked + /// first and the readiness is read after it; otherwise it is read once. + @MainActor + static func refresh( + lastReadiness: PrivateContactReadiness?, + storeFailure: String?, + readReadiness: () -> (readiness: PrivateContactReadiness?, restoreFailure: String?), + configureAgain: () -> String? + ) -> (readiness: PrivateContactReadiness?, restoreFailure: String?, storeFailure: String?) { + var storeFailure = storeFailure + if retries(readiness: lastReadiness, storeFailure: storeFailure) { + storeFailure = configureAgain() + let read = readReadiness() + return (read.readiness, read.restoreFailure, storeFailure) + } + let read = readReadiness() + if retries(readiness: read.readiness, storeFailure: storeFailure) { + storeFailure = configureAgain() + let again = readReadiness() + return (again.readiness, again.restoreFailure, storeFailure) + } + return (read.readiness, read.restoreFailure, storeFailure) + } +} + +/// How Add Contact's collision alert accepts the request the recipient +/// already sent us. With "Send privately" on, the user chose a private +/// request, so the accept replies privately +/// (`PlatformWalletManager.acceptPrivateContactRequest`, paid from the +/// shielded balance as the private send is) even when their request came +/// publicly: a public reply would publish this user as its owner and the +/// contact as its recipient, against that choice. With it off, the wallet +/// replies the way the request came +/// (`PlatformWalletManager.acceptContactRequestReplyingInKind`). The toggle is +/// the user's explicit choice; which reply an in-kind accept takes stays the +/// wallet's. +enum CollisionAccept: Equatable { + /// Reply privately, paid from the shielded balance. + case privateReply + /// Reply the way the request came. + case replyInKind + + static func of(sendPrivately: Bool) -> CollisionAccept { + sendPrivately ? .privateReply : .replyInKind + } + + /// The alert's accept button. + var buttonTitle: String { + switch self { + case .privateReply: return "Accept privately" + case .replyInKind: return "Accept" + } + } + + /// The alert's message. + var message: String { + switch self { + case .privateReply: + return "This person already sent you a request. Accept it with a private reply " + + "instead? The reply is paid from this wallet's shielded balance, and no " + + "public request names you as its sender." + case .replyInKind: + return "This person already sent you a request. Accept it instead?" + } + } +} + +/// What the request list's private-store refresh tells the user. A network +/// that does not serve the store yet (before protocol version 15) is expected +/// and stays quiet; an operational failure, or requests read but not saved, +/// is shown so the user knows to refresh again. +enum PrivateContactRefreshNotice { + /// The notice a pass that read the store leaves, or nil when every + /// identity's requests reached disk. + static func notice(unpersistedIdentityCount: UInt32) -> String? { + guard unpersistedIdentityCount > 0 else { return nil } + return "Private requests for \(unpersistedIdentityCount) " + + (unpersistedIdentityCount == 1 ? "identity were" : "identities were") + + " read but not saved. Pull to refresh again." + } + + /// The notice a pass that failed leaves, or nil when the network does not + /// serve the private store yet. + static func notice(for error: Error) -> String? { + if let walletError = error as? PlatformWalletError { + switch walletError { + case .protocolVersionNotActive: + return nil + case .sdkPinnedBelowProtocolVersion: + return ContactRequestSubmissionOutcome.sdkPinnedMessage + default: + break + } + } + return "Private requests could not be read: \(error.localizedDescription)" + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift index 0ad941084cb..0d489a702cd 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift @@ -20,6 +20,12 @@ struct ContactRequestsView: View { @Binding var optimisticSentIds: Set @EnvironmentObject var walletManager: PlatformWalletManager + /// Observed for its bind: binding the shielded account restores the + /// wallet's private payments, so the readiness is read again then. + @EnvironmentObject var shieldedService: ShieldedService + /// Read for why the shielded store could not be opened, which keeps the + /// wallet's private payments waiting. + @EnvironmentObject var walletManagerStore: WalletManagerStore @EnvironmentObject var contactMeta: DashPayContactMetaStore @Environment(\.modelContext) private var modelContext @@ -41,6 +47,27 @@ struct ContactRequestsView: View { /// with an inline error on the row). @State private var rowErrors: [Data: String] = [:] + /// Contact ids whose pair the wallet holds for a private request, as a + /// send decides it, or for a public request awaiting its outcome + /// (`contactRequestHolds`): the row stays pending or "being checked", + /// without its buttons, until the wallet's read says the pair is free. + /// Read from the wallet on appear, after an accept and after each sync + /// pass, so leaving and reopening the screen keeps it. A failed read + /// keeps the last snapshot and leaves every row without its buttons until + /// a read succeeds. + @State private var walletPending = PrivateRepliesPendingSnapshot() + + /// Why the shielded store could not be opened, as last read with the + /// pending state; nil when it is open. + @State private var shieldedStoreFailure: String? + + /// The automatic refreshes made since the wallet's private payments were + /// last read restored (`PrivatePaymentsRecovery.recheckDelay`). + @State private var readinessRechecks = 0 + + /// What the last private-store refresh has to tell the user, if anything. + @State private var privateRefreshNotice: String? + init(identity: PersistentIdentity, optimisticSentIds: Binding>) { self.identity = identity _optimisticSentIds = optimisticSentIds @@ -105,6 +132,7 @@ struct ContactRequestsView: View { if incomingPending.isEmpty && outgoingPending.isEmpty && optimisticOutgoing.isEmpty { List { + privateRefreshNoticeSection DashPayListEmptyRow( icon: "tray", title: "No pending requests", @@ -114,6 +142,7 @@ struct ContactRequestsView: View { .listStyle(.insetGrouped) } else { List { + privateRefreshNoticeSection if !incomingPending.isEmpty { Section { ForEach(incomingPending, id: \.contactIdentityId) { row in @@ -126,8 +155,17 @@ struct ContactRequestsView: View { // contact is accepted (established rows load it normally). avatarUrl: nil, createdAtMillis: row.createdAtMillis, - isInFlight: inFlightIds.contains(row.contactIdentityId), - errorMessage: rowErrors[row.contactIdentityId], + isInFlight: inFlightIds.contains(row.contactIdentityId) + || !walletPending.allowsSubmission(to: row.contactIdentityId), + errorMessage: ContactRequestSubmissionOutcome.rowMessage( + pending: walletPending.isPending(row.contactIdentityId), + awaitingOutcome: walletPending.isAwaitingOutcome(row.contactIdentityId), + restoring: walletPending.isRestoringPrivatePayments, + restoreFailure: walletPending.restoreFailure, + shieldedStoreFailure: shieldedStoreFailure, + unavailable: walletPending.isUnavailable, + error: rowErrors[row.contactIdentityId] + ), onAccept: { accept(contactId: row.contactIdentityId) }, onIgnore: { ignore(contactId: row.contactIdentityId) } ) @@ -164,10 +202,34 @@ struct ContactRequestsView: View { } } .refreshable { + // The DashPay sync settles a public request awaiting its outcome + // first, so the reload below reads what it decided. await attachOrStartSync(walletManager) + if let wallet = try? requireWallet() { + privateRefreshNotice = await syncPrivateContactRequests(wallet) + } + reloadPendingReplies() } + .task { reloadPendingReplies() } + // While the wallet's private payments stay unrestored, refresh again + // after a pause: a restoration the wallet deferred behind a busy + // store completes later and changes nothing this view observes. + .task(id: readinessRechecks) { + guard readinessRechecks > 0 else { return } + let due = await PrivatePaymentsRecovery.waitForRecheck( + after: walletPending.readiness, attempt: readinessRechecks - 1, + sleep: { try await Task.sleep(for: $0) }) + if due { reloadPendingReplies() } + } + // A deferred restoration runs once the shielded scan holding the store + // ends: refresh then too, ahead of the timer. + .onChange(of: shieldedService.isSyncing) { _, syncing in + if !syncing { reloadPendingReplies() } + } + .onChange(of: shieldedService.isBound) { _, _ in reloadPendingReplies() } .onChange(of: rowSignature) { _, _ in pruneOverlays() + reloadPendingReplies() } .onChange(of: walletManager.dashPaySyncIsSyncing) { _, syncing in // Fallback clearing rule: after the next completed @@ -177,10 +239,53 @@ struct ContactRequestsView: View { if !syncing { removedOverlayIds.removeAll() optimisticSentIds.removeAll() + reloadPendingReplies() } } } + /// The last private-store refresh's notice, when it has one. + @ViewBuilder + private var privateRefreshNoticeSection: some View { + if let privateRefreshNotice { + Section { + Text(privateRefreshNotice) + .font(.caption) + .foregroundColor(.orange) + .accessibilityIdentifier("dashpay.requests.privateRefreshNotice") + } + } + } + + /// Re-read from the wallet its readiness (`PrivatePaymentsRecovery.refresh`: + /// the wallet is asked to retry a restoration first when its payments are + /// not restored, and the readiness shown is read after that), then which + /// incoming rows' pairs it holds for a private request or for a public + /// request awaiting its outcome, and keep refreshing on a timer while the + /// payments stay unrestored. + private func reloadPendingReplies() { + let contactIds = incomingPending.map(\.contactIdentityId) + let wallet = try? requireWallet() + let identityId = identity.identityId + let refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: walletPending.readiness, + storeFailure: walletManagerStore.shieldedStoreFailure(of: walletManager), + readReadiness: { privateContactReadiness(wallet: wallet, identityId: identityId) }, + configureAgain: { walletManagerStore.configureShieldedAgain(walletManager) } + ) + walletPending.recordReadiness(refreshed.readiness, restoreFailure: refreshed.restoreFailure) + shieldedStoreFailure = refreshed.storeFailure + walletPending.record( + contactRequestHolds(wallet: wallet, identityId: identityId, contactIds: contactIds), + for: contactIds + ) + if PrivatePaymentsRecovery.recheckDelay(after: walletPending.readiness, attempt: readinessRechecks) != nil { + readinessRechecks += 1 + } else if walletPending.readiness?.privatePaymentsRestored == true { + readinessRechecks = 0 + } + } + // MARK: - Overlay maintenance /// Drop overlay entries the `@Query` already reflects: @@ -225,14 +330,46 @@ struct ContactRequestsView: View { return } let signer = KeychainSigner(modelContainer: modelContext.container) - _ = try await wallet.acceptContactRequest(request, signer: signer) + // The wallet replies the way the request came: privately + // (paid from the shielded balance) or with a document. + _ = try await walletManager.acceptContactRequestReplyingInKind( + walletId: wallet.walletId, + resolver: MnemonicResolver(), + request: request, + signer: signer + ) // Optimistic removal — the persister will promote the // pair to established shortly. removedOverlayIds.insert(contactId) kickDashPaySync(walletManager) } catch { - rowErrors[contactId] = "Accept failed: \(error.localizedDescription)" + let outcome = ContactRequestSubmissionOutcome.of(error) + walletPending.recordOutcome(outcome, for: contactId) + switch outcome { + case .mayHaveGoneThrough, .publicRequestUnconfirmed: + // As `SendViewModel` treats an unconfirmed spend: not a + // failure to retry. The wallet holds the pair (a private + // reply pending, or a public one awaiting its outcome, 76 + // when an earlier one still does), and the row reads that; + // the sync settles it. + kickDashPaySync(walletManager) + case .privateRequestPending: + // Nothing was sent: the wallet holds the pair. The row + // stays pending until its per-contact read says free. + kickDashPaySync(walletManager) + case .privatePaymentsNotRestored: + // The wallet is held until its private payments are + // restored; every row waits for the readiness to say so. + break + case .privateStoreNotRead: + // Nothing was sent and nothing is pending: the user may + // accept again, which continues the read. + rowErrors[contactId] = ContactRequestSubmissionOutcome.privateStoreNotReadMessage + case .failed(let message): + rowErrors[contactId] = "Accept failed: \(message)" + } } + reloadPendingReplies() } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactsView.swift index edc73820e76..a2108686f70 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactsView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactsView.swift @@ -226,6 +226,69 @@ func kickDashPaySync(_ walletManager: PlatformWalletManager) { Task { _ = try? await walletManager.dashPaySyncNow() } } +/// The wallet's two holds on `identityId`'s pairs with `contactIds`, one +/// read of each per contact: held for a private request, as a send decides +/// it (`ManagedPlatformWallet.privatePairHeld`: a private request in flight, +/// paid and not yet read back, or kept by the shielded store's journal), and +/// held for a public request whose broadcast may have been delivered +/// (`ManagedPlatformWallet.publicContactRequestUnconfirmed`), which a DashPay +/// sync settles. While either holds a pair, Rust refuses another send or +/// reply to it, so the views offer neither. Empty when the wallet does not +/// manage the identity, as it then holds nothing for it. Nil when the wallet +/// could not be read (no loaded wallet, or a read failed), which the views +/// keep apart from "nothing held" (`PrivateRepliesPendingSnapshot`). +@MainActor +func contactRequestHolds( + wallet: ManagedPlatformWallet?, + identityId: Data, + contactIds: [Data] +) -> ContactRequestHolds? { + guard !contactIds.isEmpty else { return ContactRequestHolds() } + guard let wallet else { return nil } + return contactRequestHolds( + contactIds: contactIds, + privatePairHeld: { try wallet.privatePairHeld(senderId: identityId, recipientId: $0) }, + publicUnconfirmed: { + try wallet.publicContactRequestUnconfirmed(senderId: identityId, recipientId: $0) + } + ) +} + +/// The wallet's readiness for `identityId`'s contact requests and, when it +/// flags a failed restoration, why it failed; a nil readiness when it could +/// not be read (`PrivateRepliesPendingSnapshot.recordReadiness` keeps the +/// last one then). +@MainActor +func privateContactReadiness( + wallet: ManagedPlatformWallet?, + identityId: Data +) -> (readiness: PrivateContactReadiness?, restoreFailure: String?) { + guard let readiness = try? wallet?.privateContactReadiness(identityId: identityId) else { + return (nil, nil) + } + guard readiness.privatePaymentsRestoreFailed else { return (readiness, nil) } + let reason = (try? wallet?.privatePaymentsRestoreFailure(identityId: identityId)) ?? nil + return (readiness, reason) +} + +/// Read DashPay's private contact request store (protocol version 15) for +/// `wallet`, returning what the refresh should tell the user, or nil. +/// Private requests reach the wallet only through this read, so it runs with +/// every pull-to-refresh of the request list. A network before protocol +/// version 15 does not serve the store yet, which is expected and quiet; any +/// other failure, or requests read but not saved, is reported. +@MainActor +func syncPrivateContactRequests(_ wallet: ManagedPlatformWallet) async -> String? { + do { + let result = try await wallet.syncPrivateContactRequests() + return PrivateContactRefreshNotice.notice( + unpersistedIdentityCount: result.unpersistedIdentityCount + ) + } catch { + return PrivateContactRefreshNotice.notice(for: error) + } +} + // MARK: - Row model + view /// UI model for one established contact row, resolved from the diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift index a567917dedf..d5565d27f42 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift @@ -76,6 +76,20 @@ struct StorageExplorerView: View { ) { DashpayIgnoredSenderStorageListView(network: network) } + modelRow( + "Private Request Positions", + icon: "bookmark", + type: PersistentPrivateContactRequestsPosition.self + ) { + PrivateContactRequestsPositionStorageListView(network: network) + } + modelRow( + "Private Shielded Addresses", + icon: "lock.rectangle", + type: PersistentPrivateShieldedAddress.self + ) { + PrivateShieldedAddressStorageListView(network: network) + } modelRow( "Sent Invitations", icon: "paperplane", @@ -291,6 +305,8 @@ struct StorageExplorerView: View { directCount(PersistentDashpayContactProfile.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayPayment.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayIgnoredSender.self, predicate: #Predicate { $0.networkRaw == raw }) + directCount(PersistentPrivateContactRequestsPosition.self, predicate: #Predicate { $0.networkRaw == raw }) + directCount(PersistentPrivateShieldedAddress.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDocument.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDataContract.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentTokenBalance.self, predicate: #Predicate { $0.networkRaw == raw }) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift index 23bc60dd8c3..fb8ff7e41bb 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift @@ -63,6 +63,68 @@ struct IdentityBalanceMetadataStorageListView: View { } } +// MARK: - PersistentPrivateContactRequestsPosition + +struct PrivateContactRequestsPositionStorageListView: View { + let network: Network + @Query private var records: [PersistentPrivateContactRequestsPosition] + + private var filtered: [PersistentPrivateContactRequestsPosition] { + records.filter { $0.networkRaw == network.rawValue } + .sorted { $0.identityId.toHexString() < $1.identityId.toHexString() } + } + + var body: some View { + let visible = filtered + List(visible) { record in + NavigationLink(destination: PrivateContactRequestsPositionStorageDetailView(record: record)) { + VStack(alignment: .leading, spacing: 4) { + Text(record.identityId.toHexString()) + .font(.body).lineLimit(1).truncationMode(.middle) + Text("Wallet: \(record.walletId.toHexString())") + .font(.caption).foregroundColor(.secondary) + .lineLimit(1).truncationMode(.middle) + // Stored as a bit pattern; show the unsigned position. + Text("Position \(UInt64(bitPattern: record.position))") + .font(.caption).foregroundColor(.secondary) + } + } + } + .navigationTitle("Private Positions (\(visible.count))") + .overlay { if visible.isEmpty { ContentUnavailableView("No Records", systemImage: "bookmark") } } + } +} + +// MARK: - PersistentPrivateShieldedAddress + +struct PrivateShieldedAddressStorageListView: View { + let network: Network + @Query private var records: [PersistentPrivateShieldedAddress] + + private var filtered: [PersistentPrivateShieldedAddress] { + records.filter { $0.networkRaw == network.rawValue } + .sorted { ($0.ownerId.toHexString(), $0.contactId.toHexString()) + < ($1.ownerId.toHexString(), $1.contactId.toHexString()) } + } + + var body: some View { + let visible = filtered + List(visible) { record in + NavigationLink(destination: PrivateShieldedAddressStorageDetailView(record: record)) { + VStack(alignment: .leading, spacing: 4) { + Text("Contact: \(record.contactId.toHexString())") + .font(.body).lineLimit(1).truncationMode(.middle) + Text("Owner: \(record.ownerId.toHexString())") + .font(.caption).foregroundColor(.secondary) + .lineLimit(1).truncationMode(.middle) + } + } + } + .navigationTitle("Private Addresses (\(visible.count))") + .overlay { if visible.isEmpty { ContentUnavailableView("No Records", systemImage: "lock.rectangle") } } + } +} + // MARK: - PersistentDocument struct DocumentStorageListView: View { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift index 7fe6ed1cd28..4b2b4e0a471 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift @@ -86,6 +86,60 @@ struct IdentityBalanceMetadataStorageDetailView: View { } } +// MARK: - PersistentPrivateContactRequestsPosition + +struct PrivateContactRequestsPositionStorageDetailView: View { + let record: PersistentPrivateContactRequestsPosition + + var body: some View { + Form { + Section("Identity") { + FieldRow(label: "Network", value: Network(rawValue: record.networkRaw)?.displayName ?? "raw \(record.networkRaw)") + FieldRow(label: "Wallet ID", value: hexString(record.walletId)) + FieldRow(label: "Identity ID", value: hexString(record.identityId)) + } + Section { + FieldRow(label: "Read Position", value: String(UInt64(bitPattern: record.position))) + FieldRow(label: "Key Fingerprint", value: hexString(record.keyFingerprint)) + FieldRow(label: "Private Payments Unresolved", value: record.privatePaymentsUnresolved ? "Yes" : "No") + } header: { + Text("Private Contact Request Store") + } footer: { + // The purge rule: a marked record outlives its wallet. + if record.privatePaymentsUnresolved { + Text("Kept when its wallet is removed, until a record stored cleared for the same " + + "wallet and identity replaces it: the private payment it stands for may still " + + "execute.") + } + } + } + .navigationTitle("Private Position") + .navigationBarTitleDisplayMode(.inline) + } +} + +// MARK: - PersistentPrivateShieldedAddress + +struct PrivateShieldedAddressStorageDetailView: View { + let record: PersistentPrivateShieldedAddress + + var body: some View { + Form { + Section("Contact") { + FieldRow(label: "Network", value: Network(rawValue: record.networkRaw)?.displayName ?? "raw \(record.networkRaw)") + FieldRow(label: "Wallet ID", value: hexString(record.walletId)) + FieldRow(label: "Owner ID", value: hexString(record.ownerId)) + FieldRow(label: "Contact ID", value: hexString(record.contactId)) + } + Section("Shielded Address") { + FieldRow(label: "Raw Address", value: hexString(record.address)) + } + } + .navigationTitle("Private Address") + .navigationBarTitleDisplayMode(.inline) + } +} + // MARK: - PersistentIdentity struct IdentityStorageDetailView: View { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift index ec183dfa41e..99c54e89ee1 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift @@ -168,6 +168,12 @@ final class WalletManagerStore: ObservableObject { /// cross-network bleed at restore time. private let modelContainer: ModelContainer + /// Why opening each network's shielded store failed, until a later + /// attempt succeeds. The DashPay views show it while the wallet's + /// private payments wait for that store, and retry it + /// (`configureShieldedAgain(_:)`). + @Published private(set) var shieldedStoreFailures: [Network: String] = [:] + init(modelContainer: ModelContainer) { self.modelContainer = modelContainer // Placeholder. Held until the first `activate(...)` call @@ -202,6 +208,11 @@ final class WalletManagerStore: ObservableObject { if let existing = managers[network] { let cachedHandle = managerSdkHandles[network] if cachedHandle == sdk.handle { + // A shielded store that did not open last time is tried + // again: until it opens, contact requests stay held (72). + if shieldedStoreFailures[network] != nil { + configureShieldedStore(existing, network: network) + } if makeActive && existing !== activeManager { // Swapping to a different warm manager supersedes any // in-flight SPV start against the outgoing one. @@ -232,6 +243,15 @@ final class WalletManagerStore: ObservableObject { } let manager = PlatformWalletManager() try manager.configure(sdk: sdk, modelContainer: modelContainer) + // Open the shielded store before any wallet is loaded or created: + // this app's persister keeps the private contact request scan state, + // so Rust holds every wallet published while no store is configured + // (code 72) until its private payment journal is read, and a later + // bind may never come (no mnemonic, shielded off). With the store + // open first, each wallet's journal is read as it is published, and + // the binds' own calls on the same path are no-ops. A failure is + // recorded and retried; the wallets stay held meanwhile. + configureShieldedStore(manager, network: network) // Best-effort: a fresh manager comes up with no wallets in // memory; restore from the network-scoped persistence // handler so reopening the app on this network resurfaces @@ -270,6 +290,45 @@ final class WalletManagerStore: ObservableObject { ) } + /// Open `network`'s shielded store on `manager`, recording why it failed + /// for the DashPay views, or clearing that once it opens. A repeat on the + /// same path does not wait on the store, so it is safe on the main + /// thread. + private func configureShieldedStore(_ manager: PlatformWalletManager, network: Network) { + do { + try manager.configureShielded(dbPath: ShieldedService.dbPath(for: network)) + shieldedStoreFailures[network] = nil + } catch { + shieldedStoreFailures[network] = error.localizedDescription + SDKLogger.event( + "manager_shielded_configure_failed", + category: .lifecycle, + severity: .error, + fields: ["network": .publicText(network.displayName)], + error: error + ) + } + } + + /// Why opening the shielded store of `manager`'s network failed last, or + /// nil when it opened (or `manager` is not one of this store's). + func shieldedStoreFailure(of manager: PlatformWalletManager) -> String? { + guard let network = managers.first(where: { $0.value === manager })?.key else { return nil } + return shieldedStoreFailures[network] + } + + /// Open `manager`'s shielded store again and return why it failed, or + /// nil once it is open. On a store already open this asks the wallet to + /// retry restoring every wallet whose private payments are still held, + /// a restoration that failed after the store opened included; it never + /// waits on a busy store (a busy store defers the restoration to a + /// task), so it is safe on the main thread. + func configureShieldedAgain(_ manager: PlatformWalletManager) -> String? { + guard let network = managers.first(where: { $0.value === manager })?.key else { return nil } + configureShieldedStore(manager, network: network) + return shieldedStoreFailures[network] + } + /// Manager for `network` if one has been activated this session; /// otherwise `nil`. Used for diagnostics surfaces (e.g. Wallet /// Memory Explorer) that want to inspect a specific network's diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ContactRequestOutcomesTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ContactRequestOutcomesTests.swift new file mode 100644 index 00000000000..da9d4717e18 --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ContactRequestOutcomesTests.swift @@ -0,0 +1,643 @@ +import XCTest +import SwiftDashSDK +@testable import SwiftExampleApp + +/// Pins how the DashPay views read a failed contact request submission and a +/// private-store refresh, code by code: an unconfirmed private send or reply +/// (18) stays pending with no fresh submission offered, a held pair (71) is +/// pending until the per-contact read says free, unrestored payments (72) +/// show "setting up" or why the restoration failed, an unsupported store (73) +/// and a pinned SDK (75) are configuration messages, an unfinished private +/// store read (74) is a retry with no pending row, and a network that does +/// not serve the private store yet is quiet while real failures are shown. +/// A public request or accept that may have gone through (20), or one the +/// wallet refuses while an earlier one awaits its outcome (76), shows +/// "being checked" with no submission offered until the wallet's read of +/// the pair says settled. +final class ContactRequestOutcomesTests: XCTestCase { + + /// Code 18: a note spend whose broadcast may have reached a node, a + /// verdict included, may still land; nothing is offered again. + func testShouldKeepAnUnconfirmedPrivateSubmissionPending() { + let outcome = ContactRequestSubmissionOutcome.of( + PlatformWalletError.shieldedSpendUnconfirmed("result could not be confirmed") + ) + XCTAssertEqual(outcome, .mayHaveGoneThrough) + } + + /// Code 20: a state transition the SDK could not confirm after it may + /// have been accepted, which a private send or accept can now return + /// through the spend contract, and a public one through the blanket + /// conversion. It may have executed: nothing is offered again. + func testShouldKeepAnUnconfirmedStateTransitionPending() { + XCTAssertEqual( + ContactRequestSubmissionOutcome.of( + PlatformWalletError.transactionBroadcastUnconfirmed("result could not be confirmed")), + .mayHaveGoneThrough) + } + + /// A shielded send treats code 20 as it treats 18: it may have gone + /// through, so no retry is offered; an ordinary failure is not. + func testShouldNotOfferARetryForAShieldedOperationThatMayHaveGoneThrough() { + XCTAssertTrue(SendViewModel.mayHaveGoneThrough(.shieldedSpendUnconfirmed("not proved"))) + XCTAssertTrue(SendViewModel.mayHaveGoneThrough(.transactionBroadcastUnconfirmed("not confirmed"))) + XCTAssertFalse(SendViewModel.mayHaveGoneThrough(.shieldedBroadcastFailed("never sent"))) + } + + /// A pending private request (code 71), which a public send or accept + /// can meet too, sent nothing: it is shown as pending rather than as a + /// submission that may have gone through. + func testShouldKeepAPendingPrivateRequestPending() { + let outcome = ContactRequestSubmissionOutcome.of( + PlatformWalletError.privateContactRequestPending("not yet read back from the store") + ) + XCTAssertEqual(outcome, .privateRequestPending) + } + + func testShouldShowAWalletPendingReplyOverAnEarlierError() { + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage(pending: true, error: "Accept failed: boom"), + ContactRequestSubmissionOutcome.privateRequestPendingMessage + ) + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage(pending: false, error: "Accept failed: boom"), + "Accept failed: boom" + ) + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage( + pending: false, unavailable: true, error: "Accept failed: boom"), + PrivateRepliesPendingSnapshot.unavailableMessage + ) + XCTAssertNil(ContactRequestSubmissionOutcome.rowMessage(pending: false, error: nil)) + } + + /// A read that found a private request pending, followed by a failed + /// read: the contact stays pending and nothing is offered for any + /// contact, until a read succeeds again. + func testShouldKeepThePendingSnapshotAndOfferNothingAfterAFailedRead() { + let pendingContact = Data(repeating: 1, count: 32) + let otherContact = Data(repeating: 2, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([pendingContact]), for: [pendingContact, otherContact]) + XCTAssertTrue(snapshot.isPending(pendingContact)) + XCTAssertFalse(snapshot.allowsSubmission(to: pendingContact)) + XCTAssertTrue(snapshot.allowsSubmission(to: otherContact)) + + snapshot.record(nil, for: [pendingContact, otherContact]) + XCTAssertTrue(snapshot.isUnavailable) + XCTAssertTrue(snapshot.isPending(pendingContact), "the last snapshot stays") + XCTAssertFalse(snapshot.allowsSubmission(to: pendingContact)) + XCTAssertFalse(snapshot.allowsSubmission(to: otherContact)) + + snapshot.record(privatelyHeld([]), for: [pendingContact, otherContact]) + XCTAssertFalse(snapshot.isUnavailable) + XCTAssertTrue(snapshot.allowsSubmission(to: pendingContact)) + } + + /// A send refused as pending (code 71) marks the contact pending at once; + /// the next read of the pair, which reads what the refusal read, decides: + /// held keeps it pending, free re-enables it. The readiness alone never + /// re-enables it. + func testShouldReEnableARefusedPairOnlyWhenThePerContactReadSaysFree() { + let contact = Data(repeating: 1, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + snapshot.recordRefusal(of: contact) + XCTAssertTrue(snapshot.isPending(contact)) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage( + pending: snapshot.isPending(contact), error: nil), + ContactRequestSubmissionOutcome.privateRequestPendingMessage) + + // A readiness that says the store was read and nothing is held for + // the wallet does not free one pair. + snapshot.recordReadiness(PrivateContactReadiness( + privatePaymentsRestored: true, privateStoreRead: true, unresolvedPrivatePayment: false)) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + + // The pair's read says held: still pending. + snapshot.record(privatelyHeld([contact]), for: [contact]) + XCTAssertTrue(snapshot.isPending(contact)) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + + // A payment that will never land frees the pair once the wallet + // proves so; the next read says free and the controls come back. + snapshot.record(privatelyHeld([]), for: [contact]) + XCTAssertFalse(snapshot.isPending(contact)) + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + } + + /// A read that does not cover a refused contact leaves its refusal. + func testShouldKeepARefusalAReadDidNotCover() { + let refused = Data(repeating: 1, count: 32) + let other = Data(repeating: 2, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.recordRefusal(of: refused) + snapshot.record(privatelyHeld([]), for: [other]) + XCTAssertTrue(snapshot.isPending(refused)) + XCTAssertTrue(snapshot.allowsSubmission(to: other)) + } + + /// Code 74: the private store read every contact request runs first did + /// not finish. Nothing was sent and nothing is pending: its own outcome, + /// with a retry message, and no pending row. + func testShouldOfferARetryForAnUnfinishedPrivateStoreRead() { + let contact = Data(repeating: 1, count: 32) + XCTAssertEqual( + ContactRequestSubmissionOutcome.of( + PlatformWalletError.privateContactStoreNotRead("not read to its end")), + .privateStoreNotRead) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + XCTAssertFalse(snapshot.isPending(contact), "the view records no refusal for 74") + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + XCTAssertNotEqual( + ContactRequestSubmissionOutcome.privateStoreNotReadMessage, + ContactRequestSubmissionOutcome.privateRequestPendingMessage) + } + + /// Code 75 is the developer's setting, shown as such, on a send and on a + /// refresh alike. + func testShouldShowAPinnedSdkAsADeveloperMessage() { + let error = PlatformWalletError.sdkPinnedBelowProtocolVersion("pinned at 14") + XCTAssertEqual( + ContactRequestSubmissionOutcome.of(error), + .failed(ContactRequestSubmissionOutcome.sdkPinnedMessage)) + XCTAssertEqual( + PrivateContactRefreshNotice.notice(for: error), + ContactRequestSubmissionOutcome.sdkPinnedMessage) + } + + /// Unrestored private payments (code 72) are their own outcome, apart + /// from a pending request (71), with their own message. + func testShouldTellUnrestoredPrivatePaymentsFromAPendingRequest() { + XCTAssertEqual( + ContactRequestSubmissionOutcome.of( + PlatformWalletError.privateContactPaymentsNotRestored("not restored")), + .privatePaymentsNotRestored) + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage(pending: true, restoring: true, error: nil), + ContactRequestSubmissionOutcome.settingUpPrivatePaymentsMessage) + XCTAssertNotEqual( + ContactRequestSubmissionOutcome.settingUpPrivatePaymentsMessage, + ContactRequestSubmissionOutcome.privateRequestPendingMessage) + } + + /// Code 72 after a failed restoration shows why it failed, read with the + /// readiness, until a readiness says restored; a shielded store that did + /// not open is shown over both. + func testShouldShowWhyARestorationFailedUntilTheReadinessSaysRestored() { + let contact = Data(repeating: 1, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + snapshot.recordReadiness( + PrivateContactReadiness( + privatePaymentsRestored: false, privateStoreRead: false, + unresolvedPrivatePayment: false, privatePaymentsRestoreFailed: true), + restoreFailure: "the journal does not read") + XCTAssertTrue(snapshot.isRestoringPrivatePayments) + XCTAssertEqual(snapshot.restoreFailure, "the journal does not read") + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage( + pending: false, restoring: snapshot.isRestoringPrivatePayments, + restoreFailure: snapshot.restoreFailure, error: nil), + ContactRequestSubmissionOutcome.restoreFailedMessage("the journal does not read")) + XCTAssertEqual( + ContactRequestSubmissionOutcome.rowMessage( + pending: false, restoring: true, restoreFailure: snapshot.restoreFailure, + shieldedStoreFailure: "disk full", error: nil), + ContactRequestSubmissionOutcome.shieldedStoreFailedMessage("disk full")) + + // A readiness that no longer flags a failure drops the reason. + snapshot.recordReadiness( + PrivateContactReadiness( + privatePaymentsRestored: false, privateStoreRead: false, + unresolvedPrivatePayment: false), + restoreFailure: "stale") + XCTAssertNil(snapshot.restoreFailure) + + snapshot.recordReadiness(PrivateContactReadiness( + privatePaymentsRestored: true, privateStoreRead: false, unresolvedPrivatePayment: false)) + XCTAssertFalse(snapshot.isRestoringPrivatePayments) + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + } + + /// A store that cannot protect private payments (code 73) is a + /// configuration error, shown as such. + func testShouldShowUnsupportedPrivateRecoveryAsAStorageError() { + XCTAssertEqual( + ContactRequestSubmissionOutcome.of( + PlatformWalletError.privateContactRecoveryUnsupported("no atomic scan state")), + .failed(ContactRequestSubmissionOutcome.recoveryUnsupportedMessage)) + } + + /// A code 72 hold survives a successful pending read that finds nothing, + /// and a readiness read after a private sync that still says not + /// restored; only a readiness read that says restored lifts it. + func testShouldHoldOnCode72UntilTheReadinessSaysRestored() { + let contact = Data(repeating: 1, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.recordRestoringRefusal() + snapshot.record(privatelyHeld([]), for: [contact]) + XCTAssertTrue(snapshot.isRestoringPrivatePayments) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + + // A private sync read the store to its end; the payments are still + // not restored. + snapshot.recordReadiness(PrivateContactReadiness( + privatePaymentsRestored: false, privateStoreRead: true, unresolvedPrivatePayment: true)) + XCTAssertTrue(snapshot.isRestoringPrivatePayments) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + + // A failed readiness read keeps what the last one said. + snapshot.recordReadiness(nil) + XCTAssertTrue(snapshot.isRestoringPrivatePayments) + + snapshot.recordReadiness(PrivateContactReadiness( + privatePaymentsRestored: true, privateStoreRead: true, unresolvedPrivatePayment: false)) + XCTAssertFalse(snapshot.isRestoringPrivatePayments) + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + } + + /// A readiness that says not restored holds every contact without any + /// refusal, as the wallet would refuse them. + func testShouldShowRestoringFromTheReadinessAlone() { + let contact = Data(repeating: 1, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + snapshot.recordReadiness(PrivateContactReadiness( + privatePaymentsRestored: false, privateStoreRead: false, unresolvedPrivatePayment: false)) + XCTAssertTrue(snapshot.isRestoringPrivatePayments) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + } + + /// A successful read that found nothing pending offers every contact it + /// covered, and nothing it did not. + func testShouldOfferEveryContactASuccessfulEmptyReadCovered() { + let contact = Data(repeating: 1, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + XCTAssertFalse(snapshot.isUnavailable) + XCTAssertFalse(snapshot.isPending(contact)) + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + XCTAssertFalse( + snapshot.allowsSubmission(to: Data(repeating: 2, count: 32)), + "a contact the read did not cover is not offered yet") + } + + private func readiness(restored: Bool, failed: Bool = false) -> PrivateContactReadiness { + PrivateContactReadiness( + privatePaymentsRestored: restored, privateStoreRead: true, + unresolvedPrivatePayment: false, privatePaymentsRestoreFailed: failed) + } + + /// The store opened, but the wallet's journal restoration failed for a + /// transient reason. A DashPay refresh asks the wallet to retry even + /// though no store-open failure is recorded, reads the readiness after + /// the attempt, and once the retry restores the payments the gate lifts: + /// no bind, no restart and no submitted request. + @MainActor + func testShouldRetryARestorationThatFailedAfterTheStoreOpenedOnARefresh() { + let contact = Data(repeating: 1, count: 32) + var restorationFails = true + var configures = 0 + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + let read = { () -> (readiness: PrivateContactReadiness?, restoreFailure: String?) in + restorationFails + ? (self.readiness(restored: false, failed: true), "the journal could not be read") + : (self.readiness(restored: true), nil) + } + + // The first refresh: the store opened, the restoration failed, and + // the retry it asks for fails too. + var refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: snapshot.readiness, storeFailure: nil, readReadiness: read, + configureAgain: { configures += 1; return nil }) + snapshot.recordReadiness(refreshed.readiness, restoreFailure: refreshed.restoreFailure) + XCTAssertEqual(configures, 1, "not restored asks the wallet to retry with no store failure recorded") + XCTAssertNil(refreshed.storeFailure) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual(snapshot.restoreFailure, "the journal could not be read") + XCTAssertNotNil(PrivatePaymentsRecovery.recheckDelay(after: snapshot.readiness, attempt: 0)) + + // The failure was transient: the next refresh asks first, the retry + // restores, and the readiness shown is the one read after it. + refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: snapshot.readiness, storeFailure: nil, readReadiness: read, + configureAgain: { configures += 1; restorationFails = false; return nil }) + snapshot.recordReadiness(refreshed.readiness, restoreFailure: refreshed.restoreFailure) + XCTAssertEqual(configures, 2) + XCTAssertFalse(snapshot.isRestoringPrivatePayments) + XCTAssertNil(snapshot.restoreFailure) + XCTAssertTrue(snapshot.allowsSubmission(to: contact), "the gate lifts on the refresh alone") + XCTAssertNil(PrivatePaymentsRecovery.recheckDelay(after: snapshot.readiness, attempt: 1)) + } + + /// A refresh asks for the retry before it reads the readiness it shows: + /// a view that last showed "not restored" asks first and shows only the + /// read made after it. + @MainActor + func testShouldShowTheReadinessReadAfterTheRetry() { + var events: [String] = [] + var restored = false + let refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: readiness(restored: false), storeFailure: nil, + readReadiness: { + events.append("read") + return (self.readiness(restored: restored), nil) + }, + configureAgain: { + events.append("configure") + restored = true + return nil + }) + XCTAssertEqual(events, ["configure", "read"]) + XCTAssertEqual(refreshed.readiness?.privatePaymentsRestored, true) + } + + /// Restored payments and an open store need no retry: one read. + @MainActor + func testShouldNotAskTheWalletToRetryWhenThePaymentsAreRestored() { + var configures = 0 + var reads = 0 + let refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: readiness(restored: true), storeFailure: nil, + readReadiness: { reads += 1; return (self.readiness(restored: true), nil) }, + configureAgain: { configures += 1; return nil }) + XCTAssertEqual(configures, 0) + XCTAssertEqual(reads, 1) + XCTAssertEqual(refreshed.readiness?.privatePaymentsRestored, true) + } + + /// A store that did not open is opened again on a refresh, whatever the + /// readiness says, and its failure clears once it opens. + @MainActor + func testShouldOpenTheStoreAgainWhileAStoreFailureIsRecorded() { + var configures = 0 + let refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: nil, storeFailure: "disk full", + readReadiness: { (nil, nil) }, + configureAgain: { configures += 1; return nil }) + XCTAssertEqual(configures, 1) + XCTAssertNil(refreshed.storeFailure) + } + + /// A restoration the wallet deferred behind a scan that holds the store + /// for minutes: the view keeps refreshing past the first minute (every + /// 3 s for 20 refreshes, then every 15 s, with no last one), and the + /// refresh after the deferred restoration completes re-enables submission + /// and schedules no more. + @MainActor + func testShouldKeepRefreshingWhileARestorationStaysDeferred() async { + let contact = Data(repeating: 1, count: 32) + var deferredDone = false + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + let read = { () -> (readiness: PrivateContactReadiness?, restoreFailure: String?) in + (self.readiness(restored: deferredDone), nil) + } + var pauses: [Duration] = [] + var refreshes = 0 + // Well past the first minute: 200 automatic refreshes, about 46 minutes. + for attempt in 0..<200 { + let refreshed = PrivatePaymentsRecovery.refresh( + lastReadiness: snapshot.readiness, storeFailure: nil, readReadiness: read, + configureAgain: { nil }) + snapshot.recordReadiness(refreshed.readiness, restoreFailure: refreshed.restoreFailure) + refreshes += 1 + if attempt == 150 { deferredDone = true } + let due = await PrivatePaymentsRecovery.waitForRecheck( + after: snapshot.readiness, attempt: attempt, sleep: { pauses.append($0) }) + if !due { break } + } + XCTAssertEqual(refreshes, 152, "it kept refreshing until the restoration completed") + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual(pauses.count, 151, "no pause once the payments read restored") + XCTAssertEqual(Array(pauses.prefix(20)), Array(repeating: .seconds(3), count: 20)) + XCTAssertEqual(Set(pauses.dropFirst(20)), [.seconds(15)]) + } + + /// The timer stops when the payments read restored, before any read + /// succeeded, and when the view goes away (its task's sleep is cut + /// short), however many refreshes came before. + @MainActor + func testShouldStopRefreshingWhenRestoredOrWhenTheViewGoesAway() async { + var slept = false + let restored = await PrivatePaymentsRecovery.waitForRecheck( + after: readiness(restored: true), attempt: 0, sleep: { _ in slept = true }) + XCTAssertFalse(restored) + XCTAssertFalse(slept, "nothing is due once restored") + let unread = await PrivatePaymentsRecovery.waitForRecheck( + after: nil, attempt: 0, sleep: { _ in slept = true }) + XCTAssertFalse(unread) + XCTAssertFalse(slept) + let dismissed = await PrivatePaymentsRecovery.waitForRecheck( + after: readiness(restored: false), attempt: 500, + sleep: { _ in throw CancellationError() }) + XCTAssertFalse(dismissed, "a view that went away refreshes no more") + } + + func testShouldAcceptACollisionPrivatelyWhenSendPrivatelyIsOn() { + let accept = CollisionAccept.of(sendPrivately: true) + XCTAssertEqual(accept, .privateReply) + XCTAssertEqual(accept.buttonTitle, "Accept privately") + XCTAssertEqual( + accept.message, + "This person already sent you a request. Accept it with a private reply instead? " + + "The reply is paid from this wallet's shielded balance, and no public request " + + "names you as its sender." + ) + } + + func testShouldAcceptACollisionInKindWhenSendPrivatelyIsOff() { + let accept = CollisionAccept.of(sendPrivately: false) + XCTAssertEqual(accept, .replyInKind) + XCTAssertEqual(accept.buttonTitle, "Accept") + XCTAssertEqual(accept.message, "This person already sent you a request. Accept it instead?") + } + + func testShouldOfferARetryForAnOrdinaryFailure() { + let error = PlatformWalletError.shieldedBroadcastFailed("rejected by the relay") + XCTAssertEqual( + ContactRequestSubmissionOutcome.of(error), + .failed(error.localizedDescription) + ) + } + + func testShouldStayQuietWhenTheNetworkDoesNotServeThePrivateStoreYet() { + XCTAssertNil(PrivateContactRefreshNotice.notice( + for: PlatformWalletError.protocolVersionNotActive("needs protocol version 15") + )) + } + + func testShouldShowAPrivateRefreshThatFailed() { + let error = PlatformWalletError.walletOperation("no node answered") + XCTAssertEqual( + PrivateContactRefreshNotice.notice(for: error), + "Private requests could not be read: \(error.localizedDescription)" + ) + } + + func testShouldShowRequestsThatWereReadButNotSaved() { + XCTAssertNil(PrivateContactRefreshNotice.notice(unpersistedIdentityCount: 0)) + XCTAssertEqual( + PrivateContactRefreshNotice.notice(unpersistedIdentityCount: 2), + "Private requests for 2 identities were read but not saved. Pull to refresh again." + ) + } + + /// Code 76: an earlier public request to the pair awaits its outcome, so + /// the wallet signed nothing. Not a failure to retry: the contact shows + /// "being checked" and no submission is offered. + func testShouldShowARefusedUnconfirmedPublicRequestAsBeingChecked() { + let contact = Data(repeating: 1, count: 32) + let outcome = ContactRequestSubmissionOutcome.of( + PlatformWalletError.publicContactRequestUnconfirmed("an earlier request awaits its outcome")) + XCTAssertEqual(outcome, .publicRequestUnconfirmed) + + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(privatelyHeld([]), for: [contact]) + snapshot.recordOutcome(outcome, for: contact) + XCTAssertTrue(snapshot.isAwaitingOutcome(contact)) + XCTAssertFalse(snapshot.isPending(contact), "not a private request pending") + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual(rowMessage(snapshot, contact, error: nil), + ContactRequestSubmissionOutcome.publicRequestUnconfirmedMessage) + } + + /// The public accept, reload and retry sequence: an accept that may have + /// gone through (20) holds the row at once; a reload whose sync did not + /// settle it reads the wallet's public hold, with nothing held privately, + /// and keeps the row held; a second accept is not offered, and one made + /// anyway is refused (76) with no error to retry; a failed read keeps it + /// held; once the sync settles the hold the read frees the pair and the + /// accept comes back. + func testShouldHoldAPublicAcceptThatMayHaveGoneThroughThroughAReloadAndARetryUntilTheWalletSettlesIt() { + let contact = Data(repeating: 1, count: 32) + var wallet = FakeContactRequestHolds() + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.record(wallet.read([contact]), for: [contact]) + XCTAssertTrue(snapshot.allowsSubmission(to: contact), "the accept is offered") + + // The accept broadcasts and its result cannot be confirmed: the + // wallet holds the pair, the signed transition kept. + wallet.publicUnconfirmed.insert(contact) + let accepted = ContactRequestSubmissionOutcome.of( + PlatformWalletError.transactionBroadcastUnconfirmed("result could not be confirmed")) + XCTAssertEqual(accepted, .mayHaveGoneThrough) + snapshot.recordOutcome(accepted, for: contact) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual(rowMessage(snapshot, contact, error: nil), + ContactRequestSubmissionOutcome.publicRequestUnconfirmedMessage) + + // A reload whose sync did not settle it: nothing is held privately, + // the public hold stands, and the row stays held. + let reload = wallet.read([contact]) + XCTAssertEqual(reload?.privatelyHeld, [], "the private-pending read is empty") + snapshot.record(reload, for: [contact]) + XCTAssertTrue(snapshot.isAwaitingOutcome(contact)) + XCTAssertFalse(snapshot.allowsSubmission(to: contact), "a second accept is not offered") + XCTAssertEqual(rowMessage(snapshot, contact, error: nil), + ContactRequestSubmissionOutcome.publicRequestUnconfirmedMessage) + + // A second accept made anyway is refused before anything is signed. + let retried = ContactRequestSubmissionOutcome.of( + PlatformWalletError.publicContactRequestUnconfirmed("an earlier request awaits its outcome")) + snapshot.recordOutcome(retried, for: contact) + snapshot.record(wallet.read([contact]), for: [contact]) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual(rowMessage(snapshot, contact, error: nil), + ContactRequestSubmissionOutcome.publicRequestUnconfirmedMessage, + "a refusal while held is not an error to retry") + + // A read that fails keeps the row held, as the last read found it. + snapshot.record(nil, for: [contact]) + XCTAssertFalse(snapshot.allowsSubmission(to: contact)) + XCTAssertEqual(rowMessage(snapshot, contact, error: nil), + ContactRequestSubmissionOutcome.publicRequestUnconfirmedMessage) + + // The sync settles the hold (a proved-used nonce frees the pair; a + // request found is recorded as sent and the row leaves the list): + // the next read says free and the accept comes back. + wallet.publicUnconfirmed.remove(contact) + snapshot.record(wallet.read([contact]), for: [contact]) + XCTAssertFalse(snapshot.isAwaitingOutcome(contact)) + XCTAssertTrue(snapshot.allowsSubmission(to: contact)) + XCTAssertNil(rowMessage(snapshot, contact, error: nil)) + } + + /// An unconfirmed submission marks only its own contact, and a read that + /// does not cover it leaves the mark. + func testShouldKeepAnUnconfirmedSubmissionAReadDidNotCover() { + let unconfirmed = Data(repeating: 1, count: 32) + let other = Data(repeating: 2, count: 32) + var snapshot = PrivateRepliesPendingSnapshot() + snapshot.recordOutcome(.mayHaveGoneThrough, for: unconfirmed) + snapshot.record(privatelyHeld([]), for: [other]) + XCTAssertTrue(snapshot.isAwaitingOutcome(unconfirmed)) + XCTAssertTrue(snapshot.allowsSubmission(to: other)) + } + + /// The views' read covers both holds for every contact: the private one + /// and the public one. A sender the wallet does not manage (code 7) holds + /// nothing; any other failed read is nil, never "nothing held". + func testShouldReadBothHoldsAndTellAnUnmanagedIdentityFromAFailedRead() { + let privately = Data(repeating: 1, count: 32) + let publicly = Data(repeating: 2, count: 32) + let free = Data(repeating: 3, count: 32) + var wallet = FakeContactRequestHolds() + wallet.privatelyHeld = [privately] + wallet.publicUnconfirmed = [publicly] + XCTAssertEqual( + wallet.read([privately, publicly, free]), + ContactRequestHolds(privatelyHeld: [privately], publicUnconfirmed: [publicly])) + + wallet.failure = PlatformWalletError.identityNotFound("not managed by this wallet") + XCTAssertEqual(wallet.read([privately]), ContactRequestHolds()) + + wallet.failure = PlatformWalletError.walletOperation("read failed") + XCTAssertNil(wallet.read([privately])) + } +} + +/// A read of both holds that found `contacts` held for a private request and +/// none awaiting a public request's outcome. +private func privatelyHeld(_ contacts: Set) -> ContactRequestHolds { + ContactRequestHolds(privatelyHeld: contacts) +} + +/// The message the views show for `contact`, from `snapshot`. +private func rowMessage(_ snapshot: PrivateRepliesPendingSnapshot, _ contact: Data, error: String?) -> String? { + ContactRequestSubmissionOutcome.rowMessage( + pending: snapshot.isPending(contact), + awaitingOutcome: snapshot.isAwaitingOutcome(contact), + restoring: snapshot.isRestoringPrivatePayments, + restoreFailure: snapshot.restoreFailure, + unavailable: snapshot.isUnavailable, + error: error) +} + +/// The wallet's two per-contact holds, read through the views' helper +/// (`contactRequestHolds`) as the wallet answers them. +private struct FakeContactRequestHolds { + var privatelyHeld: Set = [] + var publicUnconfirmed: Set = [] + /// Thrown by every read when set. + var failure: Error? + + func read(_ contactIds: [Data]) -> ContactRequestHolds? { + contactRequestHolds( + contactIds: contactIds, + privatePairHeld: { contact in + if let failure { throw failure } + return privatelyHeld.contains(contact) + }, + publicUnconfirmed: { contact in + if let failure { throw failure } + return publicUnconfirmed.contains(contact) + } + ) + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index 5b509c904e1..84e538c521a 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -91,13 +91,13 @@ final class DashPayContactPersistenceTests: XCTestCase { ignored: [PlatformWalletPersistenceHandler.ContactIgnoredSenderSnapshot] = [] ) { handler.beginChangeset(walletId: walletId) - handler.persistContacts( + XCTAssertNoThrow(try handler.persistContacts( walletId: walletId, upserts: upserts, removedSent: removedSent, removedIncoming: removedIncoming, ignored: ignored - ) + )) handler.endChangeset(walletId: walletId, success: true) } @@ -283,10 +283,13 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertTrue(try XCTUnwrap(rows.first).paymentChannelBroken) } - /// A contact upsert whose owner identity Swift hasn't seen yet is - /// skipped (next sync round replays it) — it must not crash or - /// insert an orphan row. - func testUpsertSkipsUnknownOwnerIdentity() throws { + /// A contact upsert whose owner identity is not persisted fails the + /// round instead of being skipped: the store declares the private + /// contact request scan state, so an acknowledged round without the + /// row would let the wallet store a read position past it. The callback + /// reports the failure, the rolled-back round leaves nothing, and once + /// the owner is persisted the same upsert (the next scan's) lands. + func testUnknownOwnerIdentityFailsTheRound() throws { let unknownOwner = Data(repeating: 0x77, count: 32) var snapshot = makeSnapshot(isOutgoing: false) snapshot = .init( @@ -308,9 +311,47 @@ final class DashPayContactPersistenceTests: XCTestCase { contactAccountLabel: snapshot.contactAccountLabel, contactAcceptedAccounts: snapshot.contactAcceptedAccounts ) + handler.beginChangeset(walletId: walletId) + XCTAssertThrowsError(try handler.persistContacts( + walletId: walletId, upserts: [snapshot], removedSent: [], removedIncoming: [], ignored: [])) + // The callback's failure makes Rust end the round unsuccessfully. + handler.endChangeset(walletId: walletId, success: false) + XCTAssertEqual(try fetchContactRows().count, 0) + + // The callback shim reports it as a failed callback. + let callbacks = handler.makeCallbacks() + defer { Unmanaged.fromOpaque(callbacks.context!).release() } + let contactsFn = try XCTUnwrap(callbacks.on_persist_contacts_fn) + var row = ContactRequestFFI() + row.owner_id = Self.tuple32(unknownOwner) + row.contact_id = Self.tuple32(contactId) + let rc = walletId.withUnsafeBytes { wid in + withUnsafePointer(to: &row) { rowPtr in + contactsFn(callbacks.context, wid.bindMemory(to: UInt8.self).baseAddress, + rowPtr, 1, nil, 0, nil, 0, nil, 0) + } + } + XCTAssertNotEqual(rc, 0) + + // A later scan, once the owner identity is persisted, stores it. + let context = ModelContext(container) + context.insert(PersistentIdentity(identityId: unknownOwner, isLocal: false, network: .testnet)) + try context.save() applyContacts(upserts: [snapshot]) + XCTAssertEqual(try fetchContactRows().map(\.ownerIdentityId), [unknownOwner]) + } - XCTAssertEqual(try fetchContactRows().count, 0) + /// An ignore whose owner identity is not persisted fails the round too. + func testIgnoreForAnUnknownOwnerFailsTheRound() throws { + handler.beginChangeset(walletId: walletId) + XCTAssertThrowsError(try handler.persistContacts( + walletId: walletId, upserts: [], removedSent: [], removedIncoming: [], + ignored: [.init( + ownerIdentityId: Data(repeating: 0x77, count: 32), + senderIdentityId: otherSenderId, + isIgnored: true)])) + handler.endChangeset(walletId: walletId, success: false) + XCTAssertEqual(try fetchIgnoredRows().count, 0) } // MARK: Ignored senders (per-sender mute, local-only) @@ -665,7 +706,7 @@ final class DashPayContactPersistenceTests: XCTestCase { func testPaymentRefreshDoesNotCommitAnOpenChangesetRound() throws { // Open a round and stage an (uncommitted) contact write. handler.beginChangeset(walletId: walletId) - handler.persistContacts( + try handler.persistContacts( walletId: walletId, upserts: [makeSnapshot(isOutgoing: false)], removedSent: [], diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index f18b44a9fce..b3bbb2a7d64 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -459,6 +459,187 @@ final class ErrorHandlingTests: XCTestCase { ) } + func testShouldRouteAPrivatelyReceivedRequestByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_REQUEST_NEEDS_PRIVATE_REPLY + ) + XCTAssertEqual(code, .errorPrivateContactRequestNeedsPrivateReply) + XCTAssertEqual(code.rawValue, 68) + let detail = "the contact requests with 9fRYTJZW came or went privately; " + + "reply to or rotate with it privately" + let error = PlatformWalletError(code: code, message: detail) + guard case .privateContactRequestNeedsPrivateReply(let message) = error else { + return XCTFail("lost typed private-reply error") + } + XCTAssertEqual(message, detail) + XCTAssertEqual(error.errorDescription, detail) + } + + func testShouldTellAPrivateReplyOnABuildWithoutShieldedSupportByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_BUILD_REQUIRED + ) + XCTAssertEqual(code, .errorShieldedBuildRequired) + XCTAssertEqual(code.rawValue, 69) + let detail = "this contact request needs a private reply, which is paid " + + "from the shielded pool; this build has no shielded support" + let error = PlatformWalletError(code: code, message: detail) + guard case .shieldedBuildRequired(let message) = error else { + return XCTFail("lost typed shielded-build error") + } + XCTAssertEqual(message, detail) + XCTAssertEqual(error.errorDescription, detail) + } + + func testShouldTellARequestTheNetworkDoesNotServeYetByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PROTOCOL_VERSION_NOT_ACTIVE + ) + XCTAssertEqual(code, .errorProtocolVersionNotActive) + XCTAssertEqual(code.rawValue, 70) + let detail = "get_private_document_entries needs protocol version 15; " + + "the network is proven at protocol version 14" + let error = PlatformWalletError(code: code, message: detail) + guard case .protocolVersionNotActive(let message) = error else { + return XCTFail("lost typed protocol-version error") + } + XCTAssertEqual(message, detail) + } + + func testShouldReportAPendingPrivateRequestByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_REQUEST_PENDING + ) + XCTAssertEqual(code, .errorPrivateContactRequestPending) + XCTAssertEqual(code.rawValue, 71) + let detail = "a private contact request to 9fRYTJZW is in flight or not yet read " + + "back from the store; sync private contact requests to settle it" + let error = PlatformWalletError(code: code, message: detail) + guard case .privateContactRequestPending(let message) = error else { + return XCTFail("lost typed pending error") + } + XCTAssertEqual(message, detail) + } + + /// Unrestored private payments are the wallet's hold, not one contact's + /// pending request: their own code and typed case, apart from 71. + func testShouldReportUnrestoredPrivatePaymentsByTheirOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_PAYMENTS_NOT_RESTORED + ) + XCTAssertEqual(code, .errorPrivateContactPaymentsNotRestored) + XCTAssertEqual(code.rawValue, 72) + let detail = "the wallet's private payments are not restored from the shielded store yet" + let error = PlatformWalletError(code: code, message: detail) + guard case .privateContactPaymentsNotRestored(let message) = error else { + return XCTFail("lost typed not-restored error") + } + XCTAssertEqual(message, detail) + } + + /// A store that cannot keep a private payment's recovery state has its + /// own code and typed case. + func testShouldReportUnsupportedPrivateContactRecoveryByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_RECOVERY_UNSUPPORTED + ) + XCTAssertEqual(code, .errorPrivateContactRecoveryUnsupported) + XCTAssertEqual(code.rawValue, 73) + let detail = "the persister does not keep the private contact request scan state atomically" + guard case .privateContactRecoveryUnsupported(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed recovery-unsupported error") + } + XCTAssertEqual(message, detail) + } + + /// A private store read that did not finish before a contact request was + /// decided has its own code and typed case, apart from a pending request + /// (71): nothing was reserved, and calling again continues the read. + func testShouldReportAnUnfinishedPrivateStoreReadByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_STORE_NOT_READ + ) + XCTAssertEqual(code, .errorPrivateContactStoreNotRead) + XCTAssertEqual(code.rawValue, 74) + let detail = "the private contact request store was not read to its end for 9fRYTJZW" + guard case .privateContactStoreNotRead(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed store-not-read error") + } + XCTAssertEqual(message, detail) + } + + /// An SDK pinned below the protocol version a request needs has its own + /// code and typed case, apart from a network below it (70), which lifts by + /// itself. + func testShouldReportAnSdkPinnedBelowTheProtocolVersionByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SDK_PINNED_BELOW_PROTOCOL_VERSION + ) + XCTAssertEqual(code, .errorSdkPinnedBelowProtocolVersion) + XCTAssertEqual(code.rawValue, 75) + let detail = "get_private_document_entries needs protocol version 15; " + + "the SDK is pinned at protocol version 14" + guard case .sdkPinnedBelowProtocolVersion(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed pinned-SDK error") + } + XCTAssertEqual(message, detail) + } + + /// A public contact request whose outcome is unconfirmed holds the pair by + /// its own code and typed case, apart from a private request pending (71). + func testShouldReportAnUnconfirmedPublicRequestByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PUBLIC_CONTACT_REQUEST_UNCONFIRMED + ) + XCTAssertEqual(code, .errorPublicContactRequestUnconfirmed) + XCTAssertEqual(code.rawValue, 76) + let detail = "a public contact request to 9fRYTJZW was broadcast and its outcome is not proved" + guard case .publicContactRequestUnconfirmed(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed public-unconfirmed error") + } + XCTAssertEqual(message, detail) + } + + func testShouldReadEveryFieldOfThePrivateContactReadiness() { + var ffi = PrivateContactReadinessFFI() + ffi.private_payments_restored = false + ffi.private_store_read = true + ffi.unresolved_private_payment = true + ffi.private_payments_restore_failed = true + XCTAssertEqual( + PrivateContactReadiness(ffi: ffi), + PrivateContactReadiness( + privatePaymentsRestored: false, + privateStoreRead: true, + unresolvedPrivatePayment: true, + privatePaymentsRestoreFailed: true)) + // Each flag reaches its own field: clearing only the failure flag + // reads as a payment not restored yet. + ffi.private_payments_restore_failed = false + XCTAssertFalse(PrivateContactReadiness(ffi: ffi).privatePaymentsRestoreFailed) + XCTAssertFalse(PrivateContactReadiness(ffi: ffi).privatePaymentsRestored) + } + + func testShouldReadEveryFieldOfAPrivateContact() { + var ffi = PrivateContactFFI() + ffi.received_privately = true + ffi.has_shielded_address = true + withUnsafeMutableBytes(of: &ffi.shielded_address) { raw in + for i in raw.indices { raw[i] = UInt8(i) } + } + let info = PrivateContactInfo(ffi: ffi) + XCTAssertTrue(info.receivedPrivately) + XCTAssertFalse(info.sentPrivately) + XCTAssertEqual(info.shieldedAddress, Data((0..<43).map { UInt8($0) })) + + ffi.has_shielded_address = false + XCTAssertNil(PrivateContactInfo(ffi: ffi).shieldedAddress) + } + func testShouldPreserveShieldedIdentityDebitPendingFFIResult() { let code = PlatformWalletResultCode( ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_IDENTITY_DEBIT_PENDING diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift index f6c0818f73c..036693cab39 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift @@ -71,6 +71,10 @@ final class InvitationPersistenceTests: XCTestCase { // Shielded recipients: the handler wires both recipient slots and // lands the bytes on `PersistentAssetLock.shieldedRecipientRaw43`. | PlatformWalletPersistenceCapabilities.assetLockShieldedRecipients + // Private contact request scan state: the handler wires the + // persist/load/free trio onto `PersistentPrivateContactRequestsPosition` + // and `PersistentPrivateShieldedAddress`. + | PlatformWalletPersistenceCapabilities.privateContactRequestScanState XCTAssertEqual( capabilities.version, diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PrivateContactScanStatePersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PrivateContactScanStatePersistenceTests.swift new file mode 100644 index 00000000000..42f439a0bb6 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PrivateContactScanStatePersistenceTests.swift @@ -0,0 +1,374 @@ +import XCTest +import SwiftData +import DashSDKFFI +@testable import SwiftDashSDK + +/// The private contact request scan state (read positions and private +/// contacts' shielded addresses) round-trips through SwiftData and the +/// persistence extension's C shims. +final class PrivateContactScanStatePersistenceTests: XCTestCase { + private let walletId = Data(repeating: 42, count: 32) + private let owner = Data(repeating: 7, count: 32) + private let contact = Data(repeating: 5, count: 32) + private let otherContact = Data(repeating: 6, count: 32) + + private typealias Position = PlatformWalletPersistenceHandler.PrivateContactRequestsPositionRow + private typealias Address = PlatformWalletPersistenceHandler.PrivateShieldedAddressRow + private typealias AddressKey = PlatformWalletPersistenceHandler.PrivateShieldedAddressKey + + private func makeHandler() throws -> (ModelContainer, PlatformWalletPersistenceHandler) { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + context.insert(PersistentWallet(walletId: walletId, network: .testnet)) + try context.save() + return (container, PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet)) + } + + private func round( + _ handler: PlatformWalletPersistenceHandler, + positions: [Position] = [], + addresses: [Address] = [], + removed: [AddressKey] = [], + cleared: [Data] = [], + success: Bool = true + ) throws { + handler.beginChangeset(walletId: walletId) + try handler.persistPrivateContactScanState( + walletId: walletId, positions: positions, addresses: addresses, + removedAddresses: removed, clearedIdentities: cleared) + XCTAssertEqual(handler.endChangeset(walletId: walletId, success: success), success) + } + + func testShouldStoreReplaceAndRemoveTheScanStateWithItsRound() throws { + let (_, handler) = try makeHandler() + let fingerprint = Data(repeating: 3, count: 32) + try round( + handler, + positions: [.init(identityId: owner, position: 12, keyFingerprint: fingerprint)], + addresses: [ + .init(ownerId: owner, contactId: contact, address: Data(repeating: 9, count: 43)), + .init(ownerId: owner, contactId: otherContact, address: Data(repeating: 8, count: 43)), + ]) + var stored = try handler.loadPrivateContactScanState(walletId: walletId) + XCTAssertEqual(stored.positions, [.init(identityId: owner, position: 12, keyFingerprint: fingerprint)]) + XCTAssertEqual(Set(stored.addresses.map(\.contactId)), [contact, otherContact]) + + // A rewind writes the lower position; a tombstone removes one address. + try round( + handler, + positions: [.init(identityId: owner, position: 0, keyFingerprint: fingerprint)], + removed: [.init(ownerId: owner, contactId: otherContact)]) + stored = try handler.loadPrivateContactScanState(walletId: walletId) + XCTAssertEqual(stored.positions.map(\.position), [0]) + XCTAssertEqual(stored.addresses, [ + .init(ownerId: owner, contactId: contact, address: Data(repeating: 9, count: 43)), + ]) + + // A rolled-back round leaves the stored state as it was. + try round( + handler, + positions: [.init(identityId: owner, position: 40, keyFingerprint: fingerprint)], + success: false) + XCTAssertEqual(try handler.loadPrivateContactScanState(walletId: walletId).positions.map(\.position), [0]) + + // The unresolved-payment marker is stored with the position and + // cleared by a later round. + try round(handler, positions: [.init( + identityId: owner, position: 0, keyFingerprint: fingerprint, privatePaymentsUnresolved: true)]) + XCTAssertEqual( + try handler.loadPrivateContactScanState(walletId: walletId).positions.map(\.privatePaymentsUnresolved), + [true]) + try round(handler, positions: [.init(identityId: owner, position: 0, keyFingerprint: fingerprint)]) + XCTAssertEqual( + try handler.loadPrivateContactScanState(walletId: walletId).positions.map(\.privatePaymentsUnresolved), + [false]) + + // A full-width position survives the signed SQLite column. + try round(handler, positions: [.init(identityId: owner, position: .max, keyFingerprint: fingerprint)]) + XCTAssertEqual(try handler.loadPrivateContactScanState(walletId: walletId).positions.map(\.position), [.max]) + } + + func testShouldClearTheScanStateOfARemovedIdentity() throws { + let (_, handler) = try makeHandler() + let survivor = Data(repeating: 1, count: 32) + try round( + handler, + positions: [ + .init(identityId: owner, position: 12, keyFingerprint: Data(repeating: 3, count: 32)), + .init(identityId: survivor, position: 4, keyFingerprint: Data(repeating: 2, count: 32)), + ], + addresses: [ + .init(ownerId: owner, contactId: contact, address: Data(repeating: 9, count: 43)), + .init(ownerId: survivor, contactId: contact, address: Data(repeating: 1, count: 43)), + ]) + try round(handler, cleared: [owner]) + let stored = try handler.loadPrivateContactScanState(walletId: walletId) + XCTAssertEqual(stored.positions.map(\.identityId), [survivor]) + XCTAssertEqual(stored.addresses.map(\.ownerId), [survivor]) + } + + func testShouldScopeTheScanStateByWalletAndNetworkAndPurgeItWithTheWallet() throws { + let (container, handler) = try makeHandler() + try round( + handler, + positions: [.init(identityId: owner, position: 12, keyFingerprint: Data(repeating: 3, count: 32))], + addresses: [.init(ownerId: owner, contactId: contact, address: Data(repeating: 9, count: 43))]) + XCTAssertTrue(try handler.loadPrivateContactScanState(walletId: Data(repeating: 43, count: 32)) + .positions.isEmpty) + let mainnet = PlatformWalletPersistenceHandler(modelContainer: container, network: .mainnet) + XCTAssertTrue(try mainnet.loadPrivateContactScanState(walletId: walletId).positions.isEmpty) + + try handler.deleteWalletData(walletId: walletId) + let context = ModelContext(container) + XCTAssertEqual(try context.fetchCount(FetchDescriptor()), 0) + XCTAssertEqual(try context.fetchCount(FetchDescriptor()), 0) + } + + /// A position record marked unresolved survives its wallet's purge and + /// is listed for the load to hand back as retained; an unmarked record + /// and every address go with the wallet; a cleared record stored later + /// for the same wallet and identity replaces it, so the next purge + /// removes it. + func testShouldKeepAMarkedRecordThroughItsWalletsPurgeUntilAClearedRecordReplacesIt() throws { + let (container, handler) = try makeHandler() + let unmarked = Data(repeating: 1, count: 32) + let fingerprint = Data(repeating: 3, count: 32) + try round( + handler, + positions: [ + .init(identityId: owner, position: 12, keyFingerprint: fingerprint, + privatePaymentsUnresolved: true), + .init(identityId: unmarked, position: 4, keyFingerprint: fingerprint), + ], + addresses: [.init(ownerId: owner, contactId: contact, address: Data(repeating: 9, count: 43))]) + XCTAssertEqual(try handler.loadPrivateContactScanStateWalletIds(), [walletId]) + + try handler.deleteWalletData(walletId: walletId) + let context = ModelContext(container) + XCTAssertEqual(try context.fetchCount(FetchDescriptor()), 0) + var kept = try handler.loadPrivateContactScanState(walletId: walletId) + XCTAssertEqual(kept.positions, [.init( + identityId: owner, position: 12, keyFingerprint: fingerprint, privatePaymentsUnresolved: true)], + "only the marked record outlives the wallet") + XCTAssertTrue(kept.addresses.isEmpty) + XCTAssertEqual(try handler.loadPrivateContactScanStateWalletIds(), [walletId], + "the removed wallet is still listed for its kept record") + + // The wallet registered again stores the record cleared. + context.insert(PersistentWallet(walletId: walletId, network: .testnet)) + try context.save() + try round(handler, positions: [.init(identityId: owner, position: 0, keyFingerprint: fingerprint)]) + kept = try handler.loadPrivateContactScanState(walletId: walletId) + XCTAssertEqual(kept.positions.map(\.privatePaymentsUnresolved), [false]) + try handler.deleteWalletData(walletId: walletId) + XCTAssertEqual(try ModelContext(container).fetchCount( + FetchDescriptor()), 0) + XCTAssertTrue(try handler.loadPrivateContactScanStateWalletIds().isEmpty) + } + + /// A handler configured with no network, as `configure(sdkPointer: + /// modelContainer:network:)` makes by default: a marked record of a + /// mainnet wallet, stored under mainnet, still reads back after the + /// wallet's removal, through the wallet list and the per-wallet load and + /// through their C shims, rather than reading as absent under a guessed + /// testnet scope. A testnet-scoped handler still does not see it. + func testShouldHandBackAKeptMainnetRecordToAHandlerWithNoNetwork() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + context.insert(PersistentWallet(walletId: walletId, network: .mainnet)) + try context.save() + let handler = PlatformWalletPersistenceHandler(modelContainer: container) + let fingerprint = Data(repeating: 3, count: 32) + let marked = Position( + identityId: owner, position: 12, keyFingerprint: fingerprint, privatePaymentsUnresolved: true) + try round(handler, positions: [marked]) + XCTAssertEqual( + try ModelContext(container).fetch(FetchDescriptor()) + .map(\.networkRaw), + [Network.mainnet.rawValue], + "stored under the wallet's own network") + + try handler.deleteWalletData(walletId: walletId) + XCTAssertEqual(try handler.loadPrivateContactScanStateWalletIds(), [walletId]) + XCTAssertEqual(try handler.loadPrivateContactScanState(walletId: walletId).positions, [marked]) + + let ext = handler.makePersistenceCallbacksExtension() + let list = try XCTUnwrap(ext.on_load_private_contact_scan_state_wallets_fn) + let freeList = try XCTUnwrap(ext.on_load_private_contact_scan_state_wallets_free_fn) + let load = try XCTUnwrap(ext.on_load_private_contact_scan_state_fn) + let free = try XCTUnwrap(ext.on_load_private_contact_scan_state_free_fn) + let shimContext = Unmanaged.passUnretained(handler).toOpaque() + var ids: UnsafePointer? + var idsCount: UInt = 0 + XCTAssertEqual(list(shimContext, &ids, &idsCount), 0) + XCTAssertEqual(idsCount, 1) + freeList(shimContext, ids, idsCount) + var positions: UnsafePointer? + var positionsCount: UInt = 0 + var addresses: UnsafePointer? + var addressesCount: UInt = 0 + let rc = walletId.withUnsafeBytes { wallet in + load(shimContext, wallet.bindMemory(to: UInt8.self).baseAddress, + &positions, &positionsCount, &addresses, &addressesCount) + } + XCTAssertEqual(rc, 0) + XCTAssertEqual(positionsCount, 1) + XCTAssertTrue(try XCTUnwrap(positions).pointee.private_payments_unresolved) + free(shimContext, positions, positionsCount, addresses, addressesCount) + + let testnet = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) + XCTAssertTrue(try testnet.loadPrivateContactScanStateWalletIds().isEmpty) + XCTAssertTrue(try testnet.loadPrivateContactScanState(walletId: walletId).positions.isEmpty) + } + + /// A handler with no network and no wallet row to take one from refuses + /// to store scan state rather than file it under a guessed network. + func testShouldRefuseToStoreScanStateWithNoNetworkToStoreItUnder() throws { + let container = try DashModelContainer.createInMemory() + let handler = PlatformWalletPersistenceHandler(modelContainer: container) + handler.beginChangeset(walletId: walletId) + XCTAssertThrowsError(try handler.persistPrivateContactScanState( + walletId: walletId, + positions: [.init(identityId: owner, position: 1, keyFingerprint: Data(repeating: 3, count: 32))], + addresses: [], removedAddresses: [], clearedIdentities: [])) + _ = handler.endChangeset(walletId: walletId, success: false) + } + + /// The wallet-list shim hands Rust the listed ids as 32-byte rows and + /// its free shim releases them; an empty list crosses as null. + func testShouldListTheWalletsWithScanStateThroughTheCallbackShims() throws { + let (_, handler) = try makeHandler() + let ext = handler.makePersistenceCallbacksExtension() + let list = try XCTUnwrap(ext.on_load_private_contact_scan_state_wallets_fn) + let free = try XCTUnwrap(ext.on_load_private_contact_scan_state_wallets_free_fn) + let context = Unmanaged.passUnretained(handler).toOpaque() + + var ids: UnsafePointer? + var count: UInt = 7 + XCTAssertEqual(list(context, &ids, &count), 0) + XCTAssertNil(ids) + XCTAssertEqual(count, 0) + + try round(handler, positions: [.init( + identityId: owner, position: 1, keyFingerprint: Data(repeating: 3, count: 32), + privatePaymentsUnresolved: true)]) + try handler.deleteWalletData(walletId: walletId) + XCTAssertEqual(list(context, &ids, &count), 0) + XCTAssertEqual(count, 1) + var first = try XCTUnwrap(ids).pointee + XCTAssertEqual(Swift.withUnsafeBytes(of: &first) { Data($0) }, walletId) + free(context, ids, count) + } + + /// A stored row that cannot cross the ABI fails the load instead of + /// handing back the rest without it: a valid position beside a 42-byte + /// address would otherwise resume past the entry that carried it. + func testShouldFailTheLoadOnAStoredRowThatCannotCrossTheABI() throws { + let (container, handler) = try makeHandler() + try round( + handler, + positions: [.init(identityId: owner, position: 12, keyFingerprint: Data(repeating: 3, count: 32))]) + let context = ModelContext(container) + context.insert(PersistentPrivateShieldedAddress( + networkRaw: Network.testnet.rawValue, walletId: walletId, ownerId: owner, + contactId: contact, address: Data(repeating: 9, count: 42))) + try context.save() + + let ext = handler.makePersistenceCallbacksExtension() + let load = try XCTUnwrap(ext.on_load_private_contact_scan_state_fn) + let context_ = Unmanaged.passUnretained(handler).toOpaque() + var positions: UnsafePointer? + var positionsCount: UInt = 0 + var addresses: UnsafePointer? + var addressesCount: UInt = 0 + let rc = walletId.withUnsafeBytes { wallet in + load(context_, wallet.bindMemory(to: UInt8.self).baseAddress, + &positions, &positionsCount, &addresses, &addressesCount) + } + XCTAssertNotEqual(rc, 0) + XCTAssertNil(positions) + XCTAssertNil(addresses) + XCTAssertEqual(positionsCount + addressesCount, 0) + } + + func testShouldRefuseAScanStateWriteOutsideAChangeset() throws { + let (_, handler) = try makeHandler() + XCTAssertThrowsError(try handler.persistPrivateContactScanState( + walletId: walletId, + positions: [.init(identityId: owner, position: 1, keyFingerprint: Data(repeating: 3, count: 32))], + addresses: [], removedAddresses: [], clearedIdentities: [])) + } + + /// The C shims Rust calls: a persist through the extension's slot is + /// read back through its load slot, and the free slot returns the + /// arrays. The capability is declared alongside them. + func testShouldDeclareTheCapabilityAndRoundTripThroughTheCallbackShims() throws { + let (_, handler) = try makeHandler() + XCTAssertNotEqual( + handler.makePersistenceCapabilities().bits + & PlatformWalletPersistenceCapabilities.privateContactRequestScanState, 0) + // Bit 15: bit 14 is the asset-lock shielded recipient's. + XCTAssertEqual(PlatformWalletPersistenceCapabilities.privateContactRequestScanState, 1 << 15) + XCTAssertEqual( + PlatformWalletPersistenceCapabilities.privateContactRequestScanState, + UInt64(PLATFORM_WALLET_PERSISTENCE_CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE)) + let ext = handler.makePersistenceCallbacksExtension() + let persist = try XCTUnwrap(ext.on_persist_private_contact_scan_state_fn) + let load = try XCTUnwrap(ext.on_load_private_contact_scan_state_fn) + let free = try XCTUnwrap(ext.on_load_private_contact_scan_state_free_fn) + XCTAssertNotNil(ext.on_load_private_contact_scan_state_wallets_fn) + XCTAssertNotNil(ext.on_load_private_contact_scan_state_wallets_free_fn) + let context = Unmanaged.passUnretained(handler).toOpaque() + + var position = PrivateContactRequestsPositionFFI() + Swift.withUnsafeMutableBytes(of: &position.identity_id) { _ = owner.copyBytes(to: $0) } + position.position = 77 + position.private_payments_unresolved = true + Swift.withUnsafeMutableBytes(of: &position.key_fingerprint) { + _ = Data(repeating: 3, count: 32).copyBytes(to: $0) + } + var address = PrivateShieldedAddressFFI() + Swift.withUnsafeMutableBytes(of: &address.owner_id) { _ = owner.copyBytes(to: $0) } + Swift.withUnsafeMutableBytes(of: &address.contact_id) { _ = contact.copyBytes(to: $0) } + Swift.withUnsafeMutableBytes(of: &address.address) { _ = Data(repeating: 9, count: 43).copyBytes(to: $0) } + + handler.beginChangeset(walletId: walletId) + let rc = walletId.withUnsafeBytes { wallet in + persist(context, wallet.bindMemory(to: UInt8.self).baseAddress, + &position, 1, &address, 1, nil, 0, nil, 0) + } + XCTAssertEqual(rc, 0) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: true)) + + var positions: UnsafePointer? + var positionsCount: UInt = 0 + var addresses: UnsafePointer? + var addressesCount: UInt = 0 + let loadRc = walletId.withUnsafeBytes { wallet in + load(context, wallet.bindMemory(to: UInt8.self).baseAddress, + &positions, &positionsCount, &addresses, &addressesCount) + } + XCTAssertEqual(loadRc, 0) + XCTAssertEqual(positionsCount, 1) + XCTAssertEqual(addressesCount, 1) + let loadedPosition = try XCTUnwrap(positions).pointee + XCTAssertEqual(loadedPosition.position, 77) + XCTAssertTrue(loadedPosition.private_payments_unresolved, "the unresolved marker round-trips") + var loadedOwner = loadedPosition.identity_id + XCTAssertEqual(Swift.withUnsafeBytes(of: &loadedOwner) { Data($0) }, owner) + var loadedAddress = try XCTUnwrap(addresses).pointee.address + XCTAssertEqual(Swift.withUnsafeBytes(of: &loadedAddress) { Data($0) }, Data(repeating: 9, count: 43)) + free(context, positions, positionsCount, addresses, addressesCount) + + // A wallet with nothing stored hands back two empty arrays. + let empty = Data(repeating: 43, count: 32) + let emptyRc = empty.withUnsafeBytes { wallet in + load(context, wallet.bindMemory(to: UInt8.self).baseAddress, + &positions, &positionsCount, &addresses, &addressesCount) + } + XCTAssertEqual(emptyRc, 0) + XCTAssertNil(positions) + XCTAssertNil(addresses) + XCTAssertEqual(positionsCount + addressesCount, 0) + } +} diff --git a/packages/swift-sdk/schema-models.json b/packages/swift-sdk/schema-models.json index 439a181f8e3..b7714b9657d 100644 --- a/packages/swift-sdk/schema-models.json +++ b/packages/swift-sdk/schema-models.json @@ -36,7 +36,9 @@ "PersistentInvitation": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentInvitation.swift", "PersistentMasternode": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentMasternode.swift", "PersistentTrackedMasternode": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTrackedMasternode.swift", - "PersistentIdentityBalanceMetadata": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentityBalanceMetadata.swift" + "PersistentIdentityBalanceMetadata": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentityBalanceMetadata.swift", + "PersistentPrivateContactRequestsPosition": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateContactRequestsPosition.swift", + "PersistentPrivateShieldedAddress": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift" }, "value_types": [ {