diff --git a/build.gradle b/build.gradle index 3f68363fc7..19f532634a 100644 --- a/build.gradle +++ b/build.gradle @@ -8,9 +8,21 @@ buildscript { // truth for both the dependency coordinate (wallet/build.gradle) and the // DASH_SDK_VERSION BuildConfig field shown on the About screen once the // cutover hands L1 ownership to the SDK. - // Recipe: HashEngineering/dash-wallet-qa - // recipes/platform/5.1.0-int36.yaml. - dashSdkVersion = '5.1.0-int36-20261106.165805-1' + // Pre-release SDK snapshot published to the Sonatype snapshots repository + // (declared below as 'Central Portal Snapshots'; anonymous read). Pinned to + // the exact timestamped build, not the -SNAPSHOT name, so a later upload + // can't change what this commit builds. 5.1.0-int39 = int38 plus a Kotlin binding of + // #5860 (IdentityCredits.topUpExternalIdentityFromAddresses: top up an identity the + // wallet does not manage from its Platform addresses). int38: HashEngineering/platform + // integration/5.1.0-int38 @ c45221249f = int37's bindings (the partial-amount + // Platform-address withdrawal #5830, the third-party shields shieldedShieldToRecipient + // and shieldedShieldFromIdentityToRecipient) on v5.1-dev up to 185d0e6924, which adds + // #5556 (an uncertain submission outcome survives the shared broadcast as the typed + // DashSdkError.StateTransitionResultUnconfirmed), #5823 (prove a state transition's + // outcome; getRecentStateTransitionStatus), #5762 (persist the Orchard recipient of a + // shielded asset-lock funding), the Rust-owned TXO reconcile engine and DashPay private + // contact requests (#5809/#5810/#5813). + dashSdkVersion = '5.1.0-int39-20261113.161202-1' // Legacy dashj-platform SDK (org.dashj.platform), master's pin. It replaces the // 5.0.0-20261016.200955-3 snapshot this branch pinned for document serialization // format 3 (Platform protocol 14) and the IdentityPublicKey.toObject() CBOR fix; diff --git a/common/src/main/java/org/dash/wallet/common/payments/parsers/AddressNetwork.kt b/common/src/main/java/org/dash/wallet/common/payments/parsers/AddressNetwork.kt index 003f325cc7..e9ae1dcdcb 100644 --- a/common/src/main/java/org/dash/wallet/common/payments/parsers/AddressNetwork.kt +++ b/common/src/main/java/org/dash/wallet/common/payments/parsers/AddressNetwork.kt @@ -148,6 +148,10 @@ object AddressUtils { @Throws(AddressFormatException::class) fun decode(address: String): DecodedAddress { val versionAndDataBytes = Base58.decodeChecked(address) + // A valid checksum over an EMPTY payload (e.g. "3QJmnh") has no version byte. + if (versionAndDataBytes.isEmpty()) { + throw AddressFormatException.InvalidDataLength("Legacy addresses need a version byte, but got 0 bytes") + } val version = versionAndDataBytes[0].toInt() and 0xFF val payload = versionAndDataBytes.copyOfRange(1, versionAndDataBytes.size) if (payload.size != 20) { diff --git a/common/src/main/java/org/dash/wallet/common/payments/parsers/WifKey.kt b/common/src/main/java/org/dash/wallet/common/payments/parsers/WifKey.kt index 937009759b..4df3de63ab 100644 --- a/common/src/main/java/org/dash/wallet/common/payments/parsers/WifKey.kt +++ b/common/src/main/java/org/dash/wallet/common/payments/parsers/WifKey.kt @@ -62,6 +62,15 @@ class WifKey private constructor( override fun toString(): String = toBase58() companion object { + /** [Base58.decodeChecked], refusing a checksum-valid EMPTY payload (no version byte). */ + private fun decodeCheckedWithVersion(wif: String): ByteArray { + val versionAndDataBytes = Base58.decodeChecked(wif) + if (versionAndDataBytes.isEmpty()) { + throw AddressFormatException.InvalidDataLength("WIF keys need a version byte, but got 0 bytes") + } + return versionAndDataBytes + } + /** * Decodes a WIF string without any network check (checksum still enforced). * @@ -70,7 +79,7 @@ class WifKey private constructor( @JvmStatic @Throws(AddressFormatException::class) fun decode(wif: String): WifKey { - val versionAndDataBytes = Base58.decodeChecked(wif) + val versionAndDataBytes = decodeCheckedWithVersion(wif) val version = versionAndDataBytes[0].toInt() and 0xFF val bytes = versionAndDataBytes.copyOfRange(1, versionAndDataBytes.size) return WifKey(version, bytes) @@ -89,7 +98,7 @@ class WifKey private constructor( @JvmStatic @Throws(AddressFormatException::class) fun decode(wif: String, network: AddressNetwork): WifKey { - val versionAndDataBytes = Base58.decodeChecked(wif) + val versionAndDataBytes = decodeCheckedWithVersion(wif) val version = versionAndDataBytes[0].toInt() and 0xFF if (version != network.dumpedPrivateKeyHeader) { throw AddressFormatException.WrongNetwork(version) @@ -112,7 +121,7 @@ class WifKey private constructor( @JvmStatic @Throws(AddressFormatException::class) fun decodeDash(wif: String): Pair { - val versionAndDataBytes = Base58.decodeChecked(wif) + val versionAndDataBytes = decodeCheckedWithVersion(wif) val version = versionAndDataBytes[0].toInt() and 0xFF for (network in listOf(AddressNetwork.DASH_TESTNET, AddressNetwork.DASH_MAINNET)) { if (version == network.dumpedPrivateKeyHeader) { diff --git a/common/src/test/java/org/dash/wallet/common/payments/parsers/AddressParserTest.kt b/common/src/test/java/org/dash/wallet/common/payments/parsers/AddressParserTest.kt index 39355c82e2..82f94fd1fb 100644 --- a/common/src/test/java/org/dash/wallet/common/payments/parsers/AddressParserTest.kt +++ b/common/src/test/java/org/dash/wallet/common/payments/parsers/AddressParserTest.kt @@ -184,4 +184,11 @@ class AddressParserTest { ).size ) } + + @Test + fun checksumValidEmptyPayload_isAFormatError_notACrash() { + // "3QJmnh" is the Base58Check encoding of ZERO bytes: a valid checksum, no version byte. + org.junit.Assert.assertThrows(AddressFormatException::class.java) { AddressUtils.decode("3QJmnh") } + assertFalse(AddressUtils.isValid(AddressNetwork.DASH_MAINNET, "3QJmnh")) + } } diff --git a/common/src/test/java/org/dash/wallet/common/payments/parsers/WifKeyTest.kt b/common/src/test/java/org/dash/wallet/common/payments/parsers/WifKeyTest.kt index 6a197ae621..17bc633e79 100644 --- a/common/src/test/java/org/dash/wallet/common/payments/parsers/WifKeyTest.kt +++ b/common/src/test/java/org/dash/wallet/common/payments/parsers/WifKeyTest.kt @@ -156,4 +156,13 @@ class WifKeyTest { WifKey.encode(AddressNetwork.DASH_MAINNET, ByteArray(33), false) } } + + @Test + fun checksumValidEmptyPayload_isAFormatError_notACrash() { + // "3QJmnh" is the Base58Check encoding of ZERO bytes: a valid checksum, no version byte. + assertEquals(0, Base58.decodeChecked("3QJmnh").size) + assertThrows(AddressFormatException::class.java) { WifKey.decode("3QJmnh") } + assertThrows(AddressFormatException::class.java) { WifKey.decode("3QJmnh", AddressNetwork.DASH_MAINNET) } + assertThrows(AddressFormatException::class.java) { WifKey.decodeDash("3QJmnh") } + } } diff --git a/wallet/res/drawable/ic_system_message_info.xml b/wallet/res/drawable/ic_system_message_info.xml new file mode 100644 index 0000000000..4f91ff194f --- /dev/null +++ b/wallet/res/drawable/ic_system_message_info.xml @@ -0,0 +1,27 @@ + + + + + + diff --git a/wallet/res/drawable/ic_system_message_public.xml b/wallet/res/drawable/ic_system_message_public.xml new file mode 100644 index 0000000000..0727915713 --- /dev/null +++ b/wallet/res/drawable/ic_system_message_public.xml @@ -0,0 +1,30 @@ + + + + + + + diff --git a/wallet/res/navigation/nav_home.xml b/wallet/res/navigation/nav_home.xml index 01c6294356..0d53c591e9 100644 --- a/wallet/res/navigation/nav_home.xml +++ b/wallet/res/navigation/nav_home.xml @@ -206,6 +206,30 @@ app:enterAnim="@anim/slide_in_right" app:exitAnim="@anim/activity_stay" app:popExitAnim="@anim/slide_out_left" /> + + + + + + + + + + Sending Internal Shielded + + Platform Unshielded - Unshielded Withdrawal + author: a Platform address withdrawal, a Platform identity credit withdrawal (evonode + reward withdrawals included) or a foreign pool's unshield. Shown with receive semantics. --> + Withdrawal Invitation Processing Confirming @@ -519,6 +521,72 @@ Copy username Copy address QR code for the address below + + Send to username + Send to Dash address + Scan Dash QR + This QR code is not a Dash address or payment request. + This address belongs to a different Dash network. + This is not a valid Dash address or identity ID. + Address + DASH address + Enter address + Show clipboard + Tap the address from the clipboard to paste it + There is no Dash address in the clipboard + Paste %1$s + Scan a QR code + Back + Close + Send + From + To + Change the balance to send from + Core + Shielded + Platform + Identity + Transparent balance + Shielded balance + Platform balance + Identity balance + + — + Select source + Not available for this destination yet + No identity with this ID exists + Could not check this identity. Check your connection and try again. + Checking the identity… + Confirm + Network fee + Total + + ~%1$s + When sending from Shielded balance, the transaction is not instant and takes some time + When sending from Shielded balance to Core the amount and destination becomes public + When sending from Shielded balance to Platform the amount and destination becomes public + When sending from Shielded balance to an identity the amount and destination becomes public + Sending… + This could take about 30 seconds. You can leave this screen; the payment will continue. + This will only take a moment. + Sent + Your payment was sent. + Not sent + Edit + The balance is not enough for this amount and its fee. Nothing was sent. + Your wallet is still syncing. Nothing was sent; try again once it has finished. + The payment could not be signed. Unlock your device and try again. Nothing was sent. + This kind of payment is not available yet. Nothing was sent. + An earlier payment is still confirming. Nothing was sent; try again once it has confirmed. + Another payment is still being sent. Nothing was sent; try again once it has finished. + The payment could not be sent. Nothing was sent. + Payment status unknown + Your balance changed after you confirmed. Nothing was sent; review the amount and try again. + An earlier, unfinished top-up of this identity was completed instead. This payment was not sent; try again to send it. + The app was closed while a payment was being sent. It may have gone through: check your history before sending again. + Your payment may have gone through. Do not send it again; your balances will update after the next sync. + Payment not completed + The payment could not be completed. The funds will arrive in your Shielded balance instead; the recipient was not paid. This address is not available right now Revoke access diff --git a/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt b/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt index 1101eba2ec..0c987457f4 100644 --- a/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt +++ b/wallet/src/de/schildbach/wallet/di/PlatformSdkModule.kt @@ -27,6 +27,8 @@ import de.schildbach.wallet.service.platform.sdk.DashPayBackfillGateImpl import de.schildbach.wallet.service.platform.sdk.DashSdkMessageSigner import de.schildbach.wallet.service.platform.sdk.DashSdkService import de.schildbach.wallet.service.platform.sdk.DashSdkServiceImpl +import de.schildbach.wallet.service.platform.sdk.ExternalSendService +import de.schildbach.wallet.service.platform.sdk.ExternalSendServiceImpl import de.schildbach.wallet.service.platform.sdk.PlatformMnemonicProvider import de.schildbach.wallet.service.platform.sdk.SdkMessageSigner import de.schildbach.wallet.service.platform.sdk.SecurityGuardMnemonicProvider @@ -76,6 +78,11 @@ abstract class PlatformSdkModule { service: ShieldedBalanceServiceImpl ): ShieldedBalanceService + /** Advanced-mode External Send (MO-1121): orchestration over the sibling send services. */ + @Singleton + @Binds + abstract fun bindExternalSendService(service: ExternalSendServiceImpl): ExternalSendService + /** * The SDK message-signing seam behind * [de.schildbach.wallet.security.SecurityFunctions.signMessage] (the diff --git a/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt b/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt index 48ffbd9267..0f37acffe3 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt @@ -56,6 +56,7 @@ import de.schildbach.wallet.service.platform.sdk.SdkBlockchainStateService import de.schildbach.wallet.service.platform.sdk.BindHealL1Starter import de.schildbach.wallet.service.platform.sdk.L1ShadowSyncService import de.schildbach.wallet.service.platform.sdk.NonInteractiveWalletUnlock +import de.schildbach.wallet.service.platform.sdk.PlatformAddressSyncService import de.schildbach.wallet.service.platform.sdk.ShieldedBalanceService import de.schildbach.wallet.service.platform.sdk.SdkIdentityVerifyQueries import de.schildbach.wallet.service.platform.sdk.SdkProfileQueries @@ -68,6 +69,7 @@ import de.schildbach.wallet.ui.dashpay.PlatformRepo import de.schildbach.wallet.ui.dashpay.PreBlockStage import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet.ui.more.TxMetadataSaveFrequency +import de.schildbach.wallet.ui.payments.send.ExternalSendExecutor import de.schildbach.wallet.ui.shielded.ShieldedTransferExecutor import de.schildbach.wallet_test.BuildConfig import kotlinx.coroutines.* @@ -150,9 +152,10 @@ interface PlatformSyncService { suspend fun stopSync() /** - * Unconditionally stop the two Kotlin-SDK background engines (the L1 - * shadow SPV and the shielded sync loop). Both stops are best-effort, - * failure-contained no-ops when not running. [shutdown] calls it on + * Unconditionally stop the Kotlin-SDK background engines (the L1 shadow + * SPV, the shielded sync loop and the Platform-address balance sync + * loop). Every stop is best-effort, a failure-contained no-op when not + * running. [shutdown] calls it on * every build type (debug builds used to skip the engine stops on the * routine teardown; that exemption was removed on 2026-09-25). The * destructive paths (wallet wipe, before `finalizeWipe()` deletes app @@ -260,10 +263,15 @@ class PlatformSynchronizationService @Inject constructor( private val nonInteractiveWalletUnlock: NonInteractiveWalletUnlock, private val l1ShadowSyncService: L1ShadowSyncService, private val shieldedBalanceService: ShieldedBalanceService, + private val platformAddressSyncService: PlatformAddressSyncService, private val cutoverUiDataService: CutoverUiDataService, private val sdkBlockchainStateService: SdkBlockchainStateService, private val cutoverTxSeamService: CutoverTxSeamService, private val shieldedTransferExecutor: ShieldedTransferExecutor, + // Lazy: the executor's service graph (ExternalSendServiceImpl → ShieldedBalanceService, + // SdkL1SendService, …) is resolved only when a kick first reaches it, off the main thread, + // and a dependency path back to this service can never become a construction cycle. + private val externalSendExecutor: dagger.Lazy, private val contactRequestNotificationService: ContactRequestNotificationService, // The DashPay half of the user-facing "still syncing" state; this service // is the only component that knows whether DashPay applies at all. @@ -502,7 +510,16 @@ class PlatformSynchronizationService @Inject constructor( bindEstablished = sdkWalletBinder.bindEstablished, serviceTearingDown = { de.schildbach.wallet.service.BlockchainServiceImpl.isCleaningUpNow }, stopGeneration = { l1ShadowSyncService.stopGeneration() }, - startL1 = { generation -> l1ShadowSyncService.startIfEnabled(expectedExternalStopGeneration = generation) } + startL1 = { generation -> + // Sampled BEFORE the liveness check: stopSdkEngines() cancels this + // waiter before it bumps the Platform-address stop generation, so a + // waiter still active here sampled the generation that stop moves. + val platformAddressGeneration = platformAddressSyncService.stopGeneration() + currentCoroutineContext().ensureActive() + l1ShadowSyncService.startIfEnabled(expectedExternalStopGeneration = generation).also { started -> + if (started) platformAddressSyncService.startIfReady(platformAddressGeneration) + } + } ) private var lastTopupUpdateTime = 0L private var lastMetadataUpdateTime = 0L @@ -561,6 +578,9 @@ class PlatformSynchronizationService @Inject constructor( StartupBreadcrumbs.mark(StartupBreadcrumbs.STAGE_SDK_BIND_KICKED, "SDK_BIND_KICKED") val bindJob = sdkWalletBinder.bindInBackground(nonInteractiveWalletUnlock::unlockOrNull) val lifetime = serviceLifetime.get() + // Sampled with the lifetime: an engine stop after this point (shutdown, + // or the wipe's direct stopSdkEngines) refuses this kick's start. + val platformAddressGeneration = platformAddressSyncService.stopGeneration() startupKickJob?.cancel() startupKickJob = syncScope.launch { bindJob.join() @@ -609,6 +629,14 @@ class PlatformSynchronizationService @Inject constructor( // waiter the current lifetime armed. val stillCurrent = { serviceLifetime.get() == lifetime } if (started) bindHealL1Starter.cancel(stillCurrent) else bindHealL1Starter.arm(stillCurrent) + // Platform-address (BLAST) balance sync: without it credits other + // wallets send to our Platform addresses never show up. Same + // foreground-service lifetime as the L1 engine; it declines until + // the SDK wallet is bound (the bind heal above retries it), and + // stopSdkEngines() is its teardown. Not gated on Advanced mode: + // it keeps the persisted Platform balances correct for every + // reader (External Send, invite top-up). + platformAddressSyncService.startIfReady(platformAddressGeneration) } // Phase 5d follow-up: the post-cutover UI data source (balance // header / tx list / coins-received detection served from the @@ -653,6 +681,16 @@ class PlatformSynchronizationService @Inject constructor( } }.onFailure { log.warn("startup shielded bring-up failed", it) } } + // The External Send counterpart of the pending wallet-shield sweep + // above: finish a Core → Platform send whose asset lock was built + // but whose Platform funding never completed, without the user + // opening External Send (a pending record means they already + // confirmed that payment, so Advanced mode is not consulted). Same + // trigger as that sweep: every kick, after the bind pass. The sweep + // runs on the application scope, off the main thread, one at a time + // and single-flight with sends (the service's inFlight); it no-ops + // unless the cutover is committed and the record's wallet is bound. + resumePendingExternalPlatformFunding() // DIP-15 friend-chain backfill (docs/kotlin-sdk-migration-plan.md; // scratchpad/txdiff/FINDINGS.md): the app keeps DashPay contacts on // dashj and never drives the SDK's contact-sync path, so the bound @@ -665,6 +703,17 @@ class PlatformSynchronizationService @Inject constructor( } } + /** Kick [ExternalSendExecutor.resumePendingPlatformFunding]; never throws into the kick. */ + private fun resumePendingExternalPlatformFunding() { + try { + externalSendExecutor.get().resumePendingPlatformFunding() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("startup pending external Platform funding sweep could not start", e) + } + } + override fun resume() { // shutdown() stops the Kotlin-SDK background engines whenever the // blockchain service is torn down (unclean-kill corruption guard), @@ -901,6 +950,9 @@ class PlatformSynchronizationService @Inject constructor( .onFailure { log.warn("failed to stop the L1 shadow sync on shutdown", it) } runCatching { shieldedBalanceService.stop() } .onFailure { log.warn("failed to stop the shielded runtime on shutdown", it) } + // Last, and after bindHealL1Starter.cancel(): its stop-generation bump + // must follow the heal's cancel (see bindHealL1Starter). Failure-contained. + platformAddressSyncService.stop() } override suspend fun stopSync() { diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt index 48a8ebb84f..9238ffcce3 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt @@ -42,17 +42,39 @@ import javax.inject.Singleton enum class AssetLockKind { UPGRADE, TOPUP, INVITE, SHIELD, + /** + * A lock funding a Platform ADDRESS (`AssetLockFundingType::AssetLockAddressTopUp`): + * the Core → Platform External Send to a third-party payee. Product decision + * (2026-11-06): a send — sent arrow and amount, titled "Platform". A restored + * wallet's lock that funded one of its OWN Platform addresses reads the same + * way; the funding type cannot tell the two apart. + */ + PLATFORM, + + /** + * A shield lock (`AssetLockFundingType::AssetLockShieldedAddressTopUp`) whose Orchard + * recipient is ANOTHER wallet: the Core → Shielded External Send to a third-party + * payee. Same product decision as [PLATFORM]: a send — sent arrow and amount, titled + * "Shielded". Only the authoring path knows the recipient was external, so this kind + * exists only as the in-memory seed from that send; the funding type (5) cannot tell + * own from third-party, so the durable fallback (a restart, a restore) reads + * [SHIELD] and the row returns to the self-transfer look. + */ + SHIELD_EXTERNAL, + /** An AssetUnlock THIS wallet's shielded pool paid out — a self-move. */ UNSHIELD, /** - * An AssetUnlock from a FOREIGN pool paying this wallet — at the Core - * level a plain incoming payment, and it must keep receive semantics - * (green inbound arrow, coins-received notification) under the - * "Unshielded" label. Field case: a tester funded a different seed in a - * desktop wallet, shielded there, and unshielded a piece back to this - * wallet — the unconditional kind-7 → self-move treatment relabelled a - * genuine external receive. + * An AssetUnlock paying this wallet that this wallet's pool did not + * author — at the Core level a plain incoming payment, and it must keep + * receive semantics (green inbound arrow, coins-received notification). + * It carries no source: a Platform address withdrawal, a Platform identity + * credit withdrawal (evonode rewards included) or a foreign pool's + * unshield, so the row is titled plain "Withdrawal" (2026-11-08). Field + * case: a tester funded a different seed in a desktop wallet, shielded + * there, and unshielded a piece back to this wallet — the unconditional + * kind-7 → self-move treatment relabelled a genuine external receive. */ UNSHIELD_EXTERNAL } @@ -85,6 +107,7 @@ private const val FUNDING_TYPE_UPGRADE = 0 private const val FUNDING_TYPE_TOPUP_A = 1 private const val FUNDING_TYPE_TOPUP_B = 2 private const val FUNDING_TYPE_INVITATION = 3 +private const val FUNDING_TYPE_PLATFORM_ADDRESS = ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP private const val FUNDING_TYPE_SHIELD = 5 /** Table for the allocation-free hex encoders below (lowercase, the app-wide convention). */ @@ -322,6 +345,7 @@ class AssetLockKindResolver @Inject constructor( // lock the app-side records never captured (e.g. after a restore). val kind = when (db?.assetLockDao()?.fundingTypeForTxid(hex)) { FUNDING_TYPE_SHIELD -> AssetLockKind.SHIELD + FUNDING_TYPE_PLATFORM_ADDRESS -> AssetLockKind.PLATFORM FUNDING_TYPE_INVITATION -> AssetLockKind.INVITE FUNDING_TYPE_TOPUP_A, FUNDING_TYPE_TOPUP_B -> AssetLockKind.TOPUP FUNDING_TYPE_UPGRADE -> AssetLockKind.UPGRADE diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/CutoverUiDataService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/CutoverUiDataService.kt index 65d11f971e..12e65daa96 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/CutoverUiDataService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/CutoverUiDataService.kt @@ -449,19 +449,23 @@ internal fun planL1TxRow( * The shield/unshield pair moves value between the wallet and its own * shielded pool — a self-transfer, not a payment — so both list rows render * the INTERNAL (double-arrows) transfer icon instead of the sent/received - * arrows (product spec; the fee-like kinds keep the sent arrow). + * arrows (product spec; the fee-like kinds keep the sent arrow). A shield to + * ANOTHER wallet ([AssetLockKind.SHIELD_EXTERNAL]) is a payment, not a pool + * transfer, so it keeps the sent arrow. */ internal val AssetLockKind.isPoolTransfer: Boolean get() = this == AssetLockKind.SHIELD || this == AssetLockKind.UNSHIELD /** - * The kinds an OUTGOING asset lock can carry: the Platform-funding ones and the - * shield (a lock into the wallet's own pool, kept on its transfer treatment). - * The unshield pair are AssetUnlocks, recorded INCOMING, never an outgoing lock. + * The kinds an OUTGOING asset lock can carry: the Platform-funding ones (the + * Platform-address send included), the shield (a lock into the wallet's own + * pool, kept on its transfer treatment) and the third-party shielded send. The + * unshield pair are AssetUnlocks, recorded INCOMING, never an outgoing lock. */ internal val AssetLockKind.appliesToOutgoing: Boolean get() = this == AssetLockKind.UPGRADE || this == AssetLockKind.TOPUP || - this == AssetLockKind.INVITE || this == AssetLockKind.SHIELD + this == AssetLockKind.INVITE || this == AssetLockKind.SHIELD || + this == AssetLockKind.PLATFORM || this == AssetLockKind.SHIELD_EXTERNAL /** * Whether the display pass asks the asset-lock resolver about an OUTGOING @@ -480,14 +484,21 @@ internal fun assetLockTitleRes(kind: AssetLockKind): Int = when (kind) { // unshield/withdraw "Unshielded". AssetLockKind.INVITE -> R.string.transaction_row_invitation AssetLockKind.SHIELD -> R.string.transaction_row_shielded + // Core → Platform-address send: a payment, so the sent arrow, titled "Platform". + AssetLockKind.PLATFORM -> R.string.transaction_row_platform + // Core → third-party shielded-address send: a payment like PLATFORM (sent + // arrow — not a pool transfer), titled by its destination like PLATFORM. + AssetLockKind.SHIELD_EXTERNAL -> R.string.transaction_row_shielded AssetLockKind.UNSHIELD -> R.string.transaction_row_unshielded // Every AssetUnlock without evidence that THIS wallet's pool authored it. - // That is not only a foreign pool's unshield: a Platform identity credit - // withdrawal (evonode reward withdrawals included) is an AssetUnlock too, - // and plain "Unshielded" on it read as a shielded-pool move the user never - // made (field report, 2026-09-30). Product decision, 2026-09-30, replacing - // the shared label of 2026-08-10; the arrow still carries the receive. - AssetLockKind.UNSHIELD_EXTERNAL -> R.string.transaction_row_unshielded_withdrawal + // A received AssetUnlock carries no source, so it may be a Platform address + // withdrawal (sendable via Advanced External Send, Platform → Core), a + // Platform identity credit withdrawal (evonode reward withdrawals included) + // or a foreign shielded pool's unshield. "Unshielded" mislabels the first + // two, so the row reads plain "Withdrawal" (user decision, 2026-11-08, + // replacing "Unshielded Withdrawal" of 2026-09-30); the arrow still + // carries the receive. + AssetLockKind.UNSHIELD_EXTERNAL -> R.string.transaction_row_withdrawal } /** diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/DashSdkServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/DashSdkServiceImpl.kt index 5d58a6fb46..ed973fbfe1 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/DashSdkServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/DashSdkServiceImpl.kt @@ -458,12 +458,17 @@ private val sdkWipeLog = LoggerFactory.getLogger("de.schildbach.wallet.service.p * walletManagerStore) followed by `bootstrap()` (`Sdk.initialize` → * logging → per-network `Sdk.create`) and `activateManager()` * (`WalletManagerStore.activate` → `loadPersistedWallets`). The example's - * remaining steps are intentionally deferred: + * remaining steps live elsewhere or are intentionally deferred: * * - `loadKnownContractsIntoSdk` — no contracts are persisted yet (3b), - * - sync-service binding (`platformBalanceSyncService.configure`, - * `startPlatformAddressSync` / `startShieldedSync` / - * `startDashPaySync`) — Phase 3b/4, + * - sync-service binding: the example's `rebindWalletScopedServices` is + * split across the app. The Platform-address loop + * (`startPlatformAddressSync`) is started and stopped by + * [PlatformAddressSyncService] from the blockchain service's engine kick / + * `stopSdkEngines()`, and the shielded loop by [ShieldedBalanceServiceImpl]. + * `platformBalanceSyncService.configure` is not used (it only reflects the + * loop for the example's Sync tab), and `startDashPaySync` stays deferred + * (DashPay contacts still sync on dashj), * - network-switch observer — the app's network is flavor-fixed. * * @param mnemonicProvider the Phase 3b seed bridge diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt new file mode 100644 index 0000000000..36809a90e2 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt @@ -0,0 +1,304 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform.sdk + +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import de.schildbach.wallet.ui.shielded.assetLockMaxFeeReserve +import kotlinx.coroutines.runBlocking +import org.bitcoinj.core.Utils + +// Advanced-mode External Send, Core → third-party Platform address (MO-1121): +// the persisted recipient record the SDK's resume contract requires, and the +// fee/Max arithmetic. See ManagedPlatformWallet.fundFromAssetLockExternal. + +/** + * The Platform-fee margin, in duffs, a Core → Platform lock carries on top of what the + * payee receives: `amount + margin` is locked, the payee is credited exactly `amount`, + * and the wallet's own remainder output receives the rest, out of which Platform takes + * the transition fee (rs-platform-wallet `remainder_fee_strategy` charges the fee to the + * remainder, never to the payee). + * + * The value is the DPP admission floor of an `AddressFundingFromAssetLock` with 0 inputs + * and 2 outputs (rs-dpp `calculate_address_funding_from_asset_lock_min_required_fee`): + * `required_asset_lock_duff_balance_for_processing_start_for_address_funding` (50 000 + * duffs, dpp state-transition versions v1–v4) + 2 × `address_funds_transfer_output_cost` + * (6 000 000 credits = 6 000 duffs each, state-transition min fees v1) = 62 000 duffs. + * rs-platform-wallet refuses a lock below that floor before building it + * (`enforce_asset_lock_amount_covers_address_funding_floor`), so a lock of + * `amount + margin` always clears it. The metered fee itself is not knowable before the + * send; whatever the margin does not use stays on the wallet's own Platform address. + */ +internal const val PLATFORM_FUNDING_FEE_MARGIN_DUFFS = 62_000L + +/** + * The smallest explicit Platform output, in credits (`min_output_amount`, dpp + * state-transition versions v1–v4). A smaller payee output would be rejected by Platform + * AFTER the lock is broadcast, so the send refuses it before building anything. + */ +internal const val PLATFORM_MIN_OUTPUT_CREDITS = 500_000L + +/** The BIP44 Core account the lock is funded from (as every other SDK asset-lock build). */ +internal const val EXTERNAL_FUNDING_ACCOUNT_INDEX = 0 + +/** The DIP-17 Platform payment account that owns the remainder address. */ +internal const val EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX = 0 + +/** + * SDK `AssetLockFundingType::AssetLockAddressTopUp` (`asset_locks.fundingTypeRaw == 4`): + * how the SDK tracks a Platform-address funding lock, owned or external alike. No other + * app sweep reads this type (the shielded sweep reads 5, identity recovery 0–2). + */ +internal const val ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP = 4 + +/** The Core → Platform lock in duffs: [amountDuffs] plus [PLATFORM_FUNDING_FEE_MARGIN_DUFFS]. */ +internal fun platformFundingLockDuffs(amountDuffs: Long): Long = + Math.addExact(amountDuffs, PLATFORM_FUNDING_FEE_MARGIN_DUFFS) + +/** + * The fee shown for a Core → Platform send, in duffs (an estimate, "~"): the L1 + * asset-lock fee reserve ([assetLockMaxFeeReserve], an upper bound) plus the Platform + * margin, whose unused part stays on the wallet's own Platform address. + */ +internal fun coreToPlatformFeeDuffs(spendableUtxoCount: Int): Long = + Math.addExact(assetLockMaxFeeReserve(spendableUtxoCount).duffs, PLATFORM_FUNDING_FEE_MARGIN_DUFFS) + +/** + * The Core → Platform Max, in duffs, or null when not positive: the asset-lock-eligible + * balance less the L1 fee reserve and the Platform margin. + */ +internal fun coreToPlatformMaxDuffs(eligibleDuffs: Long, spendableUtxoCount: Int): Long? = + (eligibleDuffs - coreToPlatformFeeDuffs(spendableUtxoCount)).takeIf { it > 0 } + +/** + * One Core → Platform external funding, persisted BEFORE the SDK call and kept until + * the lock is consumed: the tracked lock stores no recipients, so this record is the + * only thing that binds the lock ([outPointHex], recorded from `onAssetLockBuilt`) to + * its payee. A resume must use exactly [recipients]. + * + * [completionUnconfirmed]: an automatic resume got Platform's `AssetLockAlreadyConsumed` for + * this lock (iOS `AssetLockRecoveryService`'s `completionUnconfirmed`). That answer is + * unauthenticated, so the record is never deleted for it: the store moves it out of the + * pending slot into its completion-unconfirmed set ([PlatformFundingStore.markCompletionUnconfirmed]), + * where it no longer blocks a new Core → Platform send and is no longer resumed automatically, + * but is kept for an explicit retry. Its lock stays non-terminal in the SDK. + * + * [toString] is redacted: no address, amount or wallet id is ever logged. + */ +internal class PendingPlatformFunding( + val id: String, + val walletIdHex: String, + val lockDuffs: Long, + val destination: PlatformAddressBytes, + val explicitCredits: Long, + val remainder: PlatformAddressBytes, + /** `:`, the SDK `asset_locks` key; null until the lock is built. */ + val outPointHex: String?, + val completionUnconfirmed: Boolean = false +) { + init { + require(id.isNotEmpty() && FIELD_SEPARATOR !in id) { "malformed id" } + require(walletIdFromHex(walletIdHex) != null) { "malformed wallet id" } + require(lockDuffs > 0) { "lock must be positive" } + require(explicitCredits > 0) { "explicit amount must be positive" } + require(destination.addressType == 0 && destination.hash.size == 20) { "destination must be P2PKH" } + require(remainder.addressType == 0 && remainder.hash.size == 20) { "remainder must be P2PKH" } + require(!destination.hash.contentEquals(remainder.hash)) { "destination and remainder must differ" } + require(outPointHex == null || parseOutPointHex(outPointHex) != null) { "malformed outpoint" } + require(!completionUnconfirmed || outPointHex != null) { "only a built lock can be completion-unconfirmed" } + } + + /** The recipients, in the SDK's shape: the payee's explicit amount and the remainder. */ + val recipients: List + get() = listOf( + org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.FundRecipient( + destination.addressType, destination.hash.copyOf(), explicitCredits + ), + org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.FundRecipient( + remainder.addressType, remainder.hash.copyOf(), null + ) + ) + + fun withOutPoint(outPointHex: String): PendingPlatformFunding = + PendingPlatformFunding(id, walletIdHex, lockDuffs, destination, explicitCredits, remainder, outPointHex) + + /** This record, marked [completionUnconfirmed] (its lock must have been built). */ + fun asCompletionUnconfirmed(): PendingPlatformFunding = PendingPlatformFunding( + id, walletIdHex, lockDuffs, destination, explicitCredits, remainder, outPointHex, completionUnconfirmed = true + ) + + /** Same content, field by field (the hashes by value). */ + fun sameAs(other: PendingPlatformFunding): Boolean = + id == other.id && + walletIdHex.equals(other.walletIdHex, ignoreCase = true) && + lockDuffs == other.lockDuffs && + destination.addressType == other.destination.addressType && + destination.hash.contentEquals(other.destination.hash) && + explicitCredits == other.explicitCredits && + remainder.addressType == other.remainder.addressType && + remainder.hash.contentEquals(other.remainder.hash) && + outPointHex == other.outPointHex && + completionUnconfirmed == other.completionUnconfirmed + + /** + * The stored form. An unmarked record keeps the original ten fields (what every earlier + * build wrote and reads); [completionUnconfirmed] adds an eleventh, [COMPLETION_UNCONFIRMED]. + */ + fun encode(): String = listOfNotNull( + FORMAT_VERSION, + id, + walletIdHex.lowercase(), + lockDuffs.toString(), + destination.addressType.toString(), + Utils.HEX.encode(destination.hash), + explicitCredits.toString(), + remainder.addressType.toString(), + Utils.HEX.encode(remainder.hash), + outPointHex.orEmpty(), + COMPLETION_UNCONFIRMED.takeIf { completionUnconfirmed } + ).joinToString(FIELD_SEPARATOR) + + override fun toString(): String = + "PendingPlatformFunding(id=$id, outPoint=${if (outPointHex == null) "none" else "recorded"}, " + + "completionUnconfirmed=$completionUnconfirmed, )" + + companion object { + private const val FORMAT_VERSION = "1" + private const val FIELD_SEPARATOR = "|" + private const val FIELD_COUNT = 10 + private const val COMPLETION_UNCONFIRMED = "u" + + /** + * Decode a stored record. Malformed is NOT absent: this throws + * [IllegalStateException], and every caller fails closed on it. A record written + * before [completionUnconfirmed] existed (ten fields) decodes as not marked. + */ + fun decode(encoded: String): PendingPlatformFunding { + val fields = encoded.split(FIELD_SEPARATOR) + val marked = fields.size == FIELD_COUNT + 1 && fields[FIELD_COUNT] == COMPLETION_UNCONFIRMED + check((fields.size == FIELD_COUNT || marked) && fields[0] == FORMAT_VERSION) { + "malformed pending platform funding" + } + return try { + PendingPlatformFunding( + id = fields[1], + walletIdHex = fields[2], + lockDuffs = fields[3].toLong(), + destination = PlatformAddressBytes(fields[4].toInt(), hash20(fields[5])), + explicitCredits = fields[6].toLong(), + remainder = PlatformAddressBytes(fields[7].toInt(), hash20(fields[8])), + outPointHex = fields[9].ifEmpty { null }, + completionUnconfirmed = marked + ) + } catch (e: IllegalArgumentException) { + // NumberFormatException included; the message carries no field value. + throw IllegalStateException("malformed pending platform funding") + } + } + + private fun hash20(hex: String): ByteArray { + require(hex.length == 40 && hex.all { Character.digit(it, 16) >= 0 }) { "malformed hash" } + return Utils.HEX.decode(hex) + } + } +} + +/** + * Durable store of the (at most one) [PendingPlatformFunding]. Every call throws when the + * store cannot be read or written; [read] also throws on a malformed record. + */ +internal interface PlatformFundingStore { + /** The pending record, null when there is none. */ + suspend fun read(): PendingPlatformFunding? + + /** Replace the record and return only once it is durable. */ + suspend fun write(record: PendingPlatformFunding) + + /** + * [write] from a non-coroutine thread (the SDK's `onAssetLockBuilt`): blocks until the + * record is durable and reads back as written; throws otherwise. + */ + fun writeBlocking(record: PendingPlatformFunding) + + /** Remove the record if it is still [id]'s (a malformed or different record is kept). */ + suspend fun clear(id: String) + + /** + * In one durable transaction, move the pending record out of the pending slot into the + * completion-unconfirmed set, marked ([PendingPlatformFunding.completionUnconfirmed]), + * if it is still [id]'s and its lock was built; otherwise change nothing. Never deletes it. + */ + suspend fun markCompletionUnconfirmed(id: String) + + /** + * The completion-unconfirmed records (all wallets), never resumed automatically and never + * blocking a new send; kept for an explicit retry. Throws when unreadable or malformed. + */ + suspend fun readCompletionUnconfirmed(): List +} + +/** + * [PlatformFundingStore] over [DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING] and + * [DashPayConfig.EXTERNAL_PLATFORM_FUNDING_UNCONFIRMED]; a wallet wipe clears both + * (DashPayConfig's default `clearAll`). + */ +internal class DashPayConfigPlatformFundingStore(private val config: DashPayConfig) : PlatformFundingStore { + override suspend fun read(): PendingPlatformFunding? = + config.getPreservingErrors(DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING) + ?.takeIf { it.isNotEmpty() } + ?.let(PendingPlatformFunding::decode) + + // One DataStore transaction; it returns only after the file is written and synced. + override suspend fun write(record: PendingPlatformFunding) = + config.set(DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING, record.encode()) + + override fun writeBlocking(record: PendingPlatformFunding) = runBlocking { + write(record) + val back = read() + check(back != null && back.sameAs(record)) { "pending platform funding did not read back as written" } + } + + override suspend fun clear(id: String) = config.editPreferences { prefs -> + val stored = prefs[DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING] + val storedId = try { + stored?.takeIf { it.isNotEmpty() }?.let { PendingPlatformFunding.decode(it).id } + } catch (e: IllegalStateException) { + null + } + if (storedId == id) prefs.remove(DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING) + } + + override suspend fun markCompletionUnconfirmed(id: String) = config.editPreferences { prefs -> + val stored = prefs[DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING] + val record = try { + stored?.takeIf { it.isNotEmpty() }?.let(PendingPlatformFunding::decode) + } catch (e: IllegalStateException) { + null + } + if (record != null && record.id == id && record.outPointHex != null) { + val unconfirmed = prefs[DashPayConfig.EXTERNAL_PLATFORM_FUNDING_UNCONFIRMED].orEmpty() + prefs[DashPayConfig.EXTERNAL_PLATFORM_FUNDING_UNCONFIRMED] = + unconfirmed + record.asCompletionUnconfirmed().encode() + prefs.remove(DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING) + } + } + + override suspend fun readCompletionUnconfirmed(): List = + config.getPreservingErrors(DashPayConfig.EXTERNAL_PLATFORM_FUNDING_UNCONFIRMED) + .orEmpty() + .map(PendingPlatformFunding::decode) +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt new file mode 100644 index 0000000000..7d38a422f0 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -0,0 +1,413 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform.sdk + +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.payments.parsers.AddressFormatException +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.AddressUtils +import org.dash.wallet.common.payments.parsers.Base58 +import org.dash.wallet.common.payments.parsers.PaymentURI + +// Pure, host-testable model of the Advanced-mode "External Send" (MO-1121): +// which balance pays, what the typed destination is, and which pairs the +// wallet supports. No native, no Android, no I/O. + +/** The four balances an Advanced-mode send can be paid from. */ +enum class SendBalance { CORE, SHIELDED, PLATFORM, IDENTITY } + +/** + * A fully validated external destination. [display] is the canonical form to show + * the user; [toString] is redacted (addresses and identity ids are never logged). + */ +sealed class SendDestination { + abstract val display: String + + /** A Core L1 base58 address of the wallet's network (P2PKH or P2SH). */ + data class Core(val address: String) : SendDestination() { + override val display: String get() = address + override fun toString(): String = "Core()" + } + + /** A bech32m Orchard address (`dash1z…` / `tdash1z…`), lowercase. */ + data class Shielded(val address: String) : SendDestination() { + override val display: String get() = address + override fun toString(): String = "Shielded()" + } + + /** A bech32m DIP-18 Platform address (`dash1k…` P2PKH / `dash1s…` P2SH, `tdash1…` off mainnet), lowercase. */ + data class Platform(val address: String) : SendDestination() { + override val display: String get() = address + override fun toString(): String = "Platform()" + } + + /** An identity id: base58 of exactly 32 bytes. */ + data class Identity(val identityIdBase58: String) : SendDestination() { + override val display: String get() = identityIdBase58 + override fun toString(): String = "Identity()" + } +} + +/** The kind of balance [destination] is paid into: what keys its fee, Max, icon and name. */ +fun balanceKindOf(destination: SendDestination): SendBalance = when (destination) { + is SendDestination.Core -> SendBalance.CORE + is SendDestination.Shielded -> SendBalance.SHIELDED + is SendDestination.Platform -> SendBalance.PLATFORM + is SendDestination.Identity -> SendBalance.IDENTITY +} + +/** The result of [detectSendDestination]. */ +sealed class DestinationParse { + /** + * A destination of the wallet's network. [amount] is set only for a `dash:` payment + * URI that carried a positive one (any destination type, see [detectSendDestination]). + */ + data class Valid(val destination: SendDestination, val amount: Dash? = null) : DestinationParse() { + override fun toString(): String = "Valid($destination, amount=${if (amount == null) "none" else ""})" + } + + /** Blank input. */ + object Empty : DestinationParse() + + /** A well-formed address of another Dash network (mainnet vs testnet/devnet). */ + object WrongNetwork : DestinationParse() + + /** Anything else: bad checksum, unknown type, wrong length, a BIP70 `r=` link, … */ + object Invalid : DestinationParse() +} + +/** DIP-18 bech32m type byte of a P2PKH Platform address (rs-dpp `PlatformAddress::P2PKH_TYPE`). */ +internal const val PLATFORM_P2PKH_TYPE_BYTE = 0xb0 + +/** DIP-18 bech32m type byte of a P2SH Platform address (rs-dpp `PlatformAddress::P2SH_TYPE`). */ +internal const val PLATFORM_P2SH_TYPE_BYTE = 0x80 + +/** DIP-18 bech32m type byte of an Orchard address. */ +private const val ORCHARD_ADDRESS_TYPE_BYTE = 0x10 + +/** Orchard raw address length: 11-byte diversifier + 32-byte pk_d. */ +private const val ORCHARD_RAW_LENGTH = 43 + +/** Platform address hash length (hash160). */ +private const val PLATFORM_HASH_LENGTH = 20 + +/** Identity ids are 32 bytes. */ +internal const val IDENTITY_ID_LENGTH = 32 + +private const val MAINNET_HRP = "dash" +private const val TESTNET_HRP = "tdash" + +/** DIP-18 HRP of [network]: `dash` on mainnet, `tdash` everywhere else. */ +internal fun platformHrp(network: AddressNetwork): String = + if (network.id == AddressNetwork.ID_MAINNET) MAINNET_HRP else TESTNET_HRP + +/** + * A Platform address decoded to the SDK's storage shape: [addressType] 0 = P2PKH, + * 1 = P2SH (the `FundingInput` / `CreditOutput` convention), [hash] its 20-byte hash. + */ +class PlatformAddressBytes(val addressType: Int, val hash: ByteArray) { + override fun toString(): String = "PlatformAddressBytes(type=$addressType, )" +} + +/** + * Decode a bech32m Platform address of [network], or null when it is not one (bad + * checksum, other HRP, wrong length, unknown type byte). + */ +internal fun decodePlatformAddress(address: String, network: AddressNetwork): PlatformAddressBytes? { + val decoded = Bech32m.decode(address.trim()) ?: return null + if (decoded.hrp != platformHrp(network)) return null + val data = decoded.data + if (data.size != 1 + PLATFORM_HASH_LENGTH) return null + val type = when (data[0].toInt() and 0xff) { + PLATFORM_P2PKH_TYPE_BYTE -> 0 + PLATFORM_P2SH_TYPE_BYTE -> 1 + else -> return null + } + return PlatformAddressBytes(type, data.copyOfRange(1, data.size)) +} + +/** + * Whether [address] is a well-formed P2PKH Platform address (type byte + * [PLATFORM_P2PKH_TYPE_BYTE], 20-byte hash) of either Dash HRP. False for P2SH and for + * anything that is not a Platform address. The network is checked separately. + */ +internal fun isP2pkhPlatformAddress(address: String): Boolean { + val decoded = Bech32m.decode(address.trim()) ?: return false + if (decoded.hrp != MAINNET_HRP && decoded.hrp != TESTNET_HRP) return false + val data = decoded.data + return data.size == 1 + PLATFORM_HASH_LENGTH && (data[0].toInt() and 0xff) == PLATFORM_P2PKH_TYPE_BYTE +} + +/** The 32 bytes of a base58 identity id, or null when [identityIdBase58] is not one. */ +internal fun decodeIdentityId(identityIdBase58: String): ByteArray? { + val trimmed = identityIdBase58.trim() + if (trimmed.isEmpty()) return null + val bytes = try { + Base58.decode(trimmed) + } catch (e: AddressFormatException) { + return null + } + return bytes.takeIf { it.size == IDENTITY_ID_LENGTH } +} + +private val DASH_NETWORKS = listOf(AddressNetwork.DASH_MAINNET, AddressNetwork.DASH_TESTNET) + +/** + * Classify what the user typed or scanned as an external send destination of + * [network]. The WHOLE input is checked: the Core base58check checksum and version + * byte; the bech32m checksum, HRP (= network), payload length and type byte for + * Platform/Shielded; the decoded length (32) for an identity id. Leading and trailing + * whitespace is ignored; bech32m must be all-lowercase or all-uppercase (BIP-350) and + * is returned lowercase. + * + * A `dash:` payment URI resolves to its destination plus its optional amount: a Core + * address through the shared [PaymentURI] parser; a Shielded, Platform or identity path + * (what Advanced Receive's amount requests produce, + * `ReceiveViewModel.amountRequestPayload`) through [detectNonCoreDashUri]. A URI that + * carries a BIP70 payment request (`r=`) is [DestinationParse.Invalid] here: the + * merchant's invoice flow owns it, and paying the fallback address would bypass the + * invoice. + * + * Pure and total: it never throws, whatever the input (anything unexpected is + * [DestinationParse.Invalid]). + */ +fun detectSendDestination(input: String, network: AddressNetwork): DestinationParse = try { + detectSendDestinationOrThrow(input, network) +} catch (e: Exception) { + // A decoder bug on hostile input (scanned, typed or on the clipboard) must never + // crash the screen; the input is simply not a destination. + DestinationParse.Invalid +} + +private fun detectSendDestinationOrThrow(input: String, network: AddressNetwork): DestinationParse { + val trimmed = input.trim() + if (trimmed.isEmpty()) return DestinationParse.Empty + + if (trimmed.startsWith("${AddressNetwork.DASH_SCHEME}:", ignoreCase = true)) { + return detectDashUri(trimmed, network) + } + return detectPlainDestination(trimmed, network) +} + +/** A bare (non-URI) destination: Core, then bech32m Platform/Orchard, then an identity id. */ +private fun detectPlainDestination(input: String, network: AddressNetwork): DestinationParse { + detectCoreAddress(input, network)?.let { return it } + detectBech32mAddress(input, network)?.let { return it } + decodeIdentityId(input)?.let { + return DestinationParse.Valid(SendDestination.Identity(input)) + } + return DestinationParse.Invalid +} + +/** A base58check Core address: Valid / WrongNetwork, or null when the input is not one at all. */ +private fun detectCoreAddress(input: String, network: AddressNetwork): DestinationParse? { + val decoded = try { + AddressUtils.decode(input) + } catch (e: AddressFormatException) { + return null + } + if (network.acceptsVersion(decoded.version)) { + return DestinationParse.Valid(SendDestination.Core(input)) + } + // A valid base58check hash160 of ANOTHER Dash network is a wrong-network address; + // any other version byte (a Bitcoin address, say) is simply invalid. + return if (DASH_NETWORKS.any { it.acceptsVersion(decoded.version) }) { + DestinationParse.WrongNetwork + } else { + DestinationParse.Invalid + } +} + +/** A bech32m Platform or Orchard address: Valid / WrongNetwork / Invalid, or null when not bech32m. */ +private fun detectBech32mAddress(input: String, network: AddressNetwork): DestinationParse? { + val decoded = Bech32m.decode(input) ?: return null + if (decoded.hrp != MAINNET_HRP && decoded.hrp != TESTNET_HRP) return DestinationParse.Invalid + val data = decoded.data + if (data.isEmpty()) return DestinationParse.Invalid + val type = data[0].toInt() and 0xff + val kindIsShielded = when { + type == ORCHARD_ADDRESS_TYPE_BYTE && data.size == 1 + ORCHARD_RAW_LENGTH -> true + (type == PLATFORM_P2PKH_TYPE_BYTE || type == PLATFORM_P2SH_TYPE_BYTE) && + data.size == 1 + PLATFORM_HASH_LENGTH -> false + else -> return DestinationParse.Invalid + } + if (decoded.hrp != platformHrp(network)) return DestinationParse.WrongNetwork + val canonical = input.lowercase() + return DestinationParse.Valid( + if (kindIsShielded) SendDestination.Shielded(canonical) else SendDestination.Platform(canonical) + ) +} + +private fun detectDashUri(input: String, network: AddressNetwork): DestinationParse { + val body = input.substring(AddressNetwork.DASH_SCHEME.length + 1) + val path = body.substringBefore('?') + // A Core address (or no address at all) keeps the shared PaymentURI parser, unchanged. + if (path.isEmpty() || detectCoreAddress(path, network) != null) { + return detectCoreDashUri(input, network) + } + val query = if ('?' in body) body.substringAfter('?') else "" + return detectNonCoreDashUri(path, query, network) +} + +/** + * `dash:[?amount=]`. The query is read strictly (BIP21 + * rules): a BIP70 `r` or any unknown required (`req-…`) parameter is + * [DestinationParse.Invalid], as is a repeated or malformed `amount`; other optional + * parameters (label, message, …) are ignored. + */ +private fun detectNonCoreDashUri(path: String, query: String, network: AddressNetwork): DestinationParse { + var amount: Dash? = null + var amountSeen = false + for (param in query.split('&')) { + if (param.isEmpty()) continue + val key = param.substringBefore('=') + val value = param.substringAfter('=', missingDelimiterValue = "") + when { + key == "amount" -> { + if (amountSeen) return DestinationParse.Invalid + amountSeen = true + val duffs = parseUriAmountDuffs(value, network) ?: return DestinationParse.Invalid + amount = Dash(duffs).takeIf { it.isPositive } + } + key == "r" || key.startsWith("req-") -> return DestinationParse.Invalid + else -> Unit + } + } + return when (val destination = detectPlainDestination(path, network)) { + is DestinationParse.Valid -> DestinationParse.Valid(destination.destination, amount) + DestinationParse.WrongNetwork -> DestinationParse.WrongNetwork + DestinationParse.Empty, DestinationParse.Invalid -> DestinationParse.Invalid + } +} + +private val URI_AMOUNT = Regex("^[0-9]{1,8}(\\.[0-9]{1,8})?$") + +/** A BIP21 `amount` (decimal DASH, at most 8 places, at most [AddressNetwork.maxMoney]) in duffs, or null. */ +private fun parseUriAmountDuffs(value: String, network: AddressNetwork): Long? { + if (!URI_AMOUNT.matches(value)) return null + val duffs = java.math.BigDecimal(value).movePointRight(8).longValueExact() + return duffs.takeIf { it <= network.maxMoney } +} + +private fun detectCoreDashUri(input: String, network: AddressNetwork): DestinationParse { + // Parsed without a network expectation, so a wrong-network address is reported + // as such instead of as a generic parse failure. + val uri = try { + PaymentURI(null, input) + } catch (e: PaymentURI.ParseException) { + return DestinationParse.Invalid + } + if (uri.paymentRequestUrl != null) return DestinationParse.Invalid + val address = uri.address ?: return DestinationParse.Invalid + return when (val core = detectCoreAddress(address, network)) { + is DestinationParse.Valid -> { + val amount = uri.amount?.let { Dash(it.value) }?.takeIf { it.isPositive } + DestinationParse.Valid(core.destination, amount) + } + null -> DestinationParse.Invalid + else -> core + } +} + +/** + * Whether [ExternalSendService.maxSendable] of the pair is the largest amount its send + * accepts, so the amount page must be bounded by it and never by the raw balance (unknown + * blocks Continue). Platform → Core and Platform → Identity: the first-sorting input keeps a + * fee reserve (about 0.004 DASH), far more than the fee finally charged, so the balance + * overstates what can be sent. + */ +fun maxBoundsAmount(source: SendBalance, destinationKind: SendBalance): Boolean = + source == SendBalance.PLATFORM && (destinationKind == SendBalance.CORE || destinationKind == SendBalance.IDENTITY) + +/** Whether a pair can be sent, and if not, why (the UI maps each to its own copy). */ +enum class SendSupport { + SUPPORTED, + + /** The SDK (or the wallet) cannot do this pair yet. */ + NOT_SUPPORTED_YET, + + /** A Core-funded identity top-up is only possible for an identity this wallet manages. */ + NEEDS_OWN_IDENTITY, + + /** The source is the identity balance and the user has no identity. */ + NO_IDENTITY +} + +/** + * The one support matrix of the external send, enforced by the UI AND by + * [ExternalSendService.send]: + * + * | From \ To | Core | Shielded | Platform | Identity | + * |---|---|---|---|---| + * | Core | yes | yes | yes, P2PKH only (1) | own identity only (2) | + * | Shielded | yes | yes | yes | yes | + * | Platform | yes (3) | yes (4) | yes | yes (6) | + * | Identity | yes | yes (5) | yes | yes, not to itself | + * + * 1. `ManagedPlatformWallet.fundFromAssetLockExternal`: the payee gets the explicit + * amount, the wallet's own Platform address the remainder (and pays the fee). The SDK + * takes P2PKH recipients only, so a P2SH (`dash1s…`) destination is + * [SendSupport.NOT_SUPPORTED_YET] here and refused by [ExternalSendService.send] + * before anything is built. A lock interrupted after it was built is resumed with its + * persisted recipients ([PendingPlatformFunding]). + * 2. The Core top-up's resume gate keys on the managed identity's registration index; + * for someone else's identity a killed attempt could not be resumed (double-pay + * risk). [destinationIsOwnIdentity] null (could not tell) fails closed. + * 3. The partial-amount `ManagedPlatformWallet.withdrawCredits(coreAddress, inputs, …)` + * with inputs the wallet selects ([selectPlatformWithdrawalInputs]); amounts below the + * withdrawal minimum ([PLATFORM_MIN_WITHDRAWAL_CREDITS], over the amount plus the Core + * fee withdrawn on top, [coreWithdrawalCreditsOrNull]) are refused before signing. + * 4. `shieldedShieldToRecipient` (Type 15 to a third party's Orchard address; the SDK + * selects the Platform-address inputs). + * 5. `shieldedShieldFromIdentityToRecipient` (Type 21 to a third party's Orchard address). + * + * 6. An identity this wallet manages: `identityCredits.topUpFromAddresses`. Any other + * identity: `identityCredits.topUpExternalIdentityFromAddresses` (platform#5860; Rust + * fetches it from Platform, and an identity Platform does not have fails `NotFound` + * before anything is signed). Supported either way here; [ExternalSendService.send] + * picks the call from the managed set and refuses (Not sent) when that set is + * unreadable, never guessing. + * + * In 4 and 5 the SDK refuses an Orchard address the wallet's own shielded account + * recognizes (a self-shield is not an external send) before building anything. + */ +fun externalSendSupport( + source: SendBalance, + destination: SendDestination, + hasIdentity: Boolean, + destinationIsOwnIdentity: Boolean? +): SendSupport { + if (source == SendBalance.IDENTITY && !hasIdentity) return SendSupport.NO_IDENTITY + return when (source) { + SendBalance.CORE -> when (destination) { + is SendDestination.Core, is SendDestination.Shielded -> SendSupport.SUPPORTED + is SendDestination.Platform -> + if (isP2pkhPlatformAddress(destination.address)) SendSupport.SUPPORTED else SendSupport.NOT_SUPPORTED_YET + is SendDestination.Identity -> + if (destinationIsOwnIdentity == true) SendSupport.SUPPORTED else SendSupport.NEEDS_OWN_IDENTITY + } + SendBalance.SHIELDED -> SendSupport.SUPPORTED + SendBalance.PLATFORM -> SendSupport.SUPPORTED + SendBalance.IDENTITY -> when (destination) { + is SendDestination.Core, is SendDestination.Shielded, is SendDestination.Platform -> SendSupport.SUPPORTED + // A transfer from the user's identity to itself moves nothing and pays a fee. + is SendDestination.Identity -> + if (destinationIsOwnIdentity == true) SendSupport.NOT_SUPPORTED_YET else SendSupport.SUPPORTED + } + } +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt new file mode 100644 index 0000000000..b84107ed61 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -0,0 +1,199 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform.sdk + +import kotlinx.coroutines.flow.Flow +import org.dash.wallet.common.money.Dash + +/** A fee for one exact send. [exact] false = an estimate or an upper bound, shown as "~". */ +data class FeeEstimate(val fee: Dash, val exact: Boolean) + +/** [ExternalSendService.resolveIdentity] for the confirm step. Never carries the id. */ +sealed class IdentityResolution { + /** The identity exists on Platform; [username] is its DPNS name when one could be read. */ + data class Found(val username: String?) : IdentityResolution() { + override fun toString(): String = "Found()" + } + + /** Platform answered that no such identity exists. */ + object NotFound : IdentityResolution() + + /** The lookup failed (network, SDK not ready): unknown, never "not found". */ + object Unknown : IdentityResolution() +} + +/** Why a send provably did not spend anything. The UI maps each to its own string; no SDK text. */ +enum class NotSentReason { + INSUFFICIENT_FUNDS, + + /** The engine/pool is not caught up yet (L1 funding gate closed, shielded runtime not ready). */ + NOT_SYNCED, + + /** The signer could not sign (device locked / Keystore refused); the same send works after unlock. */ + SIGNER_LOCKED, + + /** The pair is not supported ([externalSendSupport]) or the feature is off. */ + NOT_SUPPORTED, + + /** An earlier payment's outcome is still unknown and its inputs cannot be kept out of this one. */ + PAYMENT_STILL_CONFIRMING, + + /** Another external send is already running. */ + IN_PROGRESS, + + /** + * A Max (whole-balance) send: the spendable balance is no longer what the user confirmed + * (funds arrived or left meanwhile), so nothing was drained; review and confirm again. + */ + BALANCE_CHANGED, + + /** + * Core → own identity: an earlier top-up of that identity was left unfinished, and the + * top-up's resume gate completed IT (its own amount) instead. This request was not + * executed; sending again tops up the requested amount. + */ + EARLIER_TOP_UP_COMPLETED, + + /** Anything else refused before submission (including the wallet changing under the send). */ + GENERIC +} + +/** The outcome of [ExternalSendService.send]. */ +sealed class ExternalSendResult { + /** Submitted. [txIdOrNull] is the Core txid when the route reports one. */ + data class Sent(val txIdOrNull: String?) : ExternalSendResult() + + /** Provably nothing was spent; the user may retry. */ + data class NotSent(val reason: NotSentReason) : ExternalSendResult() + + /** The outcome is unknown: terminal "may have gone through", NEVER a retry. */ + object MayHaveGoneThrough : ExternalSendResult() + + /** + * Core → Shielded only: the L1 asset lock went out but the shield transition to the + * recipient provably did not. The wallet's pending-shield sweep completes it to the + * user's OWN shielded balance instead; the recipient is not paid. Terminal; no retry. + */ + object InterruptedFundsReturnToShielded : ExternalSendResult() +} + +/** + * Advanced-mode "External Send" (MO-1121): send from one of the four balances + * ([SendBalance]) to an external destination ([SendDestination]) under the support + * matrix [externalSendSupport]. Basic mode does not use this. + * + * Every send needs the cutover committed (the SDK owns L1); shielded legs also need + * `USE_KOTLIN_SDK_SHIELDED`. Both are read error-preserving: unreadable = refused. + * Nothing amount-, address- or identity-derived is logged. + */ +interface ExternalSendService { + /** + * Live spendable balance of [source]; null = unknown (never [Dash.ZERO] for + * unknown). Shielded is only known while the pool is READY and not stale after a + * spend; Identity is null when the user has no identity. Never throws. + */ + fun observeBalance(source: SendBalance): Flow + + /** + * Whether the user has a registered identity (the IDENTITY source and the + * `hasIdentity` input of [externalSendSupport]); null = could not tell. + */ + fun observeHasIdentity(): Flow + + /** + * The SDK wallet bound right now, read WITHOUT suspending (null = none, or unknown). The + * confirm step captures it into the request and [send] refuses unless the same wallet is + * still bound at every check and right before each write. + */ + fun currentWalletIdOrNull(): String? + + /** Whether this wallet manages the identity; null = could not tell (fail closed). */ + suspend fun isOwnIdentity(identityIdBase58: String): Boolean? + + /** Identity lookup for the confirm step (AC8). Never logs the id. */ + suspend fun resolveIdentity(identityIdBase58: String): IdentityResolution + + /** + * Fee for a send from [source] into a [destinationKind] balance ([balanceKindOf] of the + * destination), or null when it cannot be known before the send (never fabricated). + */ + suspend fun estimateFee(source: SendBalance, destinationKind: SendBalance): FeeEstimate? + + /** + * The Max amount, or null when unknown: for Core → Core the whole spendable balance, + * GROSS of the drain fee (the drain delivers it minus the fee); for Shielded → Core the + * amount withdrawn (the recipient receives it minus the asset unlock's Core fee); for every + * other pair the amount the recipient receives (balance minus the fee paid on top). + * [destinationKind] is [balanceKindOf] of the destination. For the pairs where + * [maxBoundsAmount] holds it is also the largest amount the send accepts. + */ + suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? + + /** + * Send [amount] from [source] to [destination]. The caller has ALREADY + * authenticated (PIN/biometric) for this send and passes exactly what the user + * confirmed, including [expectedWalletIdHex] ([currentWalletIdOrNull] at confirmation). + * The implementation refuses unless that wallet is the bound one, and re-checks it + * right before each native call (a change or null → NotSent, nothing submitted), + * enforces [externalSendSupport] itself, and runs one attempt (plus, for a + * shielded-funded or Core→Shielded [isMax] send, one fee-adjusted retry after a + * provably pre-broadcast shortfall). A Core → Core [isMax] send is the SDK drain and + * runs only while the max-sendable balance still equals [amount] + * ([NotSentReason.BALANCE_CHANGED] otherwise). The recipient of a Core → Shielded send + * receives [amount]; the shield pool fee is paid on top. + * + * Shielded legs block for a ~30s proof: run this on an application-scoped owner so + * leaving the screen does not cancel it. + * + * Core → Platform: the payee receives [amount]; the lock carries a Platform-fee margin on + * top, whose unused part lands on the wallet's own Platform address. Its recipients are + * persisted before the SDK call ([PendingPlatformFunding]); while an earlier one is still + * pending a new Core → Platform send is [NotSentReason.PAYMENT_STILL_CONFIRMING]. A record + * whose resume got Platform's unauthenticated already-consumed answer is kept as + * completion unconfirmed and no longer blocks it. + * + * Platform / Identity / Shielded → Core: DPP takes the Core fee of the asset unlock out of + * the withdrawn amount, so [amount] plus that fee is withdrawn and the recipient receives + * exactly [amount] (a Shielded → Core [isMax] send withdraws [amount] itself, and the + * recipient receives it minus the Core fee). Platform → Core is a partial withdrawal from + * the wallet's Platform addresses (the inputs are selected here, never above an address's + * balance), the Platform fee out of what the fee-paying address keeps. Outside the + * withdrawal bounds a Platform / Identity → Core send is refused before anything is signed. + * Platform / Identity → Shielded: a shield of [amount] to the third-party Orchard address, + * fees on top; the wallet's own shielded address is refused (nothing submitted). + */ + suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult + + /** + * Finish an interrupted Core → Platform send: when a [PendingPlatformFunding] of the bound + * wallet has a built lock that is not Consumed, resume it with EXACTLY its persisted + * recipients (`resumeFundFromAssetLockExternal`), so the original payee is paid. The record + * is cleared once the lock is consumed (by this resume or earlier, as the SDK proves). + * Platform's unauthenticated already-consumed answer moves it, kept, to completion + * unconfirmed: not resumed automatically again and not blocking a new send. + * Attempts are capped per process. Never throws (except cancellation); returns the number + * of fundings completed by this call (0 or 1). + */ + suspend fun resumePendingPlatformFunding(): Int +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt new file mode 100644 index 0000000000..a63e0de01d --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -0,0 +1,2245 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform.sdk + +import de.schildbach.wallet.Constants +import de.schildbach.wallet.data.WalletData +import de.schildbach.wallet.database.entity.BlockchainIdentityConfig +import de.schildbach.wallet.database.entity.IdentityCreationState +import de.schildbach.wallet.payments.FundingSelectionLock +import de.schildbach.wallet.payments.SendEngineNotSyncedException +import de.schildbach.wallet.payments.SendNotSdkRoutableException +import de.schildbach.wallet.payments.SendSignerLockedException +import de.schildbach.wallet.payments.PendingPaymentFundingGate +import de.schildbach.wallet.payments.SubmissionMark +import de.schildbach.wallet.payments.isCompleteTxFailure +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import de.schildbach.wallet.ui.shielded.assetLockMaxFeeReserve +import de.schildbach.wallet.ui.shielded.shieldedMaxFeeAdjustment +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.services.InsufficientFundsException +import org.dash.wallet.common.services.PaymentStillConfirmingException +import org.dash.wallet.common.services.PaymentSubmissionPendingException +import org.dash.wallet.common.services.SendPaymentService +import org.dash.wallet.common.services.WalletSession +import org.dash.wallet.common.util.readRetryDelayMs +import org.dash.wallet.common.util.retryReadErrors +import org.dashfoundation.dashsdk.credits.FundingInput +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.slf4j.LoggerFactory +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference +import javax.inject.Inject +import javax.inject.Singleton + +// ── Pure helpers ────────────────────────────────────────────────────── + +/** + * What the external send logs for a failure: the class names of [t] and its causes (and a + * [DashSdkError.PlatformWallet.Generic]'s native code), never a message or a stack trace — + * SDK messages embed recipient addresses, identity ids and amounts. + */ +internal fun safeErrorSummary(t: Throwable?): String { + if (t == null) return "none" + val names = buildList { + var current: Throwable? = t + while (current != null && size < 4) { + val name = current.javaClass.simpleName.ifEmpty { current.javaClass.name } + val code = (current as? DashSdkError.PlatformWallet.Generic)?.nativeCode + add(if (code != null) "$name(code $code)" else name) + current = current.cause?.takeIf { it !== current } + } + } + return names.joinToString(" <- ") +} + +/** + * The [NotSentReason] for a [SdkWriteResult.NotBroadcast] — the reason text and the + * cause chain are matched against the named reasons the sibling services emit, so the + * UI never sees SDK text. Unmatched → [NotSentReason.GENERIC]. + */ +internal fun notSentReasonFor(result: SdkWriteResult.NotBroadcast): NotSentReason { + val texts = buildList { + add(result.reason) + var t: Throwable? = result.cause + var depth = 0 + while (t != null && depth < 10) { + t.message?.let(::add) + t = t.cause + depth++ + } + } + fun any(vararg needles: String) = texts.any { text -> needles.any { text.contains(it) } } + return when { + any(L1_PENDING_PAYMENT_UNPROTECTED_REASON, REASON_SHIELDED_IDENTITY_DEBIT_PENDING) -> + NotSentReason.PAYMENT_STILL_CONFIRMING + any(L1_SIGNER_LOCKED_REASON, REASON_PRE_BROADCAST_ASSET_LOCK_SIGNING) -> NotSentReason.SIGNER_LOCKED + any( + L1_FUNDING_GATE_CLOSED_REASON, + "shielded runtime not ready", + "L1 sync not running" + ) -> NotSentReason.NOT_SYNCED + any( + REASON_PRE_BROADCAST_BUILD_SHORTFALL, + REASON_PRE_BROADCAST_ASSET_LOCK_SELECTION, + "Insufficient shielded balance", + "asset lock coin selection is short", + "does not cover the shield pool fee" + ) -> NotSentReason.INSUFFICIENT_FUNDS + result.reason == "flag off" || any("L1 shadow flag off") -> NotSentReason.NOT_SUPPORTED + else -> NotSentReason.GENERIC + } +} + +/** + * Classify a failure THROWN by the Core send ([SendPaymentService.sendCoins], + * post-cutover the SDK route): only the typed refusals the send path raises strictly + * before broadcasting are [ExternalSendResult.NotSent]; a submission-pending failure and + * anything unknown is [ExternalSendResult.MayHaveGoneThrough]. + * + * Every [IllegalStateException] / [IllegalArgumentException] on that path is a + * pre-broadcast refusal: `sdkSendNotAttemptedException` (NotBroadcast with no fallback), + * the wiped-wallet `ensureStillOwned` refusal and a foreign [WalletSession]. The + * ambiguous SDK outcome is a [PaymentSubmissionPendingException], checked first. + */ +internal fun classifyCoreSendThrowable(e: Exception): ExternalSendResult = when (e) { + is PaymentSubmissionPendingException -> ExternalSendResult.MayHaveGoneThrough + is PaymentStillConfirmingException -> + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING) + is SendEngineNotSyncedException -> ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED) + is SendSignerLockedException -> ExternalSendResult.NotSent(NotSentReason.SIGNER_LOCKED) + is SendNotSdkRoutableException -> ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED) + is InsufficientFundsException -> ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS) + is org.bitcoinj.core.InsufficientMoneyException -> + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS) + is IllegalStateException, is IllegalArgumentException -> ExternalSendResult.NotSent(NotSentReason.GENERIC) + else -> if (isCompleteTxFailure(e)) { + ExternalSendResult.NotSent(NotSentReason.GENERIC) + } else { + ExternalSendResult.MayHaveGoneThrough + } +} + +/** + * The balance, in credits, a Platform → Identity top-up ([ExternalSendSource.platformTopUpIdentity], + * [ExternalSendSource.platformTopUpExternalIdentity]) leaves unspent on its fee payer. + * + * The top-up (`IdentityTopUpFromAddressesTransition`) always carries the fee strategy + * `DeductFromInput(0)`: the input whose address sorts FIRST pays the fee out of what that address + * KEEPS, and Platform rejects the transition when that remainder cannot cover the fee actually + * charged. The consensus minimum (`identity_topup_base_cost` 500 000 + 500 000 per input) is no + * bound on that charge: execution meters the real processing and storage cost, which the wallet + * cannot compute, and the SDK exposes no top-up fee estimate or preflight. So the reserve is the + * SDK's own reserve for the address withdrawal at the most inputs a transition may carry: + * `address_credit_withdrawal` 400 000 000 + 500 000 × [PLATFORM_MAX_ADDRESS_INPUTS] (0.00408 DASH). + * A withdrawal performs the same per-input address writes as a top-up and queues a withdrawal + * document on top, and its measured charge (about 0.00104 DASH, platform#5830) is a quarter of + * its reserve, so this errs high: it only lowers the Max. + */ +internal const val PLATFORM_TOP_UP_FEE_RESERVE_CREDITS = 400_000_000L + 500_000L * 16 + +/** + * DPP's `min_identity_funding_amount` (dpp state-transition versions v1–v2): a top-up from + * addresses must spend at least this many credits in total, or DPP rejects it. + */ +internal const val PLATFORM_MIN_IDENTITY_FUNDING_CREDITS = 200_000L + +/** + * The Core fee rate of a Platform → Core withdrawal, duffs/byte: the minimum Fibonacci rate + * DPP accepts, the rate the shielded withdrawal uses. + */ +internal const val PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE = ShieldedBalanceServiceImpl.WITHDRAW_CORE_FEE_PER_BYTE + +/** The DIP-17 Platform payment account a Platform → Core withdrawal spends from. */ +internal const val PLATFORM_WITHDRAW_ACCOUNT_INDEX = 0 + +/** Size of an asset-unlock transaction in bytes (dashcore `ASSET_UNLOCK_TX_SIZE`). */ +private const val ASSET_UNLOCK_TX_SIZE_BYTES = 190L + +/** + * The Core fee of a withdrawal's asset unlock, in duffs, at [PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE] + * (the rate every withdrawal here uses): 190 bytes × the rate. From protocol version 14 DPP + * carves it OUT of the withdrawn amount (rs-dpp `core_fee_in_credits`) for Platform-address, + * identity and shielded withdrawals alike, so [ExternalSendService.send] withdraws the confirmed + * amount PLUS this fee and the recipient receives exactly the confirmed amount (a Shielded → + * Core Max withdraws the amount itself, and the recipient receives it minus this fee). + */ +internal const val WITHDRAWAL_CORE_FEE_DUFFS = ASSET_UNLOCK_TX_SIZE_BYTES * PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE + +/** [WITHDRAWAL_CORE_FEE_DUFFS] in credits. */ +internal const val WITHDRAWAL_CORE_FEE_CREDITS = WITHDRAWAL_CORE_FEE_DUFFS * CREDITS_PER_DUFF + +/** + * The smallest Platform → Core withdrawal, in credits, at [PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE]: + * `min_withdrawal_amount` (1 000 000 credits, rs-platform-version system limits v2–v4) plus the + * Core fee of the asset unlock, which from protocol version 14 is carved out of the withdrawn + * amount (rs-dpp `min_withdrawal_amount_with_core_fee`: 190 bytes × the rate × 1000 credits per + * duff). The SDK exposes no reader for it, and DPP would reject a smaller withdrawal only while + * validating the signed transition, so [ExternalSendService.send] refuses it before anything is + * selected or signed. It bounds the GROSS withdrawal ([coreWithdrawalCreditsOrNull]): the + * recipient's amount plus [WITHDRAWAL_CORE_FEE_CREDITS]. + */ +internal const val PLATFORM_MIN_WITHDRAWAL_CREDITS = 1_000_000L + WITHDRAWAL_CORE_FEE_CREDITS + +/** The largest Platform → Core withdrawal, in credits (`max_withdrawal_amount`, 500 DASH, system limits v1–v4). */ +internal const val PLATFORM_MAX_WITHDRAWAL_CREDITS = 50_000_000_000_000L + +/** + * The gross amount, in credits, a Platform-address or identity withdrawal paying the recipient + * exactly [recipientCredits] must withdraw: [recipientCredits] + [WITHDRAWAL_CORE_FEE_CREDITS] + * (DPP carves the Core fee out of the withdrawn amount). Null when that sum overflows or falls + * outside DPP's [PLATFORM_MIN_WITHDRAWAL_CREDITS]..[PLATFORM_MAX_WITHDRAWAL_CREDITS], which bound + * the gross amount. + */ +internal fun coreWithdrawalCreditsOrNull(recipientCredits: Long): Long? { + val gross = try { + Math.addExact(recipientCredits, WITHDRAWAL_CORE_FEE_CREDITS) + } catch (e: ArithmeticException) { + return null + } + return gross.takeIf { it in PLATFORM_MIN_WITHDRAWAL_CREDITS..PLATFORM_MAX_WITHDRAWAL_CREDITS } +} + +/** DPP's `max_address_inputs` (dpp state-transition versions v2–v4): at most this many inputs per transition. */ +internal const val PLATFORM_MAX_ADDRESS_INPUTS = 16 + +/** Unsigned lexicographic order of 20-byte address hashes: the order of rs-dpp's `PlatformAddress` (P2PKH). */ +private val ADDRESS_HASH_ORDER = Comparator { a, b -> + val x = a.hash + val y = b.hash + for (i in 0 until minOf(x.size, y.size)) { + val c = (x[i].toInt() and 0xff) - (y[i].toInt() and 0xff) + if (c != 0) return@Comparator c + } + x.size - y.size +} + +/** + * Inputs for a partial Platform → Core withdrawal (`withdrawCredits` with explicit inputs) or + * a Platform → Identity top-up (the same `DeductFromInput(0)` fee rule, the same per-input + * minimum and input cap) that take EXACTLY [targetCredits] in total, or null when the addresses + * cannot cover it. + * + * The SDK charges the Platform transition fee to the input whose address sorts FIRST + * (`DeductFromInput(0)` over the inputs ordered by address), out of what that address KEEPS. + * So the chosen set's first-sorting input (the fee payer) keeps at least [feeReserveCredits] + * of its balance; every other input may be drawn in full. No input ever takes more than its + * address's balance, every input takes at least [minInputCredits] (DPP rejects the whole + * transition otherwise), only P2PKH addresses (the only kind the wallet signs) are used, and + * at most [maxInputs] inputs are chosen. Of the feasible sets the one with the fewest inputs + * (the fee grows with the input count) is returned, the fee payer first. + */ +internal fun selectPlatformWithdrawalInputs( + candidates: List, + targetCredits: Long, + feeReserveCredits: Long, + minInputCredits: Long, + maxInputs: Int = PLATFORM_MAX_ADDRESS_INPUTS +): List? { + if (targetCredits <= 0 || feeReserveCredits < 0 || maxInputs < 1) return null + val min = maxOf(minInputCredits, 1L) + val usable = candidates + .filter { it.addressType == 0 && it.hash.size == 20 && it.credits >= min } + .sortedWith(ADDRESS_HASH_ORDER) + var best: List? = null + for ((index, payer) in usable.withIndex()) { + val payerCap = payer.credits - feeReserveCredits + if (payerCap < min) continue + // Only addresses sorting AFTER the payer may join it: otherwise one of them would pay. + val others = usable.subList(index + 1, usable.size).sortedByDescending { it.credits } + val maxOthers = minOf(maxInputs - 1, others.size) + for (count in 0..maxOthers) { + if (best != null && count + 1 >= best.size) break + val picked = others.take(count) + val lowest = try { + Math.multiplyExact(min, (count + 1).toLong()) + } catch (e: ArithmeticException) { + break + } + val highest = picked.fold(payerCap) { acc, input -> saturatingAdd(acc, input.credits) } + if (targetCredits < lowest) break + if (targetCredits > highest) continue + // Every input starts at the minimum; the rest is drawn from the others first + // (in full if need be), then from the payer, which never exceeds payerCap. + var extra = targetCredits - lowest + val inputs = picked.map { input -> + val add = minOf(extra, input.credits - min) + extra -= add + FundingInput(input.addressType, input.hash.copyOf(), min + add) + } + best = listOf(FundingInput(payer.addressType, payer.hash.copyOf(), min + extra)) + inputs + break + } + } + return best +} + +/** + * The largest total, in credits, [selectPlatformWithdrawalInputs] can select from [candidates] + * under the same rules (P2PKH, every input at least [minInputCredits], at most [maxInputs] + * inputs, the first-sorting input keeping [feeReserveCredits]); null when no input can pay + * the fee. For each possible fee payer it is the payer's balance less the reserve plus the + * [maxInputs] − 1 largest balances sorting after it, drawn in full. + */ +internal fun maxPlatformWithdrawalCredits( + candidates: List, + feeReserveCredits: Long, + minInputCredits: Long, + maxInputs: Int = PLATFORM_MAX_ADDRESS_INPUTS +): Long? { + if (feeReserveCredits < 0 || maxInputs < 1) return null + val min = maxOf(minInputCredits, 1L) + val usable = candidates + .filter { it.addressType == 0 && it.hash.size == 20 && it.credits >= min } + .sortedWith(ADDRESS_HASH_ORDER) + var best: Long? = null + for ((index, payer) in usable.withIndex()) { + val payerCap = payer.credits - feeReserveCredits + if (payerCap < min) continue + val total = usable.subList(index + 1, usable.size) + .map { it.credits } + .sortedDescending() + .take(maxInputs - 1) + .fold(payerCap, ::saturatingAdd) + if (best == null || total > best) best = total + } + return best +} + +/** + * The Platform → Identity Max, in duffs: the largest top-up [maxPlatformWithdrawalCredits] + * allows with the fee payer keeping [PLATFORM_TOP_UP_FEE_RESERVE_CREDITS], rounded down to whole + * duffs. Null when it is below [PLATFORM_MIN_IDENTITY_FUNDING_CREDITS] or + * [selectPlatformWithdrawalInputs] would not take it (so the send accepts exactly this). + */ +internal fun platformToIdentityMaxDuffs(candidates: List, minInputCredits: Long): Long? { + val gross = maxPlatformWithdrawalCredits(candidates, PLATFORM_TOP_UP_FEE_RESERVE_CREDITS, minInputCredits) + ?: return null + val duffs = gross / CREDITS_PER_DUFF + val credits = duffs * CREDITS_PER_DUFF + if (credits < PLATFORM_MIN_IDENTITY_FUNDING_CREDITS) return null + return duffs.takeIf { + selectPlatformWithdrawalInputs(candidates, credits, PLATFORM_TOP_UP_FEE_RESERVE_CREDITS, minInputCredits) != null + } +} + +/** + * The Platform → Core Max, in duffs the RECIPIENT receives: the largest gross withdrawal + * [maxPlatformWithdrawalCredits] allows (capped at [PLATFORM_MAX_WITHDRAWAL_CREDITS]) less + * the Core fee DPP carves out of it ([WITHDRAWAL_CORE_FEE_CREDITS]), rounded down to whole + * duffs. Null when it is below DPP's minimum withdrawal or [selectPlatformWithdrawalInputs] + * would not take it (so the send path accepts exactly what this allows). + */ +internal fun platformToCoreMaxDuffs( + candidates: List, + feeReserveCredits: Long, + minInputCredits: Long +): Long? { + val gross = maxPlatformWithdrawalCredits(candidates, feeReserveCredits, minInputCredits) + ?.coerceAtMost(PLATFORM_MAX_WITHDRAWAL_CREDITS) + ?: return null + val recipientDuffs = (gross - WITHDRAWAL_CORE_FEE_CREDITS).takeIf { it > 0 }?.div(CREDITS_PER_DUFF) ?: return null + val sendGross = coreWithdrawalCreditsOrNull(recipientDuffs * CREDITS_PER_DUFF) ?: return null + return recipientDuffs.takeIf { + selectPlatformWithdrawalInputs(candidates, sendGross, feeReserveCredits, minInputCredits) != null + } +} + +private fun saturatingAdd(a: Long, b: Long): Long = try { + Math.addExact(a, b) +} catch (e: ArithmeticException) { + Long.MAX_VALUE +} + +/** + * The pool fee, in duffs, a Core → Shielded asset lock pays on top of what the recipient + * receives: Rust derives `shield_amount = lock_value − pool_fee` with + * `pool_fee = compute_minimum_shielded_fee(2) + asset_lock_base_cost` + * (rs-platform-wallet `fund_from_asset_lock.rs`), both versioned consensus constants — so + * for a given protocol version it does not depend on the request. [shieldFeeCredits] is the + * SDK's 2-action shield fee ([ShieldedFeeKind.TRANSFER], `FeeKind.TransferOrShield`), rounded + * UP to whole duffs, so a lock of `amount + poolFee` pays the recipient at least `amount` + * (exactly, or less than one duff more). + */ +internal fun shieldPoolFeeDuffs(shieldFeeCredits: Long): Long = + Math.addExact(ceilCreditsToDuffs(shieldFeeCredits), ShieldedBalanceServiceImpl.ASSET_LOCK_BASE_COST_DUFFS) + +/** + * The [retryReadErrors] `onError` for an external-send observation: logs that [what] is + * unreadable (so unknown) and when it is re-read ([retryDelayMs] of the attempt). + */ +internal fun logReadRetry( + what: String, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +): (Exception, Long) -> Unit = { cause, attempt -> + retryLog.warn("external send: {} unreadable; unknown, retrying in {} ms ({})", what, retryDelayMs(attempt), safeErrorSummary(cause)) +} + +private val retryLog = LoggerFactory.getLogger("de.schildbach.wallet.service.platform.sdk.ExternalSendRetry") + +/** + * The SDK's AUTO-withdrawal preflight ([ExternalSendSource.platformWithdrawalPreflight]): + * whether the account can fund any withdrawal, and the transition fee it reserves on its fee + * payer for all of its withdrawable (≥ minimum input) addresses, in credits (0 unless + * [canWithdraw]). DPP's minimum fee grows with the input count, so for a subset of those + * addresses it is an upper bound. + */ +internal data class PlatformWithdrawalPreflight(val canWithdraw: Boolean, val estimatedFeeCredits: Long) + +// ── Source seam ─────────────────────────────────────────────────────── + +/** + * Seam over everything [ExternalSendServiceImpl] touches (the SDK, the sibling send + * services, config), so the gating / wallet-pinning / no-double-broadcast orchestration + * is host-JVM unit-testable — the real calls need `libdash_sdk`. Raw native writes + * THROW (classified by the caller with [classifyBroadcastFailure]); sibling-service + * writes return their own [SdkWriteResult]. + */ +internal interface ExternalSendSource { + /** The dashj wallet session for a Core send; non-suspending (captured first). */ + fun currentCoreSession(): WalletSession? + + /** Same contract as [SdkDashPayWriteSource.boundWalletIdOrNull]. */ + suspend fun boundWalletIdOrNull(): String? + + /** + * The SDK wallet bound right now, WITHOUT suspending or starting the SDK (null when none, + * or not exactly one, is loaded): what the confirm step captures. + */ + fun currentBoundWalletIdOrNull(): String? + + /** [SdkL1SendService.cutoverCommittedOrThrow]: throws when unreadable. */ + suspend fun cutoverCommittedOrThrow(): Boolean + + /** `USE_KOTLIN_SDK_SHIELDED`, error-preserving: throws when unreadable. */ + suspend fun shieldedEnabledOrThrow(): Boolean + + /** The user's registered identity (base58), null when there is none; throws when unreadable. */ + suspend fun ownIdentityIdOrThrow(): String? + + /** + * [ownIdentityIdOrThrow] as it changes; emits [Result.failure] on a read error and keeps + * observing (re-subscribes with back-off), never completing on a transient failure. + */ + fun observeOwnIdentityId(): Flow> + + /** The 32-byte ids of the identities [walletIdHex] MANAGES (watched identities excluded). */ + suspend fun managedIdentityIds(walletIdHex: String): List + + // Reads + fun observeCoreMaxSendableDuffs(): Flow + + /** + * The Core balance an asset lock can spend — the SDK's CONFIRMED balance (in a block or + * InstantSend-locked), the figure the internal shield-from-wallet Max uses, capped at the + * SDK's max-sendable — in duffs; null when either is unknown or the cutover is not + * committed (fail closed). + */ + suspend fun coreAssetLockEligibleDuffs(): Long? + + fun observeShieldedBalance(): Flow + suspend fun platformAddressBalances(walletIdHex: String): List + suspend fun identityBalanceCredits(identityIdBase58: String): Long? + + /** True when Platform has the identity, false when it answered "none"; throws on failure. */ + suspend fun identityExists(identityIdBase58: String): Boolean + + /** The identity's DPNS label, null when it has none; throws on failure. */ + suspend fun usernameOf(identityIdBase58: String): String? + suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? + + /** The SDK wallet's spendable UTXO count for the Max shield reserve, null when unknown. */ + suspend fun spendableUtxoCount(): Int? + + // Writes + suspend fun sendCore(address: String, amount: Dash, emptyWallet: Boolean, session: WalletSession?): String + suspend fun shieldedWithdrawToCore(walletIdHex: String, address: String, amount: Dash): SdkWriteResult + suspend fun shieldedTransfer(walletIdHex: String, address: String, amount: Dash): SdkWriteResult + suspend fun shieldedUnshield(walletIdHex: String, address: String, amount: Dash): SdkWriteResult + suspend fun shieldedTopUpIdentity(walletIdHex: String, identityId: ByteArray, amount: Dash): SdkWriteResult + suspend fun shieldFromCore( + walletIdHex: String, + address: String, + amount: Dash + ): SdkWriteResult + suspend fun coreTopUpIdentity(identityIdBase58: String, amountDuffs: Long): SdkWriteResult + suspend fun platformTransfer(walletIdHex: String, to: PlatformAddressBytes, amountCredits: Long) + /** Platform addresses → an identity [walletIdHex] MANAGES (`topUpFromAddresses`). */ + suspend fun platformTopUpIdentity(walletIdHex: String, identityId: ByteArray, inputs: List) + + /** + * Platform addresses → an identity [walletIdHex] does NOT manage + * (`topUpExternalIdentityFromAddresses`, platform#5860); an identity Platform does not + * have fails `DashSdkError.NotFound` before anything is signed. + */ + suspend fun platformTopUpExternalIdentity(walletIdHex: String, identityId: ByteArray, inputs: List) + suspend fun identityWithdraw(walletIdHex: String, fromId: ByteArray, amountCredits: Long, coreAddress: String) + suspend fun identityTransferToAddress( + walletIdHex: String, + fromId: ByteArray, + to: PlatformAddressBytes, + amountCredits: Long + ) + suspend fun identityTransfer(walletIdHex: String, fromId: ByteArray, toId: ByteArray, amountCredits: Long) + + // Platform → Core (partial withdrawal) + + /** + * The SDK's AUTO-withdrawal preflight of [walletIdHex]'s Platform payment account + * ([PLATFORM_WITHDRAW_ACCOUNT_INDEX]) at [PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE] + * (`preflightWithdrawal`, an on-chain read; signs and spends nothing); throws when + * unreadable. + */ + suspend fun platformWithdrawalPreflight(walletIdHex: String): PlatformWithdrawalPreflight + + /** The version-locked minimum input amount of a Platform-address transition, in credits; throws when unreadable. */ + suspend fun platformMinInputCredits(walletIdHex: String): Long + + /** + * `withdrawCredits(coreAddress, inputs, …)`: withdraw exactly [inputs] (each one's credits + * from its address) to [coreAddress] at [PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE]. Throws on + * failure (classified by [classifyBroadcastFailure]). + */ + suspend fun platformWithdraw(walletIdHex: String, coreAddress: String, inputs: List) + + // → Shielded (third-party Orchard address); the [ShieldedBalanceService] write pipeline + + /** [ShieldedBalanceService.shieldFromCreditsToAddress] (Type 15 to [address]). */ + suspend fun platformShieldTo(walletIdHex: String, address: String, amount: Dash): SdkWriteResult + + /** [ShieldedBalanceService.shieldFromIdentityToAddress] (Type 21 from [fromId] to [address]). */ + suspend fun identityShieldTo( + walletIdHex: String, + fromId: ByteArray, + address: String, + amount: Dash + ): SdkWriteResult + + // Core → Platform (`fundFromAssetLockExternal`) + + /** + * The L1 funding gate ([SdkL1SendService.probeSendGate]): true only while the SDK's own + * Core wallet has a complete, current view of the chain to build an asset lock from. + */ + fun coreFundingGateOpen(): Boolean + + /** + * Run [build], a FRESH asset-lock build, under the pending-payment funding gate's shared + * selection lock ([de.schildbach.wallet.payments.PendingPaymentFundingGate]); null (nothing + * run) while an uncertain earlier payment's inputs are exposed or a wallet wipe ran. + */ + suspend fun withFreshCoreFunding(build: suspend () -> T): T? + + /** + * A P2PKH address of [walletIdHex]'s own Platform payment account + * ([EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX]) other than [excludeHash], for the remainder: + * the lowest unused index, else the lowest index (the selection the wallet's other + * self-payments use). Null when there is none; throws when unreadable. + */ + suspend fun ownPlatformRemainderAddress(walletIdHex: String, excludeHash: ByteArray): PlatformAddressBytes? + + /** + * `fundFromAssetLockExternal` of [record] from its wallet (BIP44 account + * [EXTERNAL_FUNDING_ACCOUNT_INDEX]): locks [PendingPlatformFunding.lockDuffs] and pays + * [PendingPlatformFunding.recipients]. [onAssetLockBuilt] gets the new lock's outpoint key + * synchronously on an SDK thread, before broadcast. Throws on failure. + */ + suspend fun fundPlatformExternal(record: PendingPlatformFunding, onAssetLockBuilt: (outPointHex: String) -> Unit) + + /** + * `resumeFundFromAssetLockExternal` of [record]'s tracked lock + * ([PendingPlatformFunding.outPointHex], required) with exactly its recipients. Throws on + * failure (an already-consumed lock as `AssetLockAlreadyConsumed`, see + * [isAssetLockAlreadyConsumed]). + */ + suspend fun resumePlatformFundingExternal(record: PendingPlatformFunding) + + /** + * The SDK's tracked status of [walletIdHex]'s asset lock [outPointHex] + * ([ASSET_LOCK_STATUS_CONSUMED] = done), null when the SDK tracks no such lock of that + * wallet; throws when unreadable. + */ + suspend fun trackedAssetLockStatus(walletIdHex: String, outPointHex: String): Int? + + /** + * Whether [walletIdHex] has any Platform-address funding lock + * ([ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP]) that is not Consumed, other than the locks + * [excludingOutPoints] (`:`, case-insensitive); throws when unreadable. + */ + suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String, excludingOutPoints: Set): Boolean +} + +/** Production [ExternalSendSource]. */ +@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) +internal class DashSdkExternalSendSource( + private val sdkService: DashSdkService, + private val sendPaymentService: SendPaymentService, + private val sdkL1SendService: SdkL1SendService, + private val cutoverUiDataService: CutoverUiDataService, + private val shieldedBalanceService: ShieldedBalanceService, + private val transparentTopUp: SdkTransparentTopUp, + private val usernameQueries: SdkUsernameQueries, + private val dashPayConfig: DashPayConfig, + private val identityConfig: BlockchainIdentityConfig, + private val walletData: WalletData, + private val fundingGate: PendingPaymentFundingGate +) : ExternalSendSource { + + private suspend fun manager(): org.dashfoundation.dashsdk.wallet.PlatformWalletManager { + sdkService.ensureStarted() + return checkNotNull(sdkService.walletManagerOrNull()) { "SDK wallet manager missing after ensureStarted()" } + } + + /** The PINNED wallet — never "whichever is current". */ + private suspend fun wallet(walletIdHex: String): org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet = + checkNotNull(manager().wallets.value[walletIdHex]) { "SDK wallet not loaded" } + + override fun currentCoreSession(): WalletSession? = sendPaymentService.currentWalletSession() + + override suspend fun boundWalletIdOrNull(): String? = manager().wallets.value.keys.singleOrNull() + + override fun currentBoundWalletIdOrNull(): String? = sdkService.loadedWalletIds().singleOrNull() + + override suspend fun cutoverCommittedOrThrow(): Boolean = sdkL1SendService.cutoverCommittedOrThrow() + + override suspend fun shieldedEnabledOrThrow(): Boolean = + dashPayConfig.getPreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED) == true + + override suspend fun ownIdentityIdOrThrow(): String? = ownIdentity( + identityConfig.getPreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), + identityConfig.getPreservingErrors(BlockchainIdentityConfig.CREATION_STATE) + ) + + override fun observeOwnIdentityId(): Flow> = + combine( + identityConfig.observePreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), + identityConfig.observePreservingErrors(BlockchainIdentityConfig.CREATION_STATE) + ) { id, state -> Result.success(ownIdentity(id, state)) } + .retryReadErrors( + Result.failure(IllegalStateException("identity record unreadable")), + onError = logReadRetry("identity record") + ) + + /** A registered identity; an unknown creation state throws (unknown, not "none"). */ + private fun ownIdentity(id: String?, state: String?): String? { + val creation = IdentityCreationState.valueOf(state ?: IdentityCreationState.NONE.name) + return id?.takeIf { it.isNotBlank() && creation >= IdentityCreationState.IDENTITY_REGISTERED } + } + + override suspend fun managedIdentityIds(walletIdHex: String): List = + wallet(walletIdHex).inMemoryIdentityStates().filter { !it.watched }.map { it.identityId } + + override fun observeCoreMaxSendableDuffs(): Flow = + combine( + sdkL1SendService.cutoverCommittedFlow(), + cutoverUiDataService.sdkMaxSendable, + cutoverUiDataService.sdkTotalBalance + ) { committed, maxSendable, total -> + // Only the SDK's own figures; never the frozen dashj balance. + if (committed == true) (maxSendable ?: total)?.value else null + } + + override suspend fun coreAssetLockEligibleDuffs(): Long? = + combine( + sdkL1SendService.cutoverCommittedFlow(), + cutoverUiDataService.sdkConfirmedBalance, + cutoverUiDataService.sdkMaxSendable + ) { committed, confirmed, maxSendable -> + // Only the SDK's own figures (ShieldedTransferViewModel's post-cutover source); + // never the frozen dashj ChainLocked fallback. The confirmed balance is wallet-wide, + // so it is capped by the SDK's max-sendable (the spendable sum, CoinJoin excluded). + // No per-funding-account figure is published, so this is the closest cheap bound; + // either figure unknown → unknown (no fallback to the other). + if (committed == true && confirmed != null && maxSendable != null) { + minOf(confirmed.value, maxSendable.value) + } else { + null + } + }.first() + + override fun observeShieldedBalance(): Flow = + flow { emitAll(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) } + // Any other DashPayConfig write re-emits the flag; don't restart the balance feeds for it. + .distinctUntilChanged() + .flatMapLatest { enabled -> + if (enabled != true) { + flowOf(null) + } else { + combine( + shieldedBalanceService.observeShieldedBalance(), + shieldedBalanceService.shieldedSyncStatus, + shieldedBalanceService.shieldedBalanceMaybeStale + ) { balance, status, stale -> + if (status == ShieldedSyncStatus.READY && !stale) balance else null + } + } + } + .retryReadErrors(null, onError = logReadRetry("shielded balance")) + + override suspend fun platformAddressBalances(walletIdHex: String): List = + wallet(walletIdHex).addressesWithBalances() + + override suspend fun identityBalanceCredits(identityIdBase58: String): Long? { + sdkService.ensureStarted() + val sdk = checkNotNull(sdkService.sdkOrNull()) { "SDK runtime missing after ensureStarted()" } + return sdk.identities.fetchBalance(identityIdBase58) + } + + override suspend fun identityExists(identityIdBase58: String): Boolean { + sdkService.ensureStarted() + val sdk = checkNotNull(sdkService.sdkOrNull()) { "SDK runtime missing after ensureStarted()" } + return sdk.identities.fetch(identityIdBase58) != null + } + + override suspend fun usernameOf(identityIdBase58: String): String? { + val documents = checkNotNull(usernameQueries.getDomainDocumentsByOwnerOrNull(identityIdBase58)) { + "DPNS lookup unavailable" + } + return documents.firstNotNullOfOrNull { it.data["label"] as? String } + } + + override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = + shieldedBalanceService.estimateShieldedFeeCredits(kind) + + override suspend fun spendableUtxoCount(): Int? = walletData.spendableUtxoCount().takeIf { it > 0 } + + override suspend fun sendCore(address: String, amount: Dash, emptyWallet: Boolean, session: WalletSession?): String = + sendPaymentService.sendCoins(address, amount, emptyWallet = emptyWallet, session = session) + + override suspend fun shieldedWithdrawToCore(walletIdHex: String, address: String, amount: Dash) = + shieldedBalanceService.withdrawToCoreExternal(address, amount, walletIdHex) + + override suspend fun shieldedTransfer(walletIdHex: String, address: String, amount: Dash) = + shieldedBalanceService.transferShieldedExternal(address, amount, walletIdHex) + + override suspend fun shieldedUnshield(walletIdHex: String, address: String, amount: Dash) = + shieldedBalanceService.unshieldToPlatformAddress(address, amount, walletIdHex) + + override suspend fun shieldedTopUpIdentity(walletIdHex: String, identityId: ByteArray, amount: Dash) = + shieldedBalanceService.topUpIdentityFromShielded(identityId, amount, walletIdHex) + + override suspend fun shieldFromCore(walletIdHex: String, address: String, amount: Dash) = + shieldedBalanceService.shieldFromWalletToAddress(address, amount, walletIdHex) + + override suspend fun coreTopUpIdentity(identityIdBase58: String, amountDuffs: Long): SdkWriteResult = + transparentTopUp.topUpReportingLockTxId(identityIdBase58, amountDuffs, newUserIntent = true) + + override suspend fun platformTransfer(walletIdHex: String, to: PlatformAddressBytes, amountCredits: Long) { + val manager = manager() + wallet(walletIdHex).transferCredits( + outputs = listOf( + org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.CreditOutput(to.addressType, to.hash, amountCredits) + ), + signerHandle = manager.signerHandle + ) + } + + override suspend fun platformTopUpIdentity(walletIdHex: String, identityId: ByteArray, inputs: List) { + val manager = manager() + manager.identityCredits.topUpFromAddresses( + walletHandle = wallet(walletIdHex).handle, + identityId = identityId, + inputs = inputs, + signerHandle = manager.signerHandle + ) + } + + override suspend fun platformTopUpExternalIdentity( + walletIdHex: String, + identityId: ByteArray, + inputs: List + ) { + val manager = manager() + manager.identityCredits.topUpExternalIdentityFromAddresses( + walletHandle = wallet(walletIdHex).handle, + identityId = identityId, + inputs = inputs, + signerHandle = manager.signerHandle + ) + } + + override suspend fun identityWithdraw(walletIdHex: String, fromId: ByteArray, amountCredits: Long, coreAddress: String) { + val manager = manager() + manager.identityCredits.withdraw( + walletHandle = wallet(walletIdHex).handle, + identityId = fromId, + amount = amountCredits, + toAddress = coreAddress, + signerHandle = manager.signerHandle + ) + } + + override suspend fun identityTransferToAddress( + walletIdHex: String, + fromId: ByteArray, + to: PlatformAddressBytes, + amountCredits: Long + ) { + val manager = manager() + manager.identityCredits.transferToAddresses( + walletHandle = wallet(walletIdHex).handle, + fromIdentityId = fromId, + outputs = listOf(FundingInput(to.addressType, to.hash, amountCredits)), + signerHandle = manager.signerHandle + ) + } + + override suspend fun identityTransfer(walletIdHex: String, fromId: ByteArray, toId: ByteArray, amountCredits: Long) { + val manager = manager() + manager.identityCredits.transfer( + walletHandle = wallet(walletIdHex).handle, + fromIdentityId = fromId, + toIdentityId = toId, + amount = amountCredits, + signerHandle = manager.signerHandle + ) + } + + override suspend fun platformWithdrawalPreflight(walletIdHex: String): PlatformWithdrawalPreflight { + val preflight = wallet(walletIdHex).preflightWithdrawal( + accountIndex = PLATFORM_WITHDRAW_ACCOUNT_INDEX, + coreFeePerByte = PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE + ) + return PlatformWithdrawalPreflight(preflight.canWithdraw, preflight.estimatedFee) + } + + override suspend fun platformMinInputCredits(walletIdHex: String): Long = wallet(walletIdHex).minAmounts().minInput + + override suspend fun platformWithdraw(walletIdHex: String, coreAddress: String, inputs: List) { + val manager = manager() + wallet(walletIdHex).withdrawCredits( + coreAddress = coreAddress, + inputs = inputs.map { + org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.WithdrawalInput(it.addressType, it.hash, it.credits) + }, + coreFeePerByte = PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE, + signerHandle = manager.signerHandle, + accountIndex = PLATFORM_WITHDRAW_ACCOUNT_INDEX + ) + } + + override suspend fun platformShieldTo(walletIdHex: String, address: String, amount: Dash) = + shieldedBalanceService.shieldFromCreditsToAddress(address, amount, walletIdHex) + + override suspend fun identityShieldTo(walletIdHex: String, fromId: ByteArray, address: String, amount: Dash) = + shieldedBalanceService.shieldFromIdentityToAddress(fromId, address, amount, walletIdHex) + + override fun coreFundingGateOpen(): Boolean = sdkL1SendService.probeSendGate().allowed + + override suspend fun withFreshCoreFunding(build: suspend () -> T): T? = + fundingGate.selectionLock.selectIfAllowed({ fundingGate.isFreshFundingBlocked() }, build)?.value + + private suspend fun database(): org.dashfoundation.dashsdk.persistence.DashDatabase { + sdkService.ensureStarted() + return checkNotNull(sdkService.databaseOrNull()) { "SDK database missing after ensureStarted()" } + } + + private fun walletIdBytes(walletIdHex: String): ByteArray = + checkNotNull(walletIdFromHex(walletIdHex)) { "malformed SDK wallet id" } + + override suspend fun ownPlatformRemainderAddress(walletIdHex: String, excludeHash: ByteArray): PlatformAddressBytes? { + val rows = database().platformAddressDao().observeByWallet(walletIdBytes(walletIdHex)).first() + .filter { + it.accountIndex == EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX && + it.addressType == 0 && + it.addressHash.size == 20 && + !it.addressHash.contentEquals(excludeHash) + } + val row = rows.filter { !it.isUsed }.minByOrNull { it.addressIndex } ?: rows.minByOrNull { it.addressIndex } + return row?.let { PlatformAddressBytes(0, it.addressHash.copyOf()) } + } + + override suspend fun fundPlatformExternal(record: PendingPlatformFunding, onAssetLockBuilt: (String) -> Unit) { + val manager = manager() + wallet(record.walletIdHex).fundFromAssetLockExternal( + amountDuffs = record.lockDuffs, + fundingAccountIndex = EXTERNAL_FUNDING_ACCOUNT_INDEX, + platformAccountIndex = EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX, + recipients = record.recipients, + signerHandle = manager.signerHandle, + coreSignerHandle = manager.mnemonicResolverHandle, + onAssetLockBuilt = { outPoint -> onAssetLockBuilt(outPoint.outPointHex) } + ) + } + + override suspend fun resumePlatformFundingExternal(record: PendingPlatformFunding) { + val outPoint = checkNotNull(record.outPointHex?.let(::parseOutPointHex)) { "no lock outpoint recorded" } + val manager = manager() + wallet(record.walletIdHex).resumeFundFromAssetLockExternal( + outPointTxid = outPoint.first, + outPointVout = outPoint.second, + platformAccountIndex = EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX, + recipients = record.recipients, + signerHandle = manager.signerHandle, + coreSignerHandle = manager.mnemonicResolverHandle + ) + } + + override suspend fun trackedAssetLockStatus(walletIdHex: String, outPointHex: String): Int? { + val walletId = walletIdBytes(walletIdHex) + return database().assetLockDao().getByOutPointHex(outPointHex) + ?.takeIf { it.walletId.contentEquals(walletId) } + ?.statusRaw + } + + override suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String, excludingOutPoints: Set): Boolean { + val excluded = excludingOutPoints.mapTo(HashSet()) { it.lowercase() } + return database().assetLockDao() + .observeByWalletAndFundingType(walletIdBytes(walletIdHex), ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP) + .first() + .any { it.statusRaw != ASSET_LOCK_STATUS_CONSUMED && it.outPointHex.lowercase() !in excluded } + } + + private companion object { + private val log = LoggerFactory.getLogger(DashSdkExternalSendSource::class.java) + } +} + +// ── Service ─────────────────────────────────────────────────────────── + +/** + * Default [ExternalSendService]. Orchestration only; every money move goes through an + * existing hardened path (the Core send funnel, [ShieldedBalanceService]'s write + * pipeline, [SdkTransparentTopUp]) or one SDK credits call classified by + * [classifyBroadcastFailure]. + * + * Funds safety, in order, for every [send]: + * 1. the Core [WalletSession] is captured before anything suspends (and the SDK wallet id + * by the caller, at confirmation); + * 2. single-flight: a concurrent send is refused ([NotSentReason.IN_PROGRESS]); + * 3. cutover committed (and the shielded flag for a shielded leg), error-preserving; + * 4. the SDK wallet the caller captured at confirmation (non-suspending, + * [ExternalSendService.currentWalletIdOrNull]) must be the bound one — a different or + * missing wallet is [NotSentReason.GENERIC] with nothing called; then + * [externalSendSupport] is enforced here (not only in the UI) with the own-identity + * facts read from the SDK; + * 5. right before the one write, the bound wallet is read again — a different wallet + * is [NotSentReason.GENERIC] with nothing called — and the write is pinned to the + * captured id; + * 6. the outcome: Broadcast → Sent, NotBroadcast → NotSent, Ambiguous / anything + * unclassified → [ExternalSendResult.MayHaveGoneThrough] (terminal). Core → Platform + * additionally persists its recipients before the call and is never NotSent once its + * asset lock was built ([sendCoreToPlatform], [resumePendingPlatformFunding]). + */ +@Singleton +class ExternalSendServiceImpl internal constructor( + private val source: ExternalSendSource, + private val network: AddressNetwork, + private val platformFundingStore: PlatformFundingStore, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val balancePollMs: Long = BALANCE_POLL_MS, + private val retryDelayMs: (Long) -> Long = ::readRetryDelayMs, + private val newFundingId: () -> String = { UUID.randomUUID().toString() }, + /** + * Seed the asset-lock kind ([AssetLockKind.PLATFORM]) in-memory the instant a + * Core → Platform lock is built, so the first classification of the L1 lock reads + * "Platform" instead of momentarily "Internal" while the SDK's `asset_locks` row + * lands — mirroring the shield/top-up/invite paths. No-op default keeps the + * host-JVM tests inert. + */ + private val seedAssetLockKind: (displayHex: String, kind: AssetLockKind) -> Unit = { _, _ -> }, + /** + * The wallet-wipe barrier every submission holds shared ([submitUnderWipeBarrier]): the app's + * one [FundingSelectionLock], the one Reset Wallet raises. No default: a private lock is one + * no wipe raises. + */ + private val fundingSelection: FundingSelectionLock +) : ExternalSendService { + + @Inject + constructor( + sdkService: DashSdkService, + sendPaymentService: SendPaymentService, + sdkL1SendService: SdkL1SendService, + cutoverUiDataService: CutoverUiDataService, + shieldedBalanceService: ShieldedBalanceService, + transparentTopUp: SdkTransparentTopUp, + usernameQueries: SdkUsernameQueries, + dashPayConfig: DashPayConfig, + identityConfig: BlockchainIdentityConfig, + walletData: WalletData, + fundingGate: PendingPaymentFundingGate, + assetLockKindResolver: AssetLockKindResolver + ) : this( + source = DashSdkExternalSendSource( + sdkService, sendPaymentService, sdkL1SendService, cutoverUiDataService, shieldedBalanceService, + transparentTopUp, usernameQueries, dashPayConfig, identityConfig, walletData, fundingGate + ), + network = AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id), + platformFundingStore = DashPayConfigPlatformFundingStore(dashPayConfig), + seedAssetLockKind = { displayHex, kind -> assetLockKindResolver.seed(displayHex, kind) }, + fundingSelection = fundingGate.selectionLock + ) + + /** Single-flight for [send] AND [resumePendingPlatformFunding]: the one owner of the funding record. */ + private val inFlight = AtomicBoolean(false) + + /** [resumePendingPlatformFunding] attempts per funding id, this process. */ + private val platformResumeAttempts = ConcurrentHashMap() + + // ── Reads ───────────────────────────────────────────────────────── + + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + override fun observeBalance(source: SendBalance): Flow = when (source) { + SendBalance.CORE -> this.source.observeCoreMaxSendableDuffs().map { duffs -> duffs?.let(::Dash) } + SendBalance.SHIELDED -> this.source.observeShieldedBalance() + SendBalance.PLATFORM -> polled { walletIdHex -> + val credits = this.source.platformAddressBalances(walletIdHex) + .fold(0L) { acc, input -> Math.addExact(acc, input.credits) } + creditsToDash(credits) + } + // distinctUntilChanged: an unrelated config write re-emits the same identity, which + // would otherwise restart the poll and re-fetch the balance at once. + SendBalance.IDENTITY -> this.source.observeOwnIdentityId().distinctUntilChanged().flatMapLatest { own -> + val id = own.getOrNull() + if (own.isFailure || id == null) { + flowOf(null) + } else { + polled { _ -> this.source.identityBalanceCredits(id)?.takeIf { it >= 0 }?.let(::creditsToDash) } + } + } + }.retryReadErrors(null, retryDelayMs, logReadRetry("$source balance", retryDelayMs)).distinctUntilChanged() + + /** Poll [read] (null on failure) on IO every [balancePollMs] while collected. */ + private fun polled(read: suspend (walletIdHex: String) -> Dash?): Flow = flow { + while (true) { + val value = try { + withContext(ioDispatcher) { source.boundWalletIdOrNull()?.let { read(it) } } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: balance read failed; unknown ({})", safeErrorSummary(e)) + null + } + emit(value) + delay(balancePollMs) + } + } + + override fun observeHasIdentity(): Flow = + source.observeOwnIdentityId() + .map, Boolean?> { result -> if (result.isFailure) null else result.getOrNull() != null } + .retryReadErrors(null, retryDelayMs, logReadRetry("identity record", retryDelayMs)) + .distinctUntilChanged() + + override fun currentWalletIdOrNull(): String? = try { + source.currentBoundWalletIdOrNull() + } catch (e: Exception) { + log.warn("external send: bound wallet unreadable ({})", safeErrorSummary(e)) + null + } + + override suspend fun isOwnIdentity(identityIdBase58: String): Boolean? { + val target = decodeIdentityId(identityIdBase58) ?: return false + return try { + withContext(ioDispatcher) { + val walletIdHex = source.boundWalletIdOrNull() ?: return@withContext null + source.managedIdentityIds(walletIdHex).any { it.contentEquals(target) } + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: managed-identity lookup failed; unknown ({})", safeErrorSummary(e)) + null + } + } + + override suspend fun resolveIdentity(identityIdBase58: String): IdentityResolution { + val id = identityIdBase58.trim() + if (decodeIdentityId(id) == null) return IdentityResolution.NotFound + val exists = try { + withContext(ioDispatcher) { source.identityExists(id) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: identity lookup failed; unknown ({})", safeErrorSummary(e)) + return IdentityResolution.Unknown + } + if (!exists) return IdentityResolution.NotFound + // The name is display-only: a failed name lookup still confirms the identity. + val username = try { + withContext(ioDispatcher) { source.usernameOf(id) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: username lookup failed; showing the identity without a name ({})", safeErrorSummary(e)) + null + } + return IdentityResolution.Found(username) + } + + override suspend fun estimateFee(source: SendBalance, destinationKind: SendBalance): FeeEstimate? = + try { + withContext(ioDispatcher) { estimateFeeInner(source, destinationKind) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: fee estimate failed; unknown ({})", safeErrorSummary(e)) + null + } + + /** + * - Core → Core: the SDK send's size-based fee reserve ([sendAllFeeReserveDuffs] over the + * spendable UTXO count; the flat [SEND_ALL_FEE_RESERVE_DUFFS] when unknown), an upper + * bound the real (smaller) fee never exceeds. A Max (drain) takes it OUT of the amount; + * any other send pays it on top. + * - Core → Shielded: the shield pool fee ([shieldPoolFeeDuffs]), paid ON TOP of the + * amount ([send] locks `amount + pool fee`, the recipient receives `amount`); the L1 + * fee of the lock is extra and unknown, so not exact. + * - Core → Platform: [coreToPlatformFeeDuffs], paid ON TOP of the amount — the L1 + * asset-lock fee reserve (an upper bound) plus the Platform-fee margin, whose unused + * part lands on the wallet's own Platform address. Not exact; null when the UTXO + * count is unknown. + * - Core → Identity: only the L1 asset-lock fee reserve ([assetLockMaxFeeReserve], an + * upper bound), paid ON TOP of the amount — the top-up locks exactly the amount + * ([ExternalSendSource.coreTopUpIdentity]). Platform's top-up fee is metered by Rust + * and taken out of the locked amount, so it is not included. Not exact; null when the + * UTXO count is unknown. + * - Shielded → *: the flat single-note pool fee of the transition; more notes cost more. + * Shielded → Core adds the asset unlock's [WITHDRAWAL_CORE_FEE_DUFFS], withdrawn on top + * of the amount. + * - Platform → *, Identity → *: Rust meters these at execution; no + * pre-send figure exists, so null. (Platform → Core's withdrawal preflight estimate is + * only the fee payer's reserve, not the fee of this exact set of inputs; the Core fee of + * the asset unlock, [WITHDRAWAL_CORE_FEE_DUFFS], is withdrawn on top of the amount, so + * the recipient still receives the confirmed amount exactly. Platform/Identity → + * Shielded add the shielded compute fee to the metered one.) + */ + private suspend fun estimateFeeInner(source: SendBalance, destinationKind: SendBalance): FeeEstimate? = + when (source) { + SendBalance.CORE -> when (destinationKind) { + SendBalance.CORE -> FeeEstimate(Dash(coreSendFeeReserveDuffs()), exact = false) + SendBalance.SHIELDED -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { + FeeEstimate(Dash(shieldPoolFeeDuffs(it)), exact = false) + } + SendBalance.PLATFORM -> this.source.spendableUtxoCount()?.let { + FeeEstimate(Dash(coreToPlatformFeeDuffs(it)), exact = false) + } + SendBalance.IDENTITY -> this.source.spendableUtxoCount()?.let { + FeeEstimate(assetLockMaxFeeReserve(it), exact = false) + } + } + SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destinationKind))?.let { + val poolFee = ceilCreditsToDuffs(it) + val fee = if (destinationKind == SendBalance.CORE) { + Math.addExact(poolFee, WITHDRAWAL_CORE_FEE_DUFFS) + } else { + poolFee + } + FeeEstimate(Dash(fee), exact = false) + } + SendBalance.PLATFORM, SendBalance.IDENTITY -> null + } + + /** + * - Core → Core: the SDK's max-sendable L1 figure, GROSS of the drain fee (the drain + * delivers it minus the fee — the Basic send's `sendAllBalance` semantics). Null (Max + * unavailable) unless it exceeds the fee reserve [estimateFee] shows, so the confirmed + * recipient amount (amount − fee) is always positive. + * - Core → Shielded: [coreToShieldedMaxDuffs] — from the asset-lock-eligible balance, + * less the L1 fee reserve and the shield pool fee. + * - Core → Platform: [coreToPlatformMaxDuffsOrNull] — the same eligible balance less the + * L1 fee reserve and the Platform-fee margin. + * - Shielded → *: the READY balance minus the single-note pool fee; a Max send also + * retries once with the exact deficit the note selection reports. Shielded → Core + * withdraws the Max itself (the recipient receives it minus [WITHDRAWAL_CORE_FEE_DUFFS]), + * so it is null unless it reaches DPP's [PLATFORM_MIN_WITHDRAWAL_CREDITS] (the recipient + * amount is then always positive). + * - Platform → Core: [platformToCoreMaxDuffsOrNull] — what the recipient receives from the + * largest withdrawal the send's input selection accepts (the first-sorting input keeps + * the SDK preflight's fee reserve; DPP carves the Core fee out of the withdrawal). The + * amount page treats it as the bound itself: unknown blocks Continue, never the balance. + * - Platform → Identity: [platformToIdentityMaxDuffsOrNull] — the largest top-up whose + * first-sorting input keeps [PLATFORM_TOP_UP_FEE_RESERVE_CREDITS]; a bound like Core's. + * - Everything else: null (no pre-send fee figure). + */ + override suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? = try { + when (source) { + SendBalance.CORE -> when (destinationKind) { + SendBalance.CORE -> withContext(ioDispatcher) { coreToCoreMaxDuffs() }?.let(::Dash) + SendBalance.SHIELDED -> withContext(ioDispatcher) { coreToShieldedMaxDuffs() }?.let(::Dash) + SendBalance.PLATFORM -> withContext(ioDispatcher) { coreToPlatformMaxDuffsOrNull() }?.let(::Dash) + SendBalance.IDENTITY -> null + } + SendBalance.SHIELDED -> { + val balance = this.source.observeShieldedBalance().first() + val feeCredits = withContext(ioDispatcher) { + this@ExternalSendServiceImpl.source.shieldedFeeCredits(shieldedKindFor(destinationKind)) + } + if (balance == null || feeCredits == null) { + null + } else { + val max = balance - Dash(ceilCreditsToDuffs(feeCredits)) + if (destinationKind == SendBalance.CORE) { + max.takeIf { it.duffs >= ceilCreditsToDuffs(PLATFORM_MIN_WITHDRAWAL_CREDITS) } + } else { + max.takeIf { it.isPositive } + } + } + } + SendBalance.PLATFORM -> when (destinationKind) { + SendBalance.CORE -> withContext(ioDispatcher) { platformToCoreMaxDuffsOrNull() }?.let(::Dash) + SendBalance.IDENTITY -> withContext(ioDispatcher) { platformToIdentityMaxDuffsOrNull() }?.let(::Dash) + SendBalance.SHIELDED, SendBalance.PLATFORM -> null + } + SendBalance.IDENTITY -> null + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: max sendable unreadable ({})", safeErrorSummary(e)) + null + } + + /** + * The Platform → Core Max from the same reads [sendPlatformToCore] makes (the bound wallet's + * address balances, the SDK's minimum input and its withdrawal preflight fee), so the + * Amount page allows exactly what the send selects inputs for ([platformToCoreMaxDuffs]). + * Null when any of them is unknown or the account cannot withdraw; throws when a read fails. + */ + private suspend fun platformToCoreMaxDuffsOrNull(): Long? { + val walletIdHex = source.boundWalletIdOrNull() ?: return null + val candidates = source.platformAddressBalances(walletIdHex) + val minInput = source.platformMinInputCredits(walletIdHex).takeIf { it > 0 } ?: return null + val preflight = source.platformWithdrawalPreflight(walletIdHex) + if (!preflight.canWithdraw) return null + val feeReserve = preflight.estimatedFeeCredits.takeIf { it > 0 } ?: return null + return platformToCoreMaxDuffs(candidates, feeReserve, minInput) + } + + /** + * The Platform → Identity Max from the same reads the top-up makes (the bound wallet's + * address balances and the SDK's minimum input), see [platformToIdentityMaxDuffs]. The + * same for a managed and an external identity: both build the same transition. Null when + * a figure is unknown; throws when a read fails. + */ + private suspend fun platformToIdentityMaxDuffsOrNull(): Long? { + val walletIdHex = source.boundWalletIdOrNull() ?: return null + val candidates = source.platformAddressBalances(walletIdHex) + val minInput = source.platformMinInputCredits(walletIdHex).takeIf { it > 0 } ?: return null + return platformToIdentityMaxDuffs(candidates, minInput) + } + + /** The Core send fee reserve: size-based, the flat reserve when the UTXO count is unknown. */ + private suspend fun coreSendFeeReserveDuffs(): Long = sendAllFeeReserveDuffs(source.spendableUtxoCount()) + + /** + * The Core → Core Max (gross, drained): the pooled max sendable, null when unknown or not + * above the fee reserve (Max unavailable — the drain would deliver nothing). Throws when a + * read fails. + */ + private suspend fun coreToCoreMaxDuffs(): Long? { + val pooled = source.observeCoreMaxSendableDuffs().first() ?: return null + return pooled.takeIf { it > coreSendFeeReserveDuffs() } + } + + /** + * The Core → Shielded Max, mirroring the internal shield-from-wallet Max's source + * ([ExternalSendSource.coreAssetLockEligibleDuffs]): eligible − the L1 asset-lock fee + * reserve ([assetLockMaxFeeReserve], reserved up front) − the shield pool fee. Null when + * any figure is unknown or the result is not positive. Throws when a read fails. + */ + private suspend fun coreToShieldedMaxDuffs(): Long? { + val eligible = source.coreAssetLockEligibleDuffs() ?: return null + val utxoCount = source.spendableUtxoCount() ?: return null + val feeCredits = source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER) ?: return null + val max = eligible - assetLockMaxFeeReserve(utxoCount).duffs - shieldPoolFeeDuffs(feeCredits) + return max.takeIf { it > 0 } + } + + /** + * The Core → Platform Max: [coreToPlatformMaxDuffs] of the asset-lock-eligible balance, + * null when a figure is unknown, the result is not positive, or it is below the Platform + * minimum output. Throws when a read fails. + */ + private suspend fun coreToPlatformMaxDuffsOrNull(): Long? { + val eligible = source.coreAssetLockEligibleDuffs() ?: return null + val utxoCount = source.spendableUtxoCount() ?: return null + return coreToPlatformMaxDuffs(eligible, utxoCount) + ?.takeIf { it >= ceilCreditsToDuffs(PLATFORM_MIN_OUTPUT_CREDITS) } + } + + // ── Send ────────────────────────────────────────────────────────── + + override suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + // (1) Captured before anything can suspend. + val coreSession = if (source == SendBalance.CORE && destination is SendDestination.Core) { + this.source.currentCoreSession() + } else { + null + } + // (2) Single-flight. + if (!inFlight.compareAndSet(false, true)) { + log.warn("external send refused: another external send is in progress") + return ExternalSendResult.NotSent(NotSentReason.IN_PROGRESS) + } + return try { + withContext(ioDispatcher) { + sendInner(source, destination, amount, isMax, coreSession, expectedWalletIdHex) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Every pre-submission step returns its own NotSent; an exception escaping here + // came from a write path and may have submitted. + log.error("external send {} → {} failed unclassified; outcome unknown ({})", source, kindOf(destination), safeErrorSummary(e)) + ExternalSendResult.MayHaveGoneThrough + } finally { + inFlight.set(false) + } + } + + private suspend fun sendInner( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + coreSession: WalletSession?, + expectedWalletIdHex: String? + ): ExternalSendResult { + val pair = "$source → ${kindOf(destination)}" + if (!amount.isPositive) return notSent(pair, NotSentReason.GENERIC, "non-positive amount") + // The destination must be a valid one of THIS network (the UI parsed it, but the + // service does not trust that). + if (!destinationValid(destination)) return notSent(pair, NotSentReason.GENERIC, "invalid destination") + + // (3) Engine ownership / flags, error-preserving. + val committed = readOrNull("cutover state") { this.source.cutoverCommittedOrThrow() } + ?: return notSent(pair, NotSentReason.GENERIC, "cutover state unreadable") + if (!committed) return notSent(pair, NotSentReason.NOT_SUPPORTED, "cutover not committed") + if (source == SendBalance.SHIELDED || destination is SendDestination.Shielded) { + val shielded = readOrNull("shielded flag") { this.source.shieldedEnabledOrThrow() } + ?: return notSent(pair, NotSentReason.GENERIC, "shielded flag unreadable") + if (!shielded) return notSent(pair, NotSentReason.NOT_SUPPORTED, "shielded flag off") + } + + // (4) The wallet the user confirmed with (captured by the caller without suspending) + // must be the one bound now; every later check and write is pinned to it. + val walletIdHex = expectedWalletIdHex + ?: return notSent(pair, NotSentReason.GENERIC, "no SDK wallet captured at confirmation") + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + val ownIdentity = readOrNull("own identity") { Result.success(this.source.ownIdentityIdOrThrow()) } + ?: return notSent(pair, NotSentReason.GENERIC, "identity record unreadable") + val ownIdentityId = ownIdentity.getOrNull() + val destinationIsOwnIdentity: Boolean? = when (destination) { + // A Core top-up needs an identity the SDK wallet manages; a Platform top-up picks + // its SDK call by it; an identity transfer only needs to tell the user's own + // identity (no self-transfer). + is SendDestination.Identity -> if (source == SendBalance.CORE || source == SendBalance.PLATFORM) { + decodeIdentityId(destination.identityIdBase58)?.let { target -> + readOrNull("managed identities") { + this.source.managedIdentityIds(walletIdHex).any { it.contentEquals(target) } + } + } + } else { + ownIdentityId?.let { decodeIdentityId(it) }?.let { own -> + decodeIdentityId(destination.identityIdBase58)?.contentEquals(own) + } + } + else -> null + } + val support = externalSendSupport(source, destination, ownIdentityId != null, destinationIsOwnIdentity) + if (support != SendSupport.SUPPORTED) { + return notSent(pair, NotSentReason.NOT_SUPPORTED, "pair not supported ($support)") + } + // Platform → Identity picks topUpFromAddresses (managed) or the external top-up by the + // managed set: unreadable is unknown, never "someone else's". + val platformTopUpOfManaged: Boolean? = + if (source == SendBalance.PLATFORM && destination is SendDestination.Identity) { + destinationIsOwnIdentity + ?: return notSent(pair, NotSentReason.GENERIC, "managed identities unreadable") + } else { + null + } + + // The identity source must be one this wallet manages (it signs with its keys). + val ownIdentityBytes: ByteArray? = if (source == SendBalance.IDENTITY) { + val own = ownIdentityId?.let(::decodeIdentityId) + ?: return notSent(pair, NotSentReason.GENERIC, "malformed own identity id") + val managed = readOrNull("managed identities") { + this.source.managedIdentityIds(walletIdHex).any { it.contentEquals(own) } + } ?: return notSent(pair, NotSentReason.GENERIC, "managed identities unreadable") + if (!managed) return notSent(pair, NotSentReason.NOT_SUPPORTED, "own identity not managed by the SDK wallet") + own + } else { + null + } + + // Unit conversions, before anything is submitted. + val amountCredits = try { + dashToCredits(amount) + } catch (e: ArithmeticException) { + return notSent(pair, NotSentReason.GENERIC, "amount out of range") + } + + // (5)+(6) The one write. + return when (source) { + SendBalance.CORE -> sendFromCore(pair, walletIdHex, destination, amount, amountCredits, isMax, coreSession) + SendBalance.SHIELDED -> sendFromShielded(pair, walletIdHex, destination, amount, isMax) + SendBalance.PLATFORM -> + sendFromPlatform(pair, walletIdHex, destination, amount, amountCredits, platformTopUpOfManaged) + SendBalance.IDENTITY -> sendFromIdentity( + pair, + walletIdHex, + checkNotNull(ownIdentityBytes) { "identity source without its id" }, + destination, + amount, + amountCredits + ) + } + } + + private suspend fun sendFromCore( + pair: String, + walletIdHex: String, + destination: SendDestination, + amount: Dash, + amountCredits: Long, + isMax: Boolean, + coreSession: WalletSession? + ): ExternalSendResult { + return when (destination) { + is SendDestination.Core -> sendCoreToCore(pair, walletIdHex, destination, amount, isMax, coreSession) + is SendDestination.Shielded -> sendCoreToShielded(pair, walletIdHex, destination, amount) + is SendDestination.Identity -> { + // The top-up marks no submission point of its own: from its start a wipe that + // cancels it leaves the outcome unknown. + val result = submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs) + } + when (result) { + // The resume gate completed an earlier, unfinished top-up of this + // identity instead: this request was not executed (no new lock). + is SdkWriteResult.Broadcast -> if (result.value.resumedEarlier) { + notSent(pair, NotSentReason.EARLIER_TOP_UP_COMPLETED, "an earlier top-up was completed instead") + } else { + ExternalSendResult.Sent(displayTxIdOrNull(result.value.lockTxIdDisplayHexOrNull)) + } + else -> mapWrite(pair, result) + } + } + is SendDestination.Platform -> sendCoreToPlatform(pair, walletIdHex, destination, amount, amountCredits) + } + } + + /** + * `fundFromAssetLockExternal`: lock `amount + margin` ([platformFundingLockDuffs]), pay the + * payee exactly [amountCredits], the remainder (fee payer) to one of the wallet's own + * Platform addresses. The SDK's resume contract is honoured in order: + * 1. the recipients are persisted ([PlatformFundingStore.write]) BEFORE the call — a failed + * write sends nothing — and at most one record is pending (a second send is refused); + * 2. `onAssetLockBuilt` records the lock's outpoint against them, durably, before the lock + * is broadcast; + * 3. the record is cleared on success, and when no lock was built and the call provably + * sent nothing (NotSent). Once the lock was built any failure keeps the record (the + * [resumePendingPlatformFunding] sweep pays the same payee) and is never NotSent. + */ + private suspend fun sendCoreToPlatform( + pair: String, + walletIdHex: String, + destination: SendDestination.Platform, + amount: Dash, + amountCredits: Long + ): ExternalSendResult { + val to = decodePlatformAddress(destination.address, network) + ?: return notSent(pair, NotSentReason.GENERIC, "invalid platform address") + if (to.addressType != 0) return notSent(pair, NotSentReason.NOT_SUPPORTED, "P2SH platform address") + if (amountCredits < PLATFORM_MIN_OUTPUT_CREDITS) { + return notSent(pair, NotSentReason.GENERIC, "below the platform minimum output") + } + val lockDuffs = try { + platformFundingLockDuffs(amount.duffs) + } catch (e: ArithmeticException) { + return notSent(pair, NotSentReason.GENERIC, "amount out of range") + } + val pending = try { + platformFundingStore.read() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send {}: pending platform funding unreadable; not sent ({})", pair, safeErrorSummary(e)) + return ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + if (pending != null) { + return notSent(pair, NotSentReason.PAYMENT_STILL_CONFIRMING, "an earlier Core → Platform send is pending") + } + val gateOpen = readOrNull("L1 funding gate") { this.source.coreFundingGateOpen() } + if (gateOpen != true) return notSent(pair, NotSentReason.NOT_SYNCED, "L1 funding gate closed") + val remainder = readOrNull("own platform address") { + this.source.ownPlatformRemainderAddress(walletIdHex, to.hash) + } ?: return notSent(pair, NotSentReason.GENERIC, "no own platform address for the remainder") + val record = try { + PendingPlatformFunding(newFundingId(), walletIdHex, lockDuffs, to, amountCredits, remainder, outPointHex = null) + } catch (e: IllegalArgumentException) { + return notSent(pair, NotSentReason.GENERIC, "malformed funding record") + } + // Under the wallet-wipe barrier from the record's write to its last update, so a Reset + // Wallet waits for all of it and its config clear can never be undone by a write of + // this record afterwards. The fresh-funding hold inside nests in this one. + return fundingSelection.withSharedSubmission( + refused = { notSent(pair, NotSentReason.GENERIC, "a wallet wipe is under way") }, + cancelled = { e, submitted -> + mapWrite(pair, wipeCancelledWriteResult("external send $pair", null, e, submitted)) + } + ) { mark -> fundPlatformUnderWipeBarrier(pair, walletIdHex, record, mark) } + } + + /** [sendCoreToPlatform] from the record's write on, under the wipe barrier ([mark]). */ + private suspend fun fundPlatformUnderWipeBarrier( + pair: String, + walletIdHex: String, + record: PendingPlatformFunding, + mark: SubmissionMark + ): ExternalSendResult { + try { + platformFundingStore.write(record) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send {}: could not persist the recipients; not sent ({})", pair, safeErrorSummary(e)) + return ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + + // From here the record exists: every path below either clears it (provably nothing + // built) or leaves it for the sweep. + val builtOutPoint = AtomicReference(null) + val outcome: SdkWriteResult = if (!stillBound(pair, walletIdHex)) { + SdkWriteResult.NotBroadcast("the bound wallet changed") + } else { + try { + this.source.withFreshCoreFunding { + mark.submitting() + this.source.fundPlatformExternal(record) { outPointHex -> + // SDK thread, before broadcast: short, no SDK calls, never throws. + builtOutPoint.set(outPointHex) + try { + platformFundingStore.writeBlocking(record.withOutPoint(outPointHex)) + } catch (e: Exception) { + // Accepted risk: if the process also dies before + // ensureOutPointRecorded, a no-outpoint record remains. The sweep + // keeps it (unknown ≠ unbuilt), and it blocks new Core → Platform + // sends until resolved. Two failures in a row; rare. + log.error("external send {}: could not record the lock outpoint, retried after the call ({})", pair, safeErrorSummary(e)) + } + seedPlatformLockKind(pair, outPointHex) + } + }?.let { SdkWriteResult.Broadcast(Unit) } + ?: SdkWriteResult.NotBroadcast(L1_PENDING_PAYMENT_UNPROTECTED_REASON) + } catch (e: CancellationException) { + // A built lock keeps its record; make its outpoint durable before unwinding. + builtOutPoint.get()?.let { outPoint -> + withContext(NonCancellable) { ensureOutPointRecorded(pair, record, outPoint) } + } + throw e + } catch (e: Exception) { + classifyBroadcastFailure(e) + } catch (e: LinkageError) { + SdkWriteResult.NotBroadcast("native library unavailable", e) + } + } + + val outPointHex = builtOutPoint.get() + if (outPointHex == null) { + // onAssetLockBuilt never fired: no lock was built, so nothing was broadcast. + return when (outcome) { + is SdkWriteResult.NotBroadcast -> { + clearPlatformFunding(pair, record.id) + mapWrite(pair, outcome) + } + is SdkWriteResult.Broadcast -> { + clearPlatformFunding(pair, record.id) + log.info("external send {}: sent", pair) + ExternalSendResult.Sent(null) + } + // Kept: the sweep clears it once no unconsumed funding lock exists. + is SdkWriteResult.Ambiguous -> mapWrite(pair, outcome) + } + } + if (outcome is SdkWriteResult.Broadcast) { + clearPlatformFunding(pair, record.id) + log.info("external send {}: sent", pair) + // The lock's txid is the display-hex part of `:`. + return ExternalSendResult.Sent(displayTxIdOrNull(outPointHex.substringBefore(':'))) + } + // The lock was built (and may be on the network): never NotSent. Make sure the + // outpoint is durable even if the callback's write failed; the sweep pays the payee. + ensureOutPointRecorded(pair, record, outPointHex) + log.warn( + "external send {}: lock built, funding not confirmed ({}: {}) — may have gone through; resumed automatically", + pair, + outcome.javaClass.simpleName, + safeErrorSummary((outcome as? SdkWriteResult.NotBroadcast)?.cause ?: (outcome as? SdkWriteResult.Ambiguous)?.cause) + ) + return ExternalSendResult.MayHaveGoneThrough + } + + /** + * Seed [AssetLockKind.PLATFORM] for the lock [outPointHex] (`:`; + * the txid part is already the resolver's display-hex key). Best-effort and never + * throws: it runs on the SDK's `onAssetLockBuilt` thread, and a miss only delays the + * "Platform" label until the SDK's durable funding type is readable. + */ + private fun seedPlatformLockKind(pair: String, outPointHex: String) { + try { + outPointHex.substringBefore(':') + .takeIf { it.length == 64 } + ?.let { seedAssetLockKind(it, AssetLockKind.PLATFORM) } + } catch (e: Exception) { + log.warn("external send {}: lock kind seed failed; the row may momentarily read Internal ({})", pair, safeErrorSummary(e)) + } + } + + /** Re-record [outPointHex] against [record] unless the store already holds exactly that. */ + private suspend fun ensureOutPointRecorded(pair: String, record: PendingPlatformFunding, outPointHex: String) { + try { + val stored = platformFundingStore.read() + if (stored == null || stored.id != record.id || stored.outPointHex != outPointHex) { + platformFundingStore.write(record.withOutPoint(outPointHex)) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.error("external send {}: could not record the lock outpoint; the lock cannot be resumed automatically ({})", pair, safeErrorSummary(e)) + } + } + + private suspend fun clearPlatformFunding(pair: String, id: String) { + try { + platformFundingStore.clear(id) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Left behind: the sweep clears it (no lock, or a consumed one). + log.warn("external send {}: could not clear the pending platform funding ({})", pair, safeErrorSummary(e)) + } + } + + // ── Core → Platform resume ──────────────────────────────────────── + + override suspend fun resumePendingPlatformFunding(): Int = try { + withContext(ioDispatcher) { resumePendingPlatformFundingInner() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("pending platform funding sweep failed; retried on the next trigger ({})", safeErrorSummary(e)) + 0 + } + + /** + * The sweep. It owns the record only while it holds [inFlight] (a running [send] may have + * just written a record whose lock is not built yet), and acts only for the bound wallet. + * - No outpoint: clear when the SDK has no unconsumed Platform-address funding lock of the + * wallet (the build never happened, or its lock is done); otherwise keep it — that lock + * cannot be attributed by amount or timing. The locks of completion-unconfirmed records + * are not counted: each is attributed, by outpoint, to its own earlier record (they stay + * non-terminal in the SDK, so counting them would keep this record, and block every + * later send, for good). Their set unreadable: keep (fail closed). + * - Outpoint, lock Consumed: done, clear. + * - Outpoint, lock not tracked: keep (nothing to resume, nothing to prove it never went out). + * - Outpoint, lock not Consumed: resume with exactly the persisted recipients, at most + * [MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS] times per process; clear only on success, + * which the SDK returns only with the funding's proved address balances. Every failure + * keeps the record, including the typed unconfirmed outcome ([isSubmissionOutcomeUnconfirmed]: + * a later sweep resubmits the same transition and the SDK proves its result) and the + * unauthenticated already-consumed answer ([isAssetLockAlreadyConsumed]). While the + * record is pending, a new Core → Platform send is refused as + * [NotSentReason.PAYMENT_STILL_CONFIRMING]. + * - Already-consumed answer (iOS `completionUnconfirmed`): the record is moved, marked, to + * the store's completion-unconfirmed set ([PlatformFundingStore.markCompletionUnconfirmed]), + * in one transaction — never deleted, since the answer proves nothing. From there it is + * not resumed automatically (in this process or any later one) and does not block a new + * Core → Platform send; it is kept for an explicit retry. If the move cannot be written + * the record stays pending (still blocking) and is not retried again in this process. + */ + private suspend fun resumePendingPlatformFundingInner(): Int { + val first = try { + platformFundingStore.read() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("pending platform funding unreadable or malformed; kept, not resumed ({})", safeErrorSummary(e)) + return 0 + } ?: return 0 + if (!inFlight.compareAndSet(false, true)) { + log.info("pending platform funding {}: an external send is running; sweep skipped", first.id) + return 0 + } + try { + // Re-read as the owner: the send that held [inFlight] may have changed it. + val record = platformFundingStore.read() ?: return 0 + if (record.completionUnconfirmed) { + // Never resumed automatically (the store keeps such records out of this slot). + log.warn("pending platform funding {}: completion unconfirmed; not resumed automatically", record.id) + return 0 + } + val committed = readOrNull("cutover state") { this.source.cutoverCommittedOrThrow() } + if (committed != true) return 0 + val bound = readOrNull("bound wallet") { this.source.boundWalletIdOrNull() } + if (bound == null || !bound.equals(record.walletIdHex, ignoreCase = true)) { + log.warn("pending platform funding {}: not of the bound wallet; kept", record.id) + return 0 + } + val outPointHex = record.outPointHex + if (outPointHex == null) { + // A failed outpoint write plus process death before ensureOutPointRecorded + // lands here with the lock open: kept below, and it blocks new Core → Platform + // sends until resolved. Rare (two failures in a row); accepted. + val unconfirmedOutPoints = try { + platformFundingStore.readCompletionUnconfirmed() + .filter { it.walletIdHex.equals(record.walletIdHex, ignoreCase = true) } + .mapNotNullTo(HashSet()) { it.outPointHex } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("pending platform funding {}: completion-unconfirmed records unreadable; kept ({})", record.id, safeErrorSummary(e)) + return 0 + } + val unconsumed = readOrNull("address funding locks") { + this.source.hasUnconsumedAddressFundingLocks(record.walletIdHex, unconfirmedOutPoints) + } ?: return 0 + if (unconsumed) { + log.warn("pending platform funding {}: no outpoint recorded and a funding lock is open; kept", record.id) + } else { + platformFundingStore.clear(record.id) + log.info("pending platform funding {}: no lock was left open; cleared", record.id) + } + return 0 + } + val status = try { + this.source.trackedAssetLockStatus(record.walletIdHex, outPointHex) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("pending platform funding {}: lock status unreadable; kept ({})", record.id, safeErrorSummary(e)) + return 0 + } + if (status == null) { + log.warn("pending platform funding {}: the SDK does not track its lock; kept", record.id) + return 0 + } + if (status == ASSET_LOCK_STATUS_CONSUMED) { + platformFundingStore.clear(record.id) + log.info("pending platform funding {}: lock consumed; cleared", record.id) + return 0 + } + val attempts = platformResumeAttempts.getOrDefault(record.id, 0) + if (attempts >= MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS) { + log.warn("pending platform funding {}: {} attempts this process; retried on the next start", record.id, attempts) + return 0 + } + platformResumeAttempts[record.id] = attempts + 1 + // Under the wallet-wipe barrier, with the wallet re-checked inside it: a Reset Wallet + // waits for the resume and its record updates, and one under way refuses it. Either + // way the record is kept (the wipe clears it with the wallet's configs). + return fundingSelection.withSharedSubmission( + refused = { + log.info("pending platform funding {}: a wallet wipe is under way; kept", record.id) + 0 + }, + cancelled = { _, _ -> + log.warn("pending platform funding {}: a wallet wipe cancelled the resume; kept", record.id) + 0 + } + ) { mark -> resumePlatformFundingUnderWipeBarrier(record, attempts + 1, mark) } + } finally { + inFlight.set(false) + } + } + + /** One resume of [record] (attempt [attempt]), under the wipe barrier ([mark]). */ + private suspend fun resumePlatformFundingUnderWipeBarrier( + record: PendingPlatformFunding, + attempt: Int, + mark: SubmissionMark + ): Int { + if (!stillBound("Core → Platform resume", record.walletIdHex)) return 0 + try { + mark.submitting() + this.source.resumePlatformFundingExternal(record) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Every failure keeps the record: only a proven completion (the call's success, or + // the SDK's Consumed status) clears it. The exception is not logged for the two + // typed answers below: their message embeds an unproven SDK diagnostic. + if (isSubmissionOutcomeUnconfirmed(e)) { + // Submitted, result unproven — e.g. Tenderdash's "tx already exists in cache" + // for the identical transition, after which the SDK's wait for its proved + // result failed (dashpay/platform#5556). The next sweep submits the same bytes + // again and the SDK waits again; DAPI answers that wait with the committed + // transition and its proof, which completes the resume and clears the record. + log.warn( + "pending platform funding {}: submitted, outcome unproven ({}, attempt {}); kept, re-checked on the next sweep", + record.id, + e.javaClass.simpleName, + attempt + ) + } else if (isAssetLockAlreadyConsumed(e)) { + // Unauthenticated (the SDK documents that completion must not be inferred from + // it), and no proved query shows whether an asset lock is spent + // (dashpay/platform#5823 refuses AddressFundingFromAssetLock for that reason). + // As iOS: completion unconfirmed — kept for an explicit retry, but no longer + // resumed automatically (Platform would only repeat it) and no longer blocking + // a new send. Not retried again in this process either way. + platformResumeAttempts[record.id] = MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS + try { + platformFundingStore.markCompletionUnconfirmed(record.id) + log.warn( + "pending platform funding {}: Platform reports the lock already consumed, unproven; " + + "kept as completion unconfirmed", + record.id + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn( + "pending platform funding {}: Platform reports the lock already consumed, unproven; " + + "could not mark it, kept pending ({})", + record.id, + safeErrorSummary(e) + ) + } + } else { + log.warn("pending platform funding {}: resume failed (attempt {}); kept ({})", record.id, attempt, safeErrorSummary(e)) + } + return 0 + } catch (e: LinkageError) { + log.warn("pending platform funding {}: native library unavailable; kept ({})", record.id, safeErrorSummary(e)) + return 0 + } + platformFundingStore.clear(record.id) + log.info("pending platform funding {}: resumed and consumed", record.id) + return 1 + } + + /** + * A Max is the SDK drain (`emptyWallet`), whose amount is display-only: it spends + * whatever is spendable when the SDK builds it, the same as Basic Send's send-all. The + * check below is a best-effort guard, not a hard bound: the drain is only started while + * the SDK's max-sendable figure still equals the [amount] the user confirmed (anything + * else, or unreadable, is NotSent with nothing spent), but funds that arrive or leave + * between that check and the SDK's build are still drained. A hard cap would need an SDK + * capped-drain API. + */ + private suspend fun sendCoreToCore( + pair: String, + walletIdHex: String, + destination: SendDestination.Core, + amount: Dash, + isMax: Boolean, + coreSession: WalletSession? + ): ExternalSendResult { + if (isMax) { + val maxNow = try { + this.source.observeCoreMaxSendableDuffs().first() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send {}: max sendable unreadable before the drain; not sent ({})", pair, safeErrorSummary(e)) + return ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + if (maxNow != amount.duffs) { + return notSent(pair, NotSentReason.BALANCE_CHANGED, "the balance changed since the Max was confirmed") + } + } + // Not under [submitUnderWipeBarrier]: the Core send funnel takes the wipe barrier itself + // around its broadcast (SendCoinsTaskRunner), and [coreSession] pins it to this wallet. + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + return try { + val txId = this.source.sendCore(destination.address, amount, emptyWallet = isMax, session = coreSession) + log.info("external send {}: sent", pair) + ExternalSendResult.Sent(txId) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + classifyCoreSendThrowable(e).also { log.warn("external send {}: {} ({})", pair, it, safeErrorSummary(e)) } + } + } + + /** + * The recipient receives the confirmed [amount]: the lock is `amount + pool fee` + * ([shieldPoolFeeDuffs]), the fee Rust carves out of the lock. A Max already left the L1 + * fee reserve out of [amount] ([coreToShieldedMaxDuffs]), so there is no Max retry. + */ + private suspend fun sendCoreToShielded( + pair: String, + walletIdHex: String, + destination: SendDestination.Shielded, + amount: Dash + ): ExternalSendResult { + val feeCredits = readOrNull("shield pool fee") { this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER) } + ?: return notSent(pair, NotSentReason.GENERIC, "shield pool fee unknown") + val lock = try { + Dash(Math.addExact(amount.duffs, shieldPoolFeeDuffs(feeCredits))) + } catch (e: ArithmeticException) { + return notSent(pair, NotSentReason.GENERIC, "amount out of range") + } + return when (val result = shieldFromCoreChecked(pair, walletIdHex, destination.address, lock)) { + is SdkWriteResult.Broadcast -> when (result.value.outcome) { + ShieldFromWalletOutcome.COMPLETED -> + ExternalSendResult.Sent(displayTxIdOrNull(result.value.lockTxIdOrNull)) + ShieldFromWalletOutcome.SHIELD_PENDING_RETRY -> { + log.warn("external send {}: lock out, shield not submitted — returns to own shielded", pair) + ExternalSendResult.InterruptedFundsReturnToShielded + } + } + else -> mapWrite(pair, result) + } + } + + private suspend fun shieldFromCoreChecked( + pair: String, + walletIdHex: String, + address: String, + amount: Dash + ): SdkWriteResult = + // The shield's own submission hold nests in this one and marks its submission point. + submitUnderWipeBarrier(pair, walletIdHex) { this.source.shieldFromCore(walletIdHex, address, amount) } + + private suspend fun sendFromShielded( + pair: String, + walletIdHex: String, + destination: SendDestination, + amount: Dash, + isMax: Boolean + ): ExternalSendResult { + val identityId = (destination as? SendDestination.Identity)?.let { decodeIdentityId(it.identityIdBase58) } + suspend fun attempt(value: Dash): SdkWriteResult = submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + when (destination) { + is SendDestination.Core -> this.source.shieldedWithdrawToCore(walletIdHex, destination.address, value) + is SendDestination.Shielded -> this.source.shieldedTransfer(walletIdHex, destination.address, value) + is SendDestination.Platform -> this.source.shieldedUnshield(walletIdHex, destination.address, value) + is SendDestination.Identity -> this.source.shieldedTopUpIdentity( + walletIdHex, + checkNotNull(identityId) { "identity destination validated above" }, + value + ) + } + } + // To Core the asset unlock's Core fee comes out of the withdrawn amount: withdraw it on + // top so the recipient receives exactly the confirmed amount. A Max withdraws the Max + // itself (the confirm sheet shows the recipient receiving it minus the Core fee). + val value = if (destination is SendDestination.Core && !isMax) { + try { + Dash(Math.addExact(amount.duffs, WITHDRAWAL_CORE_FEE_DUFFS)) + } catch (e: ArithmeticException) { + return notSent(pair, NotSentReason.GENERIC, "amount out of range") + } + } else { + amount + } + var result = attempt(value) + val first = result + if (isMax && first is SdkWriteResult.NotBroadcast) { + val adjustment = shieldedMaxFeeAdjustment(value, first) + if (adjustment != null) { + log.info("external send {}: max spend short by the pool fee; retrying once", pair) + result = attempt(adjustment.adjustedAmount) + } + } + return mapWrite(pair, result) + } + + private suspend fun sendFromPlatform( + pair: String, + walletIdHex: String, + destination: SendDestination, + amount: Dash, + amountCredits: Long, + destinationIsManagedIdentity: Boolean? + ): ExternalSendResult { + return when (destination) { + is SendDestination.Core -> sendPlatformToCore(pair, walletIdHex, destination, amountCredits) + is SendDestination.Shielded -> shieldedWrite(pair, walletIdHex) { + this.source.platformShieldTo(walletIdHex, destination.address, amount) + } + is SendDestination.Platform -> { + val to = decodePlatformAddress(destination.address, network) + ?: return notSent(pair, NotSentReason.GENERIC, "invalid platform address") + nativeWrite(pair, walletIdHex) { this.source.platformTransfer(walletIdHex, to, amountCredits) } + } + is SendDestination.Identity -> { + val identityId = decodeIdentityId(destination.identityIdBase58) + ?: return notSent(pair, NotSentReason.GENERIC, "invalid identity id") + val candidates = readOrNull("platform address balances") { + this.source.platformAddressBalances(walletIdHex) + } ?: return notSent(pair, NotSentReason.GENERIC, "platform address balances unreadable") + if (amountCredits < PLATFORM_MIN_IDENTITY_FUNDING_CREDITS) { + return notSent(pair, NotSentReason.GENERIC, "below the identity funding minimum") + } + val minInput = readOrNull("platform minimum input") { this.source.platformMinInputCredits(walletIdHex) } + ?.takeIf { it > 0 } + ?: return notSent(pair, NotSentReason.GENERIC, "platform minimum input unknown") + // The first-sorting input pays the fee from what it keeps (DeductFromInput(0)). + val inputs = selectPlatformWithdrawalInputs(candidates, amountCredits, PLATFORM_TOP_UP_FEE_RESERVE_CREDITS, minInput) + ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount and fee") + val managed = destinationIsManagedIdentity + ?: return notSent(pair, NotSentReason.GENERIC, "managed identities unreadable") + // A NotFound from the external top-up (Platform has no such identity) is raised + // before signing: classifyBroadcastFailure reads it as NotBroadcast. + nativeWrite(pair, walletIdHex) { + if (managed) { + this.source.platformTopUpIdentity(walletIdHex, identityId, inputs) + } else { + this.source.platformTopUpExternalIdentity(walletIdHex, identityId, inputs) + } + } + } + } + } + + /** + * Partial withdrawal: the inputs take exactly the gross withdrawal ([selectPlatformWithdrawalInputs] + * over the cached address balances), the fee payer keeping the SDK preflight's estimated + * transition fee. The Core fee of the asset unlock comes out of the withdrawn amount, so the + * gross withdrawal is [amountCredits] + [WITHDRAWAL_CORE_FEE_CREDITS] + * ([coreWithdrawalCreditsOrNull], as for Identity → Core) and the recipient receives exactly + * [amountCredits]. Every refusal here happens before anything is signed (NotSent); the SDK + * re-checks each input against its on-chain balance before signing. + */ + private suspend fun sendPlatformToCore( + pair: String, + walletIdHex: String, + destination: SendDestination.Core, + amountCredits: Long + ): ExternalSendResult { + val grossCredits = coreWithdrawalCreditsOrNull(amountCredits) + ?: return notSent(pair, NotSentReason.GENERIC, "outside the platform withdrawal bounds") + val candidates = readOrNull("platform address balances") { this.source.platformAddressBalances(walletIdHex) } + ?: return notSent(pair, NotSentReason.GENERIC, "platform address balances unreadable") + val minInput = readOrNull("platform minimum input") { this.source.platformMinInputCredits(walletIdHex) } + ?.takeIf { it > 0 } + ?: return notSent(pair, NotSentReason.GENERIC, "platform minimum input unknown") + val preflight = readOrNull("withdrawal preflight") { this.source.platformWithdrawalPreflight(walletIdHex) } + ?: return notSent(pair, NotSentReason.GENERIC, "withdrawal preflight unreadable") + if (!preflight.canWithdraw) { + return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "the platform addresses cannot fund a withdrawal") + } + // A zero estimate would let the fee payer be drained: unknown, not free. + val feeReserve = preflight.estimatedFeeCredits.takeIf { it > 0 } + ?: return notSent(pair, NotSentReason.GENERIC, "withdrawal fee estimate unknown") + val inputs = selectPlatformWithdrawalInputs(candidates, grossCredits, feeReserve, minInput) + ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount and fee") + return nativeWrite(pair, walletIdHex) { this.source.platformWithdraw(walletIdHex, destination.address, inputs) } + } + + private suspend fun sendFromIdentity( + pair: String, + walletIdHex: String, + fromId: ByteArray, + destination: SendDestination, + amount: Dash, + amountCredits: Long + ): ExternalSendResult { + return when (destination) { + is SendDestination.Core -> { + // The Core fee comes out of the withdrawn amount: withdraw it on top, so the + // recipient receives exactly the confirmed amount (as Platform → Core). + val grossCredits = coreWithdrawalCreditsOrNull(amountCredits) + ?: return notSent(pair, NotSentReason.GENERIC, "outside the withdrawal bounds") + nativeWrite(pair, walletIdHex) { + this.source.identityWithdraw(walletIdHex, fromId, grossCredits, destination.address) + } + } + is SendDestination.Platform -> { + val to = decodePlatformAddress(destination.address, network) + ?: return notSent(pair, NotSentReason.GENERIC, "invalid platform address") + nativeWrite(pair, walletIdHex) { + this.source.identityTransferToAddress(walletIdHex, fromId, to, amountCredits) + } + } + is SendDestination.Identity -> { + val toId = decodeIdentityId(destination.identityIdBase58) + ?: return notSent(pair, NotSentReason.GENERIC, "invalid identity id") + nativeWrite(pair, walletIdHex) { this.source.identityTransfer(walletIdHex, fromId, toId, amountCredits) } + } + is SendDestination.Shielded -> shieldedWrite(pair, walletIdHex) { + this.source.identityShieldTo(walletIdHex, fromId, destination.address, amount) + } + } + } + + /** + * One [ShieldedBalanceService] write (it pins [walletIdHex] itself and classifies its own + * outcome), under the wipe barrier after the bound-wallet re-check; mapped by [mapWrite]. + */ + private suspend fun shieldedWrite( + pair: String, + walletIdHex: String, + call: suspend () -> SdkWriteResult + ): ExternalSendResult { + val result = submitUnderWipeBarrier(pair, walletIdHex) { mark -> + mark.submitting() + call() + } + if (result is SdkWriteResult.Broadcast) log.info("external send {}: sent", pair) + return mapWrite(pair, result) + } + + /** + * One raw SDK credits call, under the wipe barrier after the wallet re-check, classified by + * [classifyBroadcastFailure]. + */ + private suspend fun nativeWrite(pair: String, walletIdHex: String, call: suspend () -> Unit): ExternalSendResult { + val result: SdkWriteResult = submitUnderWipeBarrier(pair, walletIdHex) { mark -> + try { + mark.submitting() + call() + SdkWriteResult.Broadcast(Unit) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + classifyBroadcastFailure(e) + } catch (e: LinkageError) { + // A native-boundary failure before the call ran (e.g. UnsatisfiedLinkError). + SdkWriteResult.NotBroadcast("native library unavailable", e) + } + } + if (result is SdkWriteResult.Broadcast) log.info("external send {}: sent", pair) + return mapWrite(pair, result) + } + + /** + * [write] under the wallet-wipe barrier: a shared [FundingSelectionLock] submission hold, + * as every SDK broadcast takes ([FundingSelectionLock.withSharedSubmission]), with the final + * bound-wallet check ([stillBound]) INSIDE it, so a Reset Wallet either refuses the write + * before the check or waits for it to return. [write] calls [SubmissionMark.submitting] + * right before the call that may put something on the network (a nested submission hold + * marks it itself). + * - Refused (a wipe was under way): nothing ran, NotBroadcast (Not sent). + * - Cancelled by a wipe: NotBroadcast before the mark, Ambiguous after it + * ([wipeCancelledWriteResult]), never a cancellation that reads as "nothing happened". + * - Not the bound wallet: NotBroadcast, nothing called. + * Shared holds are reentrant, so a write whose own path holds the lock again nests in this one. + */ + private suspend fun submitUnderWipeBarrier( + pair: String, + walletIdHex: String, + write: suspend (SubmissionMark) -> SdkWriteResult + ): SdkWriteResult = fundingSelection.withSharedSubmission>( + refused = { e -> SdkWriteResult.NotBroadcast("a wallet wipe is under way", e) }, + cancelled = { e, submitted -> wipeCancelledWriteResult("external send $pair", null, e, submitted) } + ) { mark -> + if (!stillBound(pair, walletIdHex)) { + SdkWriteResult.NotBroadcast("the bound wallet changed") + } else { + write(mark) + } + } + + /** + * [hex] when it is a 64-char hex txid (the display-order form `AssetLockEntity` and the + * transaction result screen key on), else null: a missing or malformed txid is only a + * missing detail of a [ExternalSendResult.Sent], never a failure. + */ + private fun displayTxIdOrNull(hex: String?): String? = + hex?.takeIf { it.length == 64 && it.all { c -> c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F' } } + ?.lowercase() + + private fun mapWrite(pair: String, result: SdkWriteResult<*>): ExternalSendResult = when (result) { + is SdkWriteResult.Broadcast -> ExternalSendResult.Sent(null) + is SdkWriteResult.NotBroadcast -> { + val reason = notSentReasonFor(result) + log.warn("external send {}: not sent ({}; {})", pair, reason, safeErrorSummary(result.cause)) + ExternalSendResult.NotSent(reason) + } + is SdkWriteResult.Ambiguous -> { + log.error("external send {}: outcome unconfirmed — may have gone through; do NOT retry ({})", pair, safeErrorSummary(result.cause)) + ExternalSendResult.MayHaveGoneThrough + } + } + + /** Re-read the bound SDK wallet right before a write: it must still be [walletIdHex]. */ + private suspend fun stillBound(pair: String, walletIdHex: String): Boolean { + val now = readOrNull("bound wallet") { this.source.boundWalletIdOrNull() } + val same = now != null && now.equals(walletIdHex, ignoreCase = true) + if (!same) log.warn("external send {}: the bound SDK wallet changed before submission; not sent", pair) + return same + } + + private fun destinationValid(destination: SendDestination): Boolean = when (val parsed = + detectSendDestination(destination.display, network) + ) { + is DestinationParse.Valid -> parsed.destination::class == destination::class + else -> false + } + + private suspend fun readOrNull(what: String, read: suspend () -> T?): T? = try { + read() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: {} unreadable ({})", what, safeErrorSummary(e)) + null + } + + private fun notSent(pair: String, reason: NotSentReason, why: String): ExternalSendResult.NotSent { + log.info("external send {}: not sent ({}: {})", pair, reason, why) + return ExternalSendResult.NotSent(reason) + } + + companion object { + private val log = LoggerFactory.getLogger(ExternalSendServiceImpl::class.java) + + /** How often the Platform / identity balances (no live feed) are re-read while observed. */ + internal const val BALANCE_POLL_MS = 15_000L + + /** Unattended Core → Platform resume attempts per funding, per process. */ + internal const val MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS = 3 + + private fun kindOf(destination: SendDestination): String = when (destination) { + is SendDestination.Core -> "Core" + is SendDestination.Shielded -> "Shielded" + is SendDestination.Platform -> "Platform" + is SendDestination.Identity -> "Identity" + } + + private fun shieldedKindFor(destinationKind: SendBalance): ShieldedFeeKind = when (destinationKind) { + SendBalance.CORE -> ShieldedFeeKind.WITHDRAWAL + SendBalance.SHIELDED -> ShieldedFeeKind.TRANSFER + SendBalance.PLATFORM -> ShieldedFeeKind.UNSHIELD + SendBalance.IDENTITY -> ShieldedFeeKind.IDENTITY_TOP_UP + } + } +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt new file mode 100644 index 0000000000..b52954e2ba --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt @@ -0,0 +1,186 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package de.schildbach.wallet.service.platform.sdk + +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeoutOrNull +import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicLong +import javax.inject.Inject +import javax.inject.Singleton + +/** + * What [PlatformAddressSyncService] needs from the SDK, as a seam so the + * start/stop fencing is testable on the host JVM. + */ +internal interface PlatformAddressSyncSource { + /** + * Whether the loop may run now: the cutover is committed, this process's + * bind pass established the app wallet, and the live SDK runtime has + * exactly that one wallet loaded. Never starts the SDK. Throws when the + * cutover state cannot be read (the caller then does not start). + */ + suspend fun ready(): Boolean + + suspend fun isRunning(): Boolean + + suspend fun start() + + /** Stop the loop of the live runtime; a no-op when no runtime is up. */ + suspend fun stop() +} + +private class DashSdkPlatformAddressSyncSource( + private val sdkService: DashSdkService, + private val sdkWalletBinder: SdkWalletBinder, + private val dashPayConfig: DashPayConfig +) : PlatformAddressSyncSource { + + /** The live, open manager, or null. Never boots the SDK. */ + private fun liveManager() = sdkService.walletManagerOrNull()?.takeUnless { it.isClosed } + + override suspend fun ready(): Boolean { + val cutoverCommitted = dashPayConfig.cutoverCommittedOrThrow() + if (!cutoverCommitted || !sdkWalletBinder.bindEstablished.value) return false + return liveManager()?.wallets?.value?.size == 1 + } + + override suspend fun isRunning(): Boolean = liveManager()?.isPlatformAddressSyncRunning() == true + + override suspend fun start() { + checkNotNull(liveManager()) { "SDK wallet manager not running" }.startPlatformAddressSync() + } + + override suspend fun stop() { + liveManager()?.stopPlatformAddressSync() + } +} + +/** + * Starts and stops the SDK's Platform-address (BLAST) balance sync loop. + * + * Without it the wallet only knew the Platform-address balances it wrote + * itself (funding / transfer changesets): credits another wallet sent to one + * of our addresses never appeared. The loop is Rust-owned; each pass queries + * every loaded wallet's addresses incrementally, updates the wallet's + * in-memory balances (what `ManagedPlatformWallet.addressesWithBalances()` + * reads) and persists them through the SDK's persistence handler + * (`platform_addresses` rows, `platform_addresses_sync_states` watermark). A + * failed pass changes nothing: the last persisted balance stays. + * + * Cadence is the SDK default (15 s, Rust `DEFAULT_SYNC_INTERVAL_SECS`; the + * Kotlin SDK exposes no setter for this loop). It runs only while the + * blockchain service runs: [PlatformSyncService] starts it from its engine + * kick after the bind pass and stops it with the other engines on teardown + * and before a wallet wipe (whose SDK close also stops it natively, and whose + * removal cascade deletes the wallet's rows and watermark). + * + * Not `resetPlatformAddressSyncState()`: the SDK reserves that for an + * explicit "clear and resync" of Platform balances. A Core rescan does not + * touch Platform-address state, and a wipe removes the wallet instead. + * + * Fencing: [stop] bumps [stopGeneration] before it waits for an in-flight + * start, and a start refuses (or undoes itself) when the generation it was + * issued under has moved, so a stop can never be overtaken by a start that + * was decided before it. + */ +@Singleton +class PlatformAddressSyncService internal constructor( + private val source: PlatformAddressSyncSource, + private val stopLockTimeoutMs: Long = STOP_LOCK_TIMEOUT_MS +) { + @Inject + constructor( + sdkService: DashSdkService, + sdkWalletBinder: SdkWalletBinder, + dashPayConfig: DashPayConfig + ) : this(DashSdkPlatformAddressSyncSource(sdkService, sdkWalletBinder, dashPayConfig)) + + private val log = LoggerFactory.getLogger(PlatformAddressSyncService::class.java) + private val mutex = Mutex() + private val generation = AtomicLong(0) + + /** Sample before deciding to start; pass it to [startIfReady]. */ + fun stopGeneration(): Long = generation.get() + + /** + * Start the loop if [PlatformAddressSyncSource.ready] and no [stop] has + * happened since [expectedStopGeneration] was sampled. Idempotent. Never + * throws except [CancellationException]; returns whether the loop is + * running afterwards. + */ + suspend fun startIfReady(expectedStopGeneration: Long): Boolean = try { + mutex.withLock { + fun superseded() = generation.get() != expectedStopGeneration + when { + superseded() -> { + log.info("Platform address sync not started: an engine stop arrived since the start was decided") + false + } + !source.ready() -> { + log.info("Platform address sync not started: the SDK wallet is not bound yet") + false + } + source.isRunning() -> true + else -> { + source.start() + if (superseded()) { + // The stop that moved the generation timed out on the + // lock and could not reach the loop started here. + log.info("Platform address sync start superseded by a stop; stopping it again") + source.stop() + false + } else { + log.info("Platform address sync started") + true + } + } + } + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("Platform address sync start failed; the next engine kick retries", e) + false + } + + /** + * Stop the loop. Best-effort and failure-contained; never throws except + * [CancellationException]. Waits (bounded) for an in-flight start so the + * loop it starts is stopped too; past the bound that start stops itself. + */ + suspend fun stop() { + generation.incrementAndGet() + try { + val stopped = withTimeoutOrNull(stopLockTimeoutMs) { mutex.withLock { source.stop() } } != null + if (!stopped) { + log.warn("Platform address sync stop: a start is still in flight; it stops itself when it returns") + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("Platform address sync stop failed", e) + } + } + + private companion object { + const val STOP_LOCK_TIMEOUT_MS = 10_000L + } +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkDashPayWrites.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkDashPayWrites.kt index 787ac29db5..3bf5d549f4 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkDashPayWrites.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkDashPayWrites.kt @@ -144,7 +144,50 @@ internal const val REASON_PRE_BROADCAST_ASSET_LOCK_SELECTION = internal const val REASON_PRE_BROADCAST_ASSET_LOCK_SIGNING = "pre-broadcast asset-lock signing failure" +/** + * [classifyBroadcastFailure] reason for + * [DashSdkError.PlatformWallet.ShieldedIdentityDebitPending]: an EARLIER identity-funded + * shield (Type 21) is still unresolved, so the SDK neither built nor broadcast this one. + * Nothing was submitted; the same request works once shielded sync has reconciled the + * earlier debit. + */ +internal const val REASON_SHIELDED_IDENTITY_DEBIT_PENDING = + "pre-broadcast: an earlier identity shield is still unresolved" + +/** + * Whether [t], or an SDK error in its cause chain, is a TYPED "the submission may have + * executed, its result is unproven" outcome: rs-sdk `StateTransitionResultUnconfirmed` + * (dashpay/platform#5556) as [DashSdkError.StateTransitionResultUnconfirmed] (rs-sdk-ffi + * code 11) or, through platform-wallet, [DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed] + * (code 20), and the shielded / masternode-withdrawal siblings. Their message carries the + * SDK's diagnostic (a node's refusal, a timeout, a consensus error) and no proof, so no + * message match may read one as pre-broadcast or as a terminal answer. + * + * Not [DashSdkError.PlatformWallet.PublicContactRequestUnconfirmed]: that one refuses a NEW + * request before signing anything, while an EARLIER one is unresolved. + */ +internal fun isSubmissionOutcomeUnconfirmed(t: Throwable): Boolean { + var cause: Throwable? = t + var hops = 0 + while (cause != null && hops++ < 8) { + when (cause) { + is DashSdkError.StateTransitionResultUnconfirmed, + is DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed, + is DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed, + is DashSdkError.PlatformWallet.ShieldedCreateUnconfirmed, + is DashSdkError.PlatformWallet.ShieldedClaimUnconfirmed, + is DashSdkError.PlatformWallet.MasternodeWithdrawalUnconfirmed -> return true + } + cause = cause.cause + } + return false +} + internal fun classifyBroadcastFailure(t: Throwable): SdkWriteResult = when { + // FIRST, before any message arm: the SDK says the submission may have executed. Its + // message embeds an arbitrary diagnostic ("Insufficient funds", "no private key stored", + // …) that must never turn it into NotBroadcast. + isSubmissionOutcomeUnconfirmed(t) -> SdkWriteResult.Ambiguous(t) t is DashSdkError.InvalidParameter || t is DashSdkError.InvalidState || t is DashSdkError.NotFound || @@ -244,6 +287,11 @@ internal fun classifyBroadcastFailure(t: Throwable): SdkWriteResult = w // submitted and the selection released — retryable with a smaller // amount. The message arms below stay as the fallback for AAR lines // that still surface these as WalletOperation strings. + // Raised by the identity shields (Type 21) BEFORE building: an earlier identity + // debit is still unresolved, so this request was never built or broadcast (SDK KDoc + // of `ShieldedIdentityDebitPending` and of `shieldedShieldFromIdentity*`). + t is DashSdkError.PlatformWallet.ShieldedIdentityDebitPending -> + SdkWriteResult.NotBroadcast(REASON_SHIELDED_IDENTITY_DEBIT_PENDING, t) t is DashSdkError.PlatformWallet.CoreInsufficientFunds -> SdkWriteResult.NotBroadcast(REASON_PRE_BROADCAST_BUILD_SHORTFALL, t) t is DashSdkError.PlatformWallet.AssetLockInsufficientFunds -> @@ -343,7 +391,11 @@ internal fun classifyBroadcastFailure(t: Throwable): SdkWriteResult = w m.contains("platform address network mismatch") || m.contains("invalid core address") || m.contains("core address network mismatch") || - m.contains("overflows u64") + m.contains("overflows u64") || + // A third-party shield (Type 15 / Type 21 to a recipient) whose recipient + // this wallet's own shielded account recognizes: rs-platform-wallet + // `resolve_shield_recipient` refuses it before building anything. + m.contains("recipient belongs to this shielded account") } == true -> SdkWriteResult.NotBroadcast("pre-broadcast shielded build-input validation failure", t) else -> SdkWriteResult.Ambiguous(t) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkL1SendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkL1SendService.kt index 80179660bd..ee5a4186f1 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkL1SendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkL1SendService.kt @@ -1137,6 +1137,15 @@ internal class DashSdkL1SendSource( // ── The send service ────────────────────────────────────────────────── +/** + * Whether the cutover is committed, failing closed: an unreadable state THROWS instead of + * reading as "not committed" (read with its errors kept, + * [DashPayConfig.observePreservingErrors]); an absent state is a real answer, not + * committed. Top-level so services that cannot depend on [SdkL1SendService] (DI) share it. + */ +internal suspend fun DashPayConfig.cutoverCommittedOrThrow(): Boolean = + !dashjEngineMayStart(CutoverState.fromStored(observePreservingErrors(DashPayConfig.CUTOVER_STATE).first())) + /** * Phase 5b of the dashj → Kotlin SDK migration * (`docs/kotlin-sdk-migration-plan.md`): route the app's NORMAL L1 SEND — @@ -2357,10 +2366,7 @@ class SdkL1SendService internal constructor( * with its errors kept, [DashPayConfig.observePreservingErrors]). An absent * state is still a real answer: not committed. */ - suspend fun cutoverCommittedOrThrow(): Boolean = - !dashjEngineMayStart( - CutoverState.fromStored(dashPayConfig.observePreservingErrors(DashPayConfig.CUTOVER_STATE).first()) - ) + suspend fun cutoverCommittedOrThrow(): Boolean = dashPayConfig.cutoverCommittedOrThrow() /** * [cutoverCommittedOrThrow] as a tri-state: null when the state cannot be read. For a decision diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreation.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreation.kt index 1e5f32c8ea..d0fefabc87 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreation.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreation.kt @@ -1718,6 +1718,9 @@ class SdkShieldedUsernameCreation internal constructor( */ internal fun isInviteAlreadyUsedFailure(t: Throwable): Boolean { if (t is DashSdkError.PlatformWallet.ShieldedInviteAlreadyClaimed) return true + // A typed unconfirmed outcome is never terminal: its message carries an + // unproven diagnostic that the substrings below could match. + if (isSubmissionOutcomeUnconfirmed(t)) return false val m = t.message ?: return false return m.contains(ALREADY_CLAIMED_DISPLAY_MARKER, ignoreCase = true) || m.contains("nullifier", ignoreCase = true) || diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryService.kt index 92927bed61..75d6478576 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryService.kt @@ -47,6 +47,9 @@ internal fun ByteArray.toTxidHex(): String = Utils.HEX.encode(reversedArray()) */ internal fun isAlreadyConsumed(t: Throwable): Boolean { if (t is DashSdkError.PlatformWallet.AssetLockAlreadyConsumed) return true + // A typed unconfirmed outcome (dashpay/platform#5556) is not this answer, whatever its + // unproven diagnostic says: the resume is retried, and a definite refusal comes back plain. + if (isSubmissionOutcomeUnconfirmed(t)) return false var cause: Throwable? = t var hops = 0 while (cause != null && hops < 8) { diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUp.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUp.kt index 9a9996a72d..1e5fe6f987 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUp.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUp.kt @@ -28,6 +28,8 @@ import org.bitcoinj.core.Sha256Hash import org.dashfoundation.dashsdk.wallet.TrackedAssetLock import org.dashj.platform.dpp.identifier.Identifier import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton @@ -230,6 +232,21 @@ internal class DashSdkTransparentTopUpSource( // ── Service ─────────────────────────────────────────────────────────── +/** + * [SdkTransparentTopUp.topUpReportingLockTxId]'s [SdkWriteResult.Broadcast] payload: the + * identity's new [creditBalance] (or [SdkTransparentTopUp.BALANCE_ALREADY_CREDITED]) and, + * best-effort, the top-up asset lock's DISPLAY-order txid hex. + * + * [resumedEarlier]: the resume gate found an EARLIER unresolved top-up lock for this identity and + * completed THAT one (its amount, not the requested one); no new asset lock was built, so the + * requested top-up was NOT executed. + */ +data class TopUpOutcome( + val creditBalance: Long, + val lockTxIdDisplayHexOrNull: String?, + val resumedEarlier: Boolean = false +) + /** * TRANSPARENT-funded identity TOP-UP ("Buy Credits") — the post-cutover * replacement for the dashj asset-lock funding path in @@ -389,6 +406,45 @@ class SdkTransparentTopUp internal constructor( identityIdBase58: String, amountDuffs: Long, newUserIntent: Boolean + ): SdkWriteResult = topUpGuarded(identityIdBase58, amountDuffs, newUserIntent, onLockTxId = {}) + + /** + * [topUp], and on [SdkWriteResult.Broadcast] also the DISPLAY-order txid of the top-up's + * asset lock ([TopUpOutcome.lockTxIdDisplayHexOrNull]) — the same post-success capture that + * labels the lock "Topup". Best-effort: an unrecoverable txid is null and never changes the + * outcome. [TopUpOutcome.resumedEarlier] says the Broadcast completed an EARLIER unresolved + * top-up lock the resume gate found, not a new one of [amountDuffs]: the caller must not + * report it as this request. + */ + suspend fun topUpReportingLockTxId( + identityIdBase58: String, + amountDuffs: Long, + newUserIntent: Boolean + ): SdkWriteResult { + val lockTxId = AtomicReference(null) + val resumedEarlier = AtomicBoolean(false) + return when ( + val result = topUpGuarded( + identityIdBase58, + amountDuffs, + newUserIntent, + onLockTxId = { lockTxId.set(it) }, + onResumedEarlier = { resumedEarlier.set(true) } + ) + ) { + is SdkWriteResult.Broadcast -> + SdkWriteResult.Broadcast(TopUpOutcome(result.value, lockTxId.get(), resumedEarlier.get())) + is SdkWriteResult.NotBroadcast -> result + is SdkWriteResult.Ambiguous -> result + } + } + + private suspend fun topUpGuarded( + identityIdBase58: String, + amountDuffs: Long, + newUserIntent: Boolean, + onLockTxId: (String) -> Unit, + onResumedEarlier: () -> Unit = {} ): SdkWriteResult { synchronized(this) { when (guard) { @@ -407,7 +463,15 @@ class SdkTransparentTopUp internal constructor( } } val result = try { - withContext(ioDispatcher) { topUpTransparent(identityIdBase58, amountDuffs, newUserIntent) } + withContext(ioDispatcher) { + topUpTransparent( + identityIdBase58, + amountDuffs, + newUserIntent, + onLockTxId = onLockTxId, + onResumedEarlier = onResumedEarlier + ) + } } catch (t: Throwable) { // A thrown (non-cancellation) failure escaping the pipeline is, by // the money-path contract, treated as unconfirmed: it may have @@ -450,7 +514,19 @@ class SdkTransparentTopUp internal constructor( * rejected as already-consumed (see the catch below). Non-null also * means "this is the retry", so it can never loop. */ - skipLockOutpoint: Pair? = null + skipLockOutpoint: Pair? = null, + /** + * Receives the DISPLAY-order txid of the top-up's asset lock once it is known on a + * successful top-up (best-effort; see [topUpReportingLockTxId]). Must not throw. + */ + onLockTxId: (String) -> Unit = {}, + /** + * Called, on a [newUserIntent], before a [SdkWriteResult.Broadcast] that consumed an + * EARLIER request's unresolved top-up lock the resume gate found (its amount, not + * [amountDuffs]) instead of building a new one ([TopUpOutcome.resumedEarlier]). Must not + * throw. + */ + onResumedEarlier: () -> Unit = {} ): SdkWriteResult { // Fail closed unless the cutover is committed — pre-cutover this path // must submit nothing (the dashj path owns funding then). @@ -575,6 +651,7 @@ class SdkTransparentTopUp internal constructor( // the attempt that actually credited died before recording. try { val lockTxidDisplayHex = displayHexOf(existingLock.outpointTxid) + onLockTxId(lockTxidDisplayHex) seedAssetLockKind(lockTxidDisplayHex, AssetLockKind.TOPUP) recordTopUp(lockTxidDisplayHex, idBase58) } catch (t2: Throwable) { @@ -594,7 +671,9 @@ class SdkTransparentTopUp internal constructor( identityIdBase58, amountDuffs, newUserIntent, - skipLockOutpoint = existingLock.outpointTxid to existingLock.outpointVout + skipLockOutpoint = existingLock.outpointTxid to existingLock.outpointVout, + onLockTxId = onLockTxId, + onResumedEarlier = onResumedEarlier ) } return when (val classified = classifyBroadcastFailure(t)) { @@ -656,6 +735,7 @@ class SdkTransparentTopUp internal constructor( // first feed classification already reads "Topup"; the Room // insert below is the durable backstop across restarts. Same // display-hex key the resolver hashes into TopUpsDao.getByTxId. + onLockTxId(lockTxidDisplayHex) seedAssetLockKind(lockTxidDisplayHex, AssetLockKind.TOPUP) recordTopUp(lockTxidDisplayHex, idBase58) } else { @@ -670,6 +750,9 @@ class SdkTransparentTopUp internal constructor( log.warn("failed to capture/record top-up asset-lock txid", t) } + // On a new intent the resume branch completed an EARLIER request's lock (whatever amount + // it locked), not a top-up of amountDuffs. (On a rerun the lock is this request's own.) + if (existingLock != null && newUserIntent) onResumedEarlier() return SdkWriteResult.Broadcast(newBalance) } diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTxDetailProvider.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTxDetailProvider.kt index dfdb0f528a..02123a134a 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTxDetailProvider.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkTxDetailProvider.kt @@ -83,9 +83,10 @@ data class SdkTxDetail( /** * The Platform-funding role of this transaction when it is a wallet-authored * asset lock the app-side records identify (identity upgrade / top-up / - * invite). The SDK records these as INTERNAL moves; classified app-side so - * the detail sheet renders "sent to" + the "…Fee" title instead of the - * "moved internally to" internal-move presentation. Null for a plain move. + * invite / Platform-address or third-party shielded send). The SDK records these as INTERNAL + * moves; classified app-side so the detail sheet renders "sent to" + the + * kind's title instead of the "moved internally to" internal-move + * presentation. Null for a plain move. */ val assetLockKind: AssetLockKind? = null ) { diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt index 44764ff82d..377ea7ac74 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -80,6 +80,18 @@ enum class ShieldFromWalletOutcome { SHIELD_PENDING_RETRY } +/** + * Outcome payload of [ShieldedBalanceService.shieldFromWalletToAddress] on the + * [SdkWriteResult.Broadcast] arm: the staged [outcome] plus, best-effort, the txid of the L1 + * asset lock the call built ([lockTxIdOrNull], DISPLAY-order hex, the `AssetLockEntity` key). + * It is only reported with [ShieldFromWalletOutcome.COMPLETED]; null when the lock could not be + * identified, which never changes [outcome]. + */ +data class ShieldToAddressOutcome( + val outcome: ShieldFromWalletOutcome, + val lockTxIdOrNull: String? = null +) + /** * Readiness/sync state of the shielded runtime, for UI that must not show a * bare "0" while the pool is still catching up: @@ -97,6 +109,25 @@ enum class ShieldFromWalletOutcome { */ enum class ShieldedSyncStatus { NOT_READY, SYNCING, READY } +/** + * Which pool-paid shielded transition a fee estimate is for + * ([ShieldedBalanceService.estimateShieldedFeeCredits]); each maps to the SDK's + * `ShieldedProver.FeeKind` of the same name. + */ +enum class ShieldedFeeKind { + /** Type 16 shielded → shielded transfer (and Type 15/18 shield bundles). */ + TRANSFER, + + /** Type 17 shielded → Platform address. */ + UNSHIELD, + + /** Type 19 shielded → Core L1 withdrawal. */ + WITHDRAWAL, + + /** Type 22 shielded → existing identity top-up. */ + IDENTITY_TOP_UP +} + /** * Phase 4 service layer (`docs/kotlin-sdk-migration-plan.md`): the wallet's * SHIELDED (Orchard) balance runtime on the Dash Platform Kotlin SDK, @@ -516,4 +547,110 @@ interface ShieldedBalanceService { * the ~30s proof. */ suspend fun withdrawToCore(addressBase58: String, amount: Dash): SdkWriteResult + + // ── External sends (Advanced mode "External Send") ──────────────── + // + // The same writes as above, to a destination the user typed, pinned to the + // SDK wallet [expectedWalletIdHex] the caller captured before its first + // suspension: a runtime bound to another wallet is a + // [SdkWriteResult.NotBroadcast] before anything is submitted. + + /** [transferShielded] to an external Orchard address, no memo, pinned to [expectedWalletIdHex]. */ + suspend fun transferShieldedExternal( + toAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** [withdrawToCore] to an external Core address, pinned to [expectedWalletIdHex]. */ + suspend fun withdrawToCoreExternal( + addressBase58: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** + * Unshield [amount] (Type 17) to the bech32m Platform address [toPlatformAddress] + * (`dash1k…`/`dash1s…`, `tdash1…` off mainnet). Rust re-validates the address and + * its network. Blocks for the ~30s proof. + */ + suspend fun unshieldToPlatformAddress( + toPlatformAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** + * Top up the existing identity [identityId] (32 bytes) with [amount] credits from + * the shielded pool (Type 22). The identity does not have to be one this wallet + * manages; the flat pool fee ([ShieldedFeeKind.IDENTITY_TOP_UP]) is spent on top of + * [amount]. Blocks for the ~30s proof. + */ + suspend fun topUpIdentityFromShielded( + identityId: ByteArray, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** + * [shieldFromCredits] to an EXTERNAL Orchard recipient [toShieldedAddress] (Type 15, + * `shieldedShieldToRecipient`): [amount] credits from the wallet's own Platform payment + * addresses (account 0; the SDK selects the inputs, in ascending derivation order, and + * reserves the flat shield fee on top) become a note of the recipient. An address this + * wallet's own shielded account recognizes is refused by the SDK before anything is + * built ([SdkWriteResult.NotBroadcast]); malformed / wrong-network input is refused + * here. A spend that may have been submitted is [SdkWriteResult.Ambiguous] (never + * retried). Blocks for the ~30s proof. + */ + suspend fun shieldFromCreditsToAddress( + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** + * Shield [amount] credits from the wallet's managed identity [identityId] (32 bytes) to + * the EXTERNAL Orchard recipient [toShieldedAddress] (Type 21, + * `shieldedShieldFromIdentityToRecipient`). The identity pays [amount] plus the metered + * transition fee and the shielded compute fee. Same refusals as + * [shieldFromCreditsToAddress]; an earlier identity shield that is still unresolved is a + * [SdkWriteResult.NotBroadcast] (the SDK built nothing). Blocks for the ~30s proof. + */ + suspend fun shieldFromIdentityToAddress( + identityId: ByteArray, + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** + * [shieldFromWallet] to an EXTERNAL Orchard recipient [toShieldedAddress]: one fresh + * L1 asset lock + Type 18 paying that address. + * + * The staged contract differs from the self-shield in one place. + * [ShieldFromWalletOutcome.SHIELD_PENDING_RETRY] here means the lock is out and + * stage (b) PROVABLY did not submit (its failure is a definitive pre-broadcast one): + * the resume sweep ([resumePendingWalletShields]) re-derives the shield from the + * tracked lock and pays the SENDER's own default address, so the funds come back to + * the user's shielded balance, never to the external recipient. A stage (b) failure + * that may have submitted is [SdkWriteResult.Ambiguous]: the recipient may have been + * paid, and if not the same sweep returns the lock to the sender (the lock is + * single-use, so it is never paid twice). + * + * A [ShieldFromWalletOutcome.COMPLETED] result carries the new lock's display txid + * ([ShieldToAddressOutcome.lockTxIdOrNull]) when it could be identified. + */ + suspend fun shieldFromWalletToAddress( + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult + + /** + * The consensus-pinned flat pool fee, in credits, of a single-note (2-action) + * transition of [kind]; a spend selecting more notes pays more, so this is an + * estimate, not the exact fee. Null when the flag is off or the SDK cannot tell. + * Never throws (except cancellation). + */ + suspend fun estimateShieldedFeeCredits(kind: ShieldedFeeKind): Long? } diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt index b26cb415b4..e45ae3a58b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -67,6 +67,7 @@ import java.nio.ByteBuffer import java.nio.charset.CodingErrorAction import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton @@ -703,6 +704,27 @@ interface ShieldedSource { /** Type 15: shield credits into the wallet's own pool. Blocks for the proof. */ suspend fun shield(walletId: ByteArray, amountCredits: Long) + /** + * Type 15 to a THIRD PARTY: shield credits from the wallet's Platform payment addresses + * to [recipientRaw43] (the SDK refuses an address of this wallet's own shielded account). + * Blocks for the proof. Default throws: only the production source (and fakes that + * exercise it) need it. + */ + suspend fun shieldToRecipient(walletId: ByteArray, recipientRaw43: ByteArray, amountCredits: Long): Unit = + throw UnsupportedOperationException("shield to a recipient not supported by this source") + + /** + * Type 21 to a THIRD PARTY: shield credits from the managed identity [identityId] + * (32 bytes) to [recipientRaw43]. Blocks for the proof. Default throws: only the + * production source (and fakes that exercise it) need it. + */ + suspend fun shieldFromIdentityToRecipient( + walletId: ByteArray, + identityId: ByteArray, + recipientRaw43: ByteArray, + amountCredits: Long + ): Unit = throw UnsupportedOperationException("identity shield to a recipient not supported by this source") + /** * Type 18: build an L1 asset lock of [amountDuffs] from the SDK * wallet's OWN Core UTXOs, broadcast it over the SDK's SPV peers, @@ -761,6 +783,20 @@ interface ShieldedSource { /** Type 19: shielded → Core L1. Blocks for the proof. */ suspend fun withdraw(walletId: ByteArray, toCoreAddress: String, amountCredits: Long, coreFeePerByte: Int) + + /** + * Type 22: shielded → existing identity [identityId] (32 bytes). Blocks for the proof. + * Default throws: only the production source (and fakes that exercise it) need it. + */ + suspend fun identityTopUpFromPool(walletId: ByteArray, identityId: ByteArray, amountCredits: Long): Unit = + throw UnsupportedOperationException("identity top-up from the pool not supported by this source") + + /** + * The flat 2-action pool fee in credits for [kind]. Default throws: only the + * production source (and fakes that exercise it) need it. + */ + suspend fun estimateSpendFeeCredits(kind: ShieldedFeeKind): Long = + throw UnsupportedOperationException("fee estimate not supported by this source") } /** Production [ShieldedSource]: boots the SDK on demand. */ @@ -865,6 +901,29 @@ internal class DashSdkShieldedSource( override suspend fun shield(walletId: ByteArray, amountCredits: Long) = manager().shieldedShield(walletId = walletId, amount = amountCredits) + override suspend fun shieldToRecipient(walletId: ByteArray, recipientRaw43: ByteArray, amountCredits: Long) = + manager().shieldedShieldToRecipient( + walletId = walletId, + recipientRaw43 = recipientRaw43, + amount = amountCredits + ) + + override suspend fun shieldFromIdentityToRecipient( + walletId: ByteArray, + identityId: ByteArray, + recipientRaw43: ByteArray, + amountCredits: Long + ) { + // The proven post-debit identity balance is not needed: the identity balance + // reads re-fetch it. + manager().shieldedShieldFromIdentityToRecipient( + walletId = walletId, + identityId = identityId, + recipientRaw43 = recipientRaw43, + amount = amountCredits + ) + } + override suspend fun fundFromAssetLock( walletId: ByteArray, recipientRaw43: ByteArray, @@ -979,6 +1038,24 @@ internal class DashSdkShieldedSource( amount = amountCredits, coreFeePerByte = coreFeePerByte ) + + override suspend fun identityTopUpFromPool(walletId: ByteArray, identityId: ByteArray, amountCredits: Long) = + manager().shieldedIdentityTopUpFromPool( + walletId = walletId, + identityId = identityId, + amount = amountCredits + ) + + override suspend fun estimateSpendFeeCredits(kind: ShieldedFeeKind): Long = + manager().estimateShieldedFee( + when (kind) { + ShieldedFeeKind.TRANSFER -> ShieldedProver.FeeKind.TransferOrShield + ShieldedFeeKind.UNSHIELD -> ShieldedProver.FeeKind.Unshield + ShieldedFeeKind.WITHDRAWAL -> ShieldedProver.FeeKind.Withdrawal + ShieldedFeeKind.IDENTITY_TOP_UP -> ShieldedProver.FeeKind.IdentityTopUpFromPool + }, + SHIELD_NUM_ACTIONS + ) } /** @@ -1105,7 +1182,8 @@ class ShieldedBalanceServiceImpl internal constructor( */ private val sweepScope: CoroutineScope? = null, /** - * Seed the asset-lock kind ([AssetLockKind.SHIELD]) in-memory the instant a + * Seed the asset-lock kind ([AssetLockKind.SHIELD], or [AssetLockKind.SHIELD_EXTERNAL] + * for a shield to another wallet's address) in-memory the instant a * wallet-shield's funding lock is known, so the first engine-feed * classification of this L1 lock already reads "Shielded" instead of * momentarily "Internal" — mirroring the transparent/invite paths. No-op @@ -2199,7 +2277,18 @@ class ShieldedBalanceServiceImpl internal constructor( amount: Dash, fundingPath: String?, expectedWalletIdHex: String? = null, - onSubmitting: suspend () -> Unit = {} + onSubmitting: suspend () -> Unit = {}, + /** + * An external Orchard recipient (raw 43 bytes) instead of the wallet's own default + * address — [shieldFromWalletToAddress]. Changes the stage (b) classification, see + * [classifyWalletShieldFailure]. + */ + externalRecipientRaw43: ByteArray? = null, + /** + * Receives the display txid of the lock this call built, after a COMPLETED attempt, + * when it can be identified (best-effort; [shieldFromWalletToAddress]). Never throws. + */ + onLockTxId: (String) -> Unit = {} ): SdkWriteResult { val operation = if (fundingPath == null) "shieldFromWallet" else "shieldMixedFundsFromWallet" if (!isEnabled()) return SdkWriteResult.NotBroadcast("flag off") @@ -2256,7 +2345,7 @@ class ShieldedBalanceServiceImpl internal constructor( ) } - val recipient = try { + val recipient = externalRecipientRaw43 ?: try { source.shieldedDefaultAddress(walletId) } catch (t: Throwable) { if (t is CancellationException) throw t @@ -2393,19 +2482,34 @@ class ShieldedBalanceServiceImpl internal constructor( endSpend() } kickImmediateShieldedSync() - // Seed the funding lock's kind as SHIELD (best-effort, post- - // success) so the L1 asset lock renders "Shielded" on first - // classification instead of "Internal". The new lock is the + // Seed the funding lock's kind (best-effort, post-success) so + // the L1 asset lock renders "Shielded" on first classification + // instead of "Internal": SHIELD (a self-transfer) for the + // wallet's own pool, SHIELD_EXTERNAL (a send) when the Orchard + // recipient is another wallet's. Only this path knows which, so + // after a restart the funding-type fallback reads SHIELD for + // both (see [AssetLockKind.SHIELD_EXTERNAL]). The new lock is the // outPointHex absent from lockedBefore; its txid part (before // ':') is ALREADY display hex (AssetLockEntity keys on display), - // so it is the resolver's seed key directly. + // so it is the resolver's seed key directly. The same txid is + // reported to [onLockTxId] (External Send's result screen). try { source.walletShieldLocks(walletId) .map { it.outPointHex } .firstOrNull { it !in lockedBefore } ?.substringBefore(':') ?.takeIf { it.length == 64 } - ?.let { seedAssetLockKind(it, AssetLockKind.SHIELD) } + ?.let { + onLockTxId(it) + seedAssetLockKind( + it, + if (externalRecipientRaw43 != null) { + AssetLockKind.SHIELD_EXTERNAL + } else { + AssetLockKind.SHIELD + } + ) + } } catch (t: Throwable) { if (t is CancellationException) throw t log.warn("shield funding-lock kind seed failed; the row may momentarily read Internal", t) @@ -2413,7 +2517,10 @@ class ShieldedBalanceServiceImpl internal constructor( SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) } catch (t: Throwable) { if (t is CancellationException) throw t - classifyWalletShieldFailure(operation, walletId, lockedBefore, t) + classifyWalletShieldFailure( + operation, walletId, lockedBefore, t, + externalRecipient = externalRecipientRaw43 != null + ) } } ) @@ -2438,33 +2545,55 @@ class ShieldedBalanceServiceImpl internal constructor( operation: String, walletId: ByteArray, lockedBefore: Set, - failure: Throwable + failure: Throwable, + /** + * The lock pays someone else ([shieldFromWalletToAddress]). The resume sweep always + * pays the sender's own address, so SHIELD_PENDING_RETRY ("the funds come back to + * you") is only true when stage (b) provably did not submit; a stage (b) failure that + * may have reached Platform is Ambiguous (the recipient may have been paid). + */ + externalRecipient: Boolean = false ): SdkWriteResult { val newLocks = try { trackedShieldLocks(walletId).filter { it.outPointHex !in lockedBefore && it.resumable } } catch (t: Throwable) { if (t is CancellationException) throw t - log.error("shielded {} failed and the tracked-lock evidence is unreadable", operation, failure) + log.error("shielded {} failed and the tracked-lock evidence is unreadable ({})", operation, safeErrorSummary(failure)) + return SdkWriteResult.Ambiguous(failure) + } + if (newLocks.isNotEmpty() && externalRecipient && + classifyBroadcastFailure(failure) !is SdkWriteResult.NotBroadcast + ) { + log.error( + "shielded {}: the L1 asset lock is out and the shield transition to the external " + + "recipient may have been submitted — outcome unconfirmed; if it was not, the " + + "pending-shield sweep returns the lock to this wallet's own shielded balance ({})", + operation, + safeErrorSummary(failure) + ) return SdkWriteResult.Ambiguous(failure) } if (newLocks.isNotEmpty()) { log.error( "shielded {}: the L1 asset lock is out ({} tracked outpoint(s)) but the shield " + - "transition did not complete — it will be resumed automatically", - operation, newLocks.size, failure + "transition did not complete — it will be resumed automatically ({})", + operation, + newLocks.size, + safeErrorSummary(failure) ) return SdkWriteResult.Broadcast(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY) } return when (val classified = classifyBroadcastFailure(failure)) { is SdkWriteResult.NotBroadcast -> { - log.warn("shielded {} rejected pre-broadcast (no lock tracked)", operation, failure) + log.warn("shielded {} rejected pre-broadcast (no lock tracked) ({})", operation, safeErrorSummary(failure)) classified } else -> { log.error( "shielded {} outcome unconfirmed and no lock tracked (yet) — the pending-shield " + - "sweep recovers any lock once the SDK persists it", - operation, failure + "sweep recovers any lock once the SDK persists it ({})", + operation, + safeErrorSummary(failure) ) SdkWriteResult.Ambiguous(failure) } @@ -2613,6 +2742,121 @@ class ShieldedBalanceServiceImpl internal constructor( toAddress: String, amount: Dash, memo: String? + ): SdkWriteResult = transferShieldedInternal(toAddress, amount, memo, expectedWalletIdHex = null) + + override suspend fun transferShieldedExternal( + toAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult = transferShieldedInternal(toAddress, amount, memo = null, expectedWalletIdHex) + + override suspend fun withdrawToCoreExternal( + addressBase58: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult = withdrawToCoreInternal(addressBase58, amount, expectedWalletIdHex) + + override suspend fun unshieldToPlatformAddress( + toPlatformAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + val target = toPlatformAddress.trim() + if (target.isEmpty()) { + return notBroadcast("unshieldToPlatformAddress", "empty platform address", null) + } + return runShieldedWrite("unshieldToPlatformAddress", amount, expectedWalletIdHex) { walletId, credits -> + source.unshield(walletId, target, credits) + } + } + + override suspend fun topUpIdentityFromShielded( + identityId: ByteArray, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + if (identityId.size != 32) { + return notBroadcast("topUpIdentityFromShielded", "identity id is not 32 bytes", null) + } + val target = identityId.copyOf() + return runShieldedWrite("topUpIdentityFromShielded", amount, expectedWalletIdHex) { walletId, credits -> + source.identityTopUpFromPool(walletId, target, credits) + } + } + + override suspend fun shieldFromCreditsToAddress( + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + val recipientRaw43 = decodeOrchardAddress(toShieldedAddress, displayHrpSafe()) + ?: return notBroadcast("shieldFromCreditsToAddress", "malformed or wrong-network shielded address", null) + return runShieldedWrite("shieldFromCreditsToAddress", amount, expectedWalletIdHex) { walletId, credits -> + source.shieldToRecipient(walletId, recipientRaw43, credits) + } + } + + override suspend fun shieldFromIdentityToAddress( + identityId: ByteArray, + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + if (identityId.size != 32) { + return notBroadcast("shieldFromIdentityToAddress", "identity id is not 32 bytes", null) + } + val recipientRaw43 = decodeOrchardAddress(toShieldedAddress, displayHrpSafe()) + ?: return notBroadcast("shieldFromIdentityToAddress", "malformed or wrong-network shielded address", null) + val fromId = identityId.copyOf() + return runShieldedWrite("shieldFromIdentityToAddress", amount, expectedWalletIdHex) { walletId, credits -> + source.shieldFromIdentityToRecipient(walletId, fromId, recipientRaw43, credits) + } + } + + override suspend fun shieldFromWalletToAddress( + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + val recipientRaw43 = decodeOrchardAddress(toShieldedAddress, displayHrpSafe()) + ?: return notBroadcast("shieldFromWallet", "malformed or wrong-network shielded address", null) + val lockTxId = AtomicReference(null) + return when ( + val result = shieldFromWalletInternal( + amount, + fundingPath = null, + expectedWalletIdHex = expectedWalletIdHex, + externalRecipientRaw43 = recipientRaw43, + onLockTxId = { lockTxId.set(it) } + ) + ) { + is SdkWriteResult.Broadcast -> SdkWriteResult.Broadcast( + ShieldToAddressOutcome( + result.value, + lockTxId.get().takeIf { result.value == ShieldFromWalletOutcome.COMPLETED } + ) + ) + is SdkWriteResult.NotBroadcast -> result + is SdkWriteResult.Ambiguous -> result + } + } + + override suspend fun estimateShieldedFeeCredits(kind: ShieldedFeeKind): Long? { + if (!isEnabled()) return null + return try { + source.estimateSpendFeeCredits(kind).takeIf { it >= 0 } + } catch (t: Throwable) { + if (t is CancellationException) throw t + log.warn("shielded fee estimate failed; the fee is unknown ({})", safeErrorSummary(t)) + null + } + } + + private suspend fun transferShieldedInternal( + toAddress: String, + amount: Dash, + memo: String?, + expectedWalletIdHex: String? ): SdkWriteResult { // Pure preflights first — provably nothing submitted. val recipientRaw43 = decodeOrchardAddress(toAddress, displayHrpSafe()) @@ -2621,7 +2865,7 @@ class ShieldedBalanceServiceImpl internal constructor( if (cleanMemo != null && cleanMemo.toByteArray(Charsets.UTF_8).size > MAX_SHIELDED_MEMO_BYTES) { return notBroadcast("transferShielded", "memo exceeds $MAX_SHIELDED_MEMO_BYTES UTF-8 bytes", null) } - return runShieldedWrite("transferShielded", amount) { walletId, credits -> + return runShieldedWrite("transferShielded", amount, expectedWalletIdHex) { walletId, credits -> source.transfer(walletId, recipientRaw43, credits, cleanMemo) } } @@ -2637,12 +2881,19 @@ class ShieldedBalanceServiceImpl internal constructor( source.unshield(walletId, target, credits) } - override suspend fun withdrawToCore(addressBase58: String, amount: Dash): SdkWriteResult { + override suspend fun withdrawToCore(addressBase58: String, amount: Dash): SdkWriteResult = + withdrawToCoreInternal(addressBase58, amount, expectedWalletIdHex = null) + + private suspend fun withdrawToCoreInternal( + addressBase58: String, + amount: Dash, + expectedWalletIdHex: String? + ): SdkWriteResult { val address = addressBase58.trim() if (address.isEmpty()) { return notBroadcast("withdrawToCore", "empty core address", null) } - return runShieldedWrite("withdrawToCore", amount) { walletId, credits -> + return runShieldedWrite("withdrawToCore", amount, expectedWalletIdHex) { walletId, credits -> source.withdraw(walletId, address, credits, WITHDRAW_CORE_FEE_PER_BYTE) } } @@ -2669,6 +2920,8 @@ class ShieldedBalanceServiceImpl internal constructor( private suspend fun runShieldedWrite( operation: String, amount: Dash, + /** When set, the ready runtime must be bound to this SDK wallet, else NotBroadcast. */ + expectedWalletIdHex: String? = null, block: suspend (walletId: ByteArray, amountCredits: Long) -> Unit ): SdkWriteResult { if (!isEnabled()) return SdkWriteResult.NotBroadcast("flag off") @@ -2685,7 +2938,12 @@ class ShieldedBalanceServiceImpl internal constructor( if (!ensureShieldedReady()) { return notBroadcast(operation, "shielded runtime not ready", null) } - val walletId = readyWalletIdHex.value?.let(::walletIdFromHex) + val walletIdHex = readyWalletIdHex.value + ?: return notBroadcast(operation, "shielded runtime not ready", null) + if (expectedWalletIdHex != null && !walletIdHex.equals(expectedWalletIdHex, ignoreCase = true)) { + return notBroadcast(operation, "the shielded runtime is bound to another wallet", null) + } + val walletId = walletIdFromHex(walletIdHex) ?: return notBroadcast(operation, "shielded runtime not ready", null) // The single broadcast attempt (~30s Halo 2 proof — callers show @@ -2724,13 +2982,13 @@ class ShieldedBalanceServiceImpl internal constructor( val classified = classifyBroadcastFailure(t) when (classified) { is SdkWriteResult.NotBroadcast -> - log.warn("shielded {} rejected pre-broadcast (notes released)", operation, t) + log.warn("shielded {} rejected pre-broadcast (notes released) ({})", operation, safeErrorSummary(t)) is SdkWriteResult.Ambiguous -> { log.error( "shielded {} outcome unconfirmed — it MAY be on chain and the spent " + - "notes stay reserved; do NOT retry (the next shielded sync reconciles)", + "notes stay reserved; do NOT retry (the next shielded sync reconciles) ({})", operation, - t + safeErrorSummary(t) ) // The spend MAY have landed while the reserved notes still // count as unspent: the reconciliation (stale + durable @@ -3016,7 +3274,7 @@ class ShieldedBalanceServiceImpl internal constructor( } private fun notBroadcast(operation: String, reason: String, cause: Throwable?): SdkWriteResult.NotBroadcast { - log.info("shielded {} not attempted ({})", operation, reason, cause) + log.info("shielded {} not attempted ({}; cause: {})", operation, reason, safeErrorSummary(cause)) return SdkWriteResult.NotBroadcast(reason, cause) } diff --git a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt index 27cf966c01..0bc4a17b3e 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt @@ -290,6 +290,36 @@ open class DashPayConfig @Inject constructor( val MIXED_FUNDS_MIGRATION_IN_FLIGHT = stringPreferencesKey("mixed_funds_migration_in_flight") val MIXED_FUNDS_CONSOLIDATION = stringPreferencesKey("mixed_funds_consolidation") + /** + * An Advanced-mode external send MAY be in flight or its outcome was never + * acknowledged: set (one DataStore write) before the send is handed to the SDK, + * cleared on a definitive Sent / Not sent, kept on an unknown outcome until the user + * acknowledges it. Present on a fresh process = show "may have gone through" instead + * of the editable form ([de.schildbach.wallet.ui.payments.send.ExternalSendExecutor]). + * A bare flag: no amount, address or id. + */ + val EXTERNAL_SEND_IN_FLIGHT = booleanPreferencesKey("external_send_in_flight") + + /** + * The one Core → third-party Platform address send whose asset lock is not yet known + * consumed ([de.schildbach.wallet.service.platform.sdk.PendingPlatformFunding]): its + * recipients, its lock amount and, once built, the lock's outpoint. Written before + * the SDK call, the outpoint added from `onAssetLockBuilt`, removed once the lock is + * consumed. The SDK's tracked lock stores no recipients, so this is what a resume + * pays; while it is present no new Core → Platform send starts. Never logged. + */ + val EXTERNAL_PLATFORM_FUNDING_PENDING = stringPreferencesKey("external_platform_funding_pending") + + /** + * Core → Platform fundings whose automatic resume got Platform's (unauthenticated) + * `AssetLockAlreadyConsumed`, each an encoded + * [de.schildbach.wallet.service.platform.sdk.PendingPlatformFunding] marked + * `completionUnconfirmed`, moved here from [EXTERNAL_PLATFORM_FUNDING_PENDING] in one + * transaction. Not resumed automatically and not blocking a new send; kept (never + * inferred complete) for an explicit retry. Never logged. + */ + val EXTERNAL_PLATFORM_FUNDING_UNCONFIRMED = stringSetPreferencesKey("external_platform_funding_unconfirmed") + /** * `startedAtMillis` of the in-flight marker whose "could not confirm" * guidance the user closed. While it matches the current marker the diff --git a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt index 4ed4f400ad..cdb05545af 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/AdvancedPaymentsFragment.kt @@ -51,6 +51,7 @@ import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_IN import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ACTIVE_TAB_RECEIVE import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ARG_ACTIVE_TAB import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ARG_SOURCE +import de.schildbach.wallet.ui.payments.send.AdvancedSendFragment import de.schildbach.wallet_test.R import de.schildbach.wallet_test.databinding.FragmentAdvancedPaymentsBinding import kotlinx.coroutines.flow.distinctUntilChanged @@ -70,8 +71,8 @@ import org.dash.wallet.common.ui.viewBinding * Receive / Internal / Send picker right under the status bar, above the bottom * navigation (`ShowNavBar` on the destination), over the payments pages. * - * Receive is [AdvancedReceiveFragment] (the Compose [ReceivePage]); Internal and Send - * are the same child pages as [PaymentsFragment]'s. The enter/exit transitions are on + * Receive is [AdvancedReceiveFragment] (the Compose [ReceivePage]), Send is + * [AdvancedSendFragment] (MO-1121); Internal is the same child page as [PaymentsFragment]'s. The enter/exit transitions are on * the NavOptions (see [paymentsRoute]). There is no close control: like the other * bottom-nav screens it is left through the bottom navigation or Back. * @@ -265,7 +266,7 @@ class AdvancedPaymentsFragment : Fragment(R.layout.fragment_advanced_payments) { override fun createFragment(position: Int): Fragment = when (tabIds[position]) { ACTIVE_TAB_RECEIVE -> AdvancedReceiveFragment.newInstance() ACTIVE_TAB_INTERNAL -> PaymentsInternalFragment.newInstance() - else -> PaymentsPayFragment.newInstance(source = source) + else -> AdvancedSendFragment.newInstance(source = source) } } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt new file mode 100644 index 0000000000..ffa353f7eb --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt @@ -0,0 +1,236 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import android.app.Activity +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.core.os.bundleOf +import androidx.fragment.app.Fragment +import androidx.fragment.app.viewModels +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.navigation.fragment.findNavController +import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.Constants +import de.schildbach.wallet.ui.dashpay.ContactsScreenMode +import de.schildbach.wallet.ui.more.connections.protocol.DashConnectUri +import de.schildbach.wallet.ui.payments.PaymentsFragment.Companion.ARG_SOURCE +import de.schildbach.wallet.ui.payments.PaymentsFragmentDirections +import de.schildbach.wallet.ui.send.SendCoinsActivity +import de.schildbach.wallet_test.R +import kotlinx.coroutines.launch +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.DashPaymentIntentParser +import org.dash.wallet.common.payments.parsers.PaymentIntentParserException +import org.dash.wallet.common.services.analytics.AnalyticsConstants +import org.dash.wallet.common.ui.components.ActionItem +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.ui.components.LocalDashColors +import org.dash.wallet.common.ui.components.Menu +import org.dash.wallet.common.ui.dialogs.AdaptiveDialog +import org.dash.wallet.common.ui.scan.ScanActivity + +/** + * The Send page of [de.schildbach.wallet.ui.payments.AdvancedPaymentsFragment] (Figma + * 6894:49688): Send to username, Send to Dash address and Scan Dash QR. Basic mode keeps + * [de.schildbach.wallet.ui.payments.PaymentsPayFragment]. + * + * - Send to username: the contact picker, exactly as the Basic Send tab opens it. + * - Send to Dash address: [ExternalSendFragment] on its address page. + * - Scan Dash QR: [AdvancedSendViewModel.scanActionFor] decides. + */ +@AndroidEntryPoint +class AdvancedSendFragment : Fragment() { + + companion object { + fun newInstance(source: String) = AdvancedSendFragment().apply { + arguments = bundleOf(ARG_SOURCE to source) + } + } + + private val viewModel by viewModels() + + private val scanLauncher = registerForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { result -> + val input = result.data?.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT) + if (result.resultCode == Activity.RESULT_OK && input != null) { + handleScan(input) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = + ComposeView(requireContext()).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { + DashWalletTheme { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + AdvancedSendPage( + showSendToUsername = uiState.showSendToUsername, + onSendToUsername = ::sendToUsername, + onSendToAddress = { openExternalSend(prefill = null) }, + onScan = ::scan + ) + } + } + } + + private val source: String + get() = arguments?.getString(ARG_SOURCE) ?: "" + + /** As [de.schildbach.wallet.ui.payments.PaymentsPayFragment]: the contact picker pays on Core. */ + private fun sendToUsername() { + val navController = findNavController() + if (navController.currentDestination?.getAction(R.id.payments_to_contacts) == null) return + viewModel.logEvent(AnalyticsConstants.UsersContacts.TAB_SEND_TO_CONTACT) + navController.navigate( + PaymentsFragmentDirections.paymentsToContacts( + ShowNavBar = false, + mode = ContactsScreenMode.SELECT_CONTACT, + source = source + ) + ) + } + + private fun scan() { + viewModel.logEvent(AnalyticsConstants.SendReceive.SCAN_TO_SEND) + scanLauncher.launch(ScanActivity.getIntent(activity)) + } + + private fun openExternalSend(prefill: String?) { + val navController = findNavController() + // Only from the Advanced payments screen, so a second tap after navigating does nothing. + if (navController.currentDestination?.getAction(R.id.payments_to_externalSend) == null) return + if (prefill == null) { + viewModel.logEvent(AnalyticsConstants.SendReceive.SEND_TO_ADDRESS) + } + navController.navigate( + R.id.payments_to_externalSend, + bundleOf(ExternalSendViewModel.ARG_PREFILL to prefill) + ) + } + + private fun handleScan(input: String) { + val action = AdvancedSendViewModel.scanActionFor( + input, + AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id), + Constants.SUPPORTS_CONNECT, + DashConnectUri::isConnectUri + ) + when (action) { + is AdvancedScanAction.DashConnect -> { + val navController = findNavController() + if (navController.currentDestination?.getAction(R.id.payments_to_connections) != null) { + navController.navigate(PaymentsFragmentDirections.paymentsToConnections(action.input)) + } + } + is AdvancedScanAction.PaymentRequest -> payInvoice(action.input) + is AdvancedScanAction.ExternalSend -> openExternalSend(action.input) + is AdvancedScanAction.Error -> showError( + getString(if (action.wrongNetwork) R.string.external_send_wrong_network else R.string.advanced_send_invalid_qr) + ) + } + } + + /** A BIP70 invoice: the same path as the Basic Send tab. */ + private fun payInvoice(input: String) { + viewLifecycleOwner.lifecycleScope.launch { + try { + val paymentIntent = DashPaymentIntentParser(AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id)) + .parse(input, true) + paymentIntent.source = source + SendCoinsActivity.start(requireContext(), paymentIntent) + } catch (ex: PaymentIntentParserException) { + showError(ex.localizedMessage.format(resources)) + } + } + } + + /** The Basic Send tab's error dialog. */ + private fun showError(message: String) { + val activity = activity ?: return + AdaptiveDialog.create( + R.drawable.ic_error, + getString(R.string.error), + message, + getString(R.string.button_dismiss) + ).show(activity) + } +} + +/** Figma 6894:49841: one menu card, 20dp under the tab picker. */ +@Composable +fun AdvancedSendPage( + showSendToUsername: Boolean, + onSendToUsername: () -> Unit, + onSendToAddress: () -> Unit, + onScan: () -> Unit +) { + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + ) { + Menu { + if (showSendToUsername) { + ActionItem( + title = stringResource(R.string.advanced_send_to_username), + icon = R.drawable.ic_payments_send_to_contact, + onClick = onSendToUsername + ) + } + ActionItem( + title = stringResource(R.string.advanced_send_to_address), + icon = R.drawable.ic_send_to_address, + onClick = onSendToAddress + ) + ActionItem( + title = stringResource(R.string.advanced_send_scan_qr), + icon = R.drawable.ic_payments_send_by_qr, + onClick = onScan + ) + } + } +} + +@Preview(showBackground = true, widthDp = 420, heightDp = 400) +@Composable +private fun AdvancedSendPagePreview() { + DashWalletTheme { + Box(modifier = Modifier.background(LocalDashColors.current.backgroundPrimary)) { + AdvancedSendPage(showSendToUsername = true, onSendToUsername = {}, onSendToAddress = {}, onScan = {}) + } + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt new file mode 100644 index 0000000000..ddd474cd28 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt @@ -0,0 +1,116 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.service.platform.sdk.DestinationParse +import de.schildbach.wallet.service.platform.sdk.ExternalSendService +import de.schildbach.wallet.service.platform.sdk.detectSendDestination +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.update +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.DashPaymentIntentParser +import org.dash.wallet.common.util.Constants +import org.dash.wallet.common.services.analytics.AnalyticsService +import javax.inject.Inject + +/** @property showSendToUsername the user has an identity, so they can pick a contact. */ +data class AdvancedSendUIState(val showSendToUsername: Boolean = false) + +/** What a scanned QR code leads to on the Advanced Send tab. */ +sealed class AdvancedScanAction { + /** A DashConnect `dash-key:` / `dash-st:` code, for the Connections screen. */ + data class DashConnect(val input: String) : AdvancedScanAction() + + /** + * A payment request the Basic Send tab handles and that is not a plain destination — a + * BIP70 `dash:?r=` link, an AnyPay `pay:?r=` link, a serialized `DASH:-` request, or any + * other `dash:` URI the external flow cannot use: [DashPaymentIntentParser] → + * `SendCoinsActivity`, exactly as the Basic Send tab. + */ + data class PaymentRequest(val input: String) : AdvancedScanAction() + + /** A destination of this network: the external send flow, pre-filled with [input]. */ + data class ExternalSend(val input: String) : AdvancedScanAction() + + /** Not usable; [wrongNetwork] = an address of another Dash network. */ + data class Error(val wrongNetwork: Boolean) : AdvancedScanAction() +} + +/** The Send tab of the Advanced payments screen (Figma 6894:49688). */ +@HiltViewModel +class AdvancedSendViewModel @Inject constructor( + service: ExternalSendService, + private val analytics: AnalyticsService +) : ViewModel() { + + companion object { + /** + * Route a scanned [input], in order: a DashConnect code ([isDashConnect], only when + * [supportsConnect]); a plain destination of this network, including a `dash:` URI + * without `r=` ([detectSendDestination] Valid) → the external flow; a wrong-network + * one → that error; anything else the Basic Send tab's [DashPaymentIntentParser] owns + * (`dash:`/`DASH:-` URIs and AnyPay `pay:` links that are not a plain destination, e.g. + * BIP70 `r=` invoices) → the Basic path; everything else → invalid QR. + */ + fun scanActionFor( + input: String, + network: AddressNetwork, + supportsConnect: Boolean, + isDashConnect: (String) -> Boolean + ): AdvancedScanAction { + if (supportsConnect && isDashConnect(input)) return AdvancedScanAction.DashConnect(input) + val parse = detectSendDestination(input, network) + return when { + parse is DestinationParse.Valid -> AdvancedScanAction.ExternalSend(input) + // Never carries `r=` (an invoice link is Invalid there), so no invoice is lost. + parse is DestinationParse.WrongNetwork -> AdvancedScanAction.Error(wrongNetwork = true) + isBasicPaymentRequest(input) -> AdvancedScanAction.PaymentRequest(input) + else -> AdvancedScanAction.Error(wrongNetwork = false) + } + } + + /** + * The schemes [DashPaymentIntentParser.parse] (`supportAnypayUrls = true`) handles + * besides a bare address: `pay:` (AnyPay), `DASH:-` (serialized BIP70 request) and + * `dash:` URIs. It decides itself (and reports its own error) for these. + */ + private fun isBasicPaymentRequest(input: String): Boolean = + input.startsWith("${Constants.ANYPAY_SCHEME}:") || + input.startsWith("${Constants.DASH_SCHEME}:", ignoreCase = true) + } + + private val _uiState = MutableStateFlow(AdvancedSendUIState()) + val uiState: StateFlow = _uiState.asStateFlow() + + init { + service.observeHasIdentity() + .onEach { has -> _uiState.update { it.copy(showSendToUsername = has == true) } } + .launchIn(viewModelScope) + } + + fun logEvent(event: String) { + analytics.logEvent(event, mapOf()) + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt new file mode 100644 index 0000000000..7d35611112 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -0,0 +1,362 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import de.schildbach.wallet.data.WalletData +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.ExternalSendService +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.SendDestination +import de.schildbach.wallet.service.platform.sdk.safeErrorSummary +import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.dash.wallet.common.money.Dash +import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Exactly what the user confirmed on the confirm sheet: captured BEFORE authentication and + * passed to [ExternalSendService.send] unchanged. [expectedWalletIdHex] is the SDK wallet bound + * when the confirm sheet opened ([ExternalSendService.currentWalletIdOrNull]); the send is + * refused unless it is still the bound one. [toString] is redacted. + */ +data class ExternalSendRequest( + val source: SendBalance, + val destination: SendDestination, + val amount: Dash, + val isMax: Boolean, + val expectedWalletIdHex: String? +) { + override fun toString(): String = "ExternalSendRequest($source → $destination, , isMax=$isMax)" +} + +/** The one external send the app runs at a time, as [ExternalSendExecutor] reports it. */ +sealed class ExternalSendExecution { + /** The in-flight marker of a previous process is still being read; nothing can be sent yet. */ + object Restoring : ExternalSendExecution() + + object Idle : ExternalSendExecution() + + data class Sending(val request: ExternalSendRequest) : ExternalSendExecution() + + /** Terminal until the screen [ExternalSendExecutor.acknowledge]s it. */ + data class Finished(val request: ExternalSendRequest, val result: ExternalSendResult) : ExternalSendExecution() + + /** + * A previous process died with an external send possibly submitted (or its unknown outcome + * unacknowledged), or the marker could not be read: "may have gone through — check your + * history". Terminal until acknowledged. + */ + object InterruptedByRestart : ExternalSendExecution() + + /** + * An outcome was acknowledged and its marker is being cleared: claimed atomically so a + * second acknowledgement does nothing, and not Idle so nothing new can be submitted (and + * have its own marker wiped) before the clear finishes. Becomes Idle after the clear. + */ + object Acknowledging : ExternalSendExecution() +} + +/** + * The persisted "an external send may be in flight" flag ([DashPayConfig.EXTERNAL_SEND_IN_FLIGHT]). + * Every call throws when the store cannot be read or written. + */ +internal interface ExternalSendInFlightMarker { + suspend fun isSet(): Boolean + suspend fun set() + suspend fun clear() +} + +/** [ExternalSendInFlightMarker] over [DashPayConfig] (error-preserving reads). */ +internal class DashPayConfigInFlightMarker(private val config: DashPayConfig) : ExternalSendInFlightMarker { + override suspend fun isSet(): Boolean = config.getPreservingErrors(DashPayConfig.EXTERNAL_SEND_IN_FLIGHT) == true + override suspend fun set() = config.set(DashPayConfig.EXTERNAL_SEND_IN_FLIGHT, true) + override suspend fun clear() = config.set(DashPayConfig.EXTERNAL_SEND_IN_FLIGHT, false) +} + +/** + * App-lifetime owner of the Advanced-mode external send (MO-1121). A shielded leg blocks for a + * ~30 s proof, so the send runs on the application scope: leaving the screen, rotating or + * backgrounding the app never cancels it. [state] is the single source of truth; the + * [ExternalSendViewModel] of any later visit mirrors it, so a user who left during the send + * sees the outcome when they open the external send again. + * + * Process death: before the request is handed to the service the in-flight marker is written + * (a failed write sends nothing). It is cleared right away only on Not sent (nothing spent); + * on Sent and on an unknown outcome only when the user acknowledges it, so a process that dies + * before the user saw a Sent still warns on the next launch instead of offering the form again. + * A fresh process that finds it set (or cannot read it) starts in + * [ExternalSendExecution.InterruptedByRestart]. + * + * Reset Wallet: this singleton outlives the wallet, so a wipe listener ([forgetWalletState]) + * returns it to Idle and moves it to a new wallet generation. A send of the wiped wallet that + * completes afterwards publishes nothing and touches no marker: the next wallet never shows, + * or opens the transaction of, the old one's outcome. + * + * Deliberately simpler than the shielded [de.schildbach.wallet.ui.shielded.ShieldedTransferExecutor]: + * no system notification and no stall watchdog. The service is itself single-flight. + */ +@Singleton +class ExternalSendExecutor internal constructor( + private val service: ExternalSendService, + private val marker: ExternalSendInFlightMarker, + private val applicationScope: CoroutineScope +) { + @Inject + constructor( + service: ExternalSendService, + dashPayConfig: DashPayConfig, + walletData: WalletData, + applicationScope: CoroutineScope + ) : this(service, DashPayConfigInFlightMarker(dashPayConfig), applicationScope) { + walletData.attachOnWalletWipedListener { forgetWalletState() } + } + + companion object { + private val log = LoggerFactory.getLogger(ExternalSendExecutor::class.java) + } + + private val _state = MutableStateFlow(ExternalSendExecution.Restoring) + val state: StateFlow = _state.asStateFlow() + + /** + * The wallet generation: bumped by every wipe ([forgetWalletState]). A send captures it when + * submitted and, once the wallet it was for is gone, neither publishes its outcome nor + * touches the in-flight marker (which may by then be the next wallet's). + */ + private val generation = AtomicLong(0) + + /** The running [resumePendingPlatformFunding] sweep (declared before `init`, which starts one). */ + private val platformFundingSweep = AtomicReference(null) + + init { + applicationScope.launch { + val interrupted = try { + marker.isSet() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send in-flight marker unreadable; assuming a send may have gone through ({})", safeErrorSummary(e)) + true + } + if (interrupted) log.warn("external send: a previous process may have left a send in flight") + _state.update { + if (it is ExternalSendExecution.Restoring) { + if (interrupted) ExternalSendExecution.InterruptedByRestart else ExternalSendExecution.Idle + } else { + it + } + } + } + resumePendingPlatformFunding() + } + + /** + * Finish an interrupted Core → Platform send in the background + * ([ExternalSendService.resumePendingPlatformFunding]): run when the executor starts, on + * every SDK engine kick after its bind pass (app start and each blockchain-service start, + * `PlatformSynchronizationService.kickSdkEngines`), and each time the external send + * screen opens. One sweep at a time; cheap (one store read) + * when nothing is pending. It shares the service's single-flight with sends: it skips + * while a send runs, and a send submitted while it resumes a lock is refused as in + * progress (Not sent, nothing spent). + */ + fun resumePendingPlatformFunding() { + val running = platformFundingSweep.get() + if (running?.isActive == true) return + val job = applicationScope.launch(start = CoroutineStart.LAZY) { + val completed = try { + service.resumePendingPlatformFunding() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: pending Core → Platform sweep failed ({})", safeErrorSummary(e)) + 0 + } + if (completed > 0) log.info("external send: an interrupted Core → Platform send was completed") + } + if (platformFundingSweep.compareAndSet(running, job)) job.start() else job.cancel() + } + + /** + * Start sending [request]. Refused (false) while another send is running, an earlier + * outcome has not been acknowledged, or the previous process's marker is not yet read: one + * attempt per confirmation, and a terminal result is never silently replaced. + */ + fun submit(request: ExternalSendRequest): Boolean { + // Read BEFORE the state claim: a wipe that resets the state from here on is seen by + // [isCurrent], so this send can never publish into the next wallet's state. + val submittedIn = generation.get() + + fun isCurrent() = generation.get() == submittedIn + var accepted = false + _state.update { current -> + if (current is ExternalSendExecution.Idle) { + accepted = true + ExternalSendExecution.Sending(request) + } else { + accepted = false + current + } + } + if (!accepted) { + log.warn("external send refused: a previous send is still running or unacknowledged") + return false + } + applicationScope.launch { + var result: ExternalSendResult = ExternalSendResult.MayHaveGoneThrough + var marked = false + try { + if (!isCurrent()) { + // The wallet was wiped before anything was handed to the service. + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + return@launch + } + try { + marker.set() + marked = true + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Nothing handed to the service: provably nothing spent. + log.warn("external send: could not record the in-flight marker; not sent ({})", safeErrorSummary(e)) + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + if (marked && !isCurrent()) { + // A wipe ran while the marker was written: nothing is sent. The marker is + // left alone, as in the finally path: by now it may be the replacement + // wallet's own send's, and clearing it would drop that send's restart + // protection. Worst case one spurious "interrupted" warning, the safe side. + marked = false + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + } + if (marked) { + result = service.send( + request.source, + request.destination, + request.amount, + request.isMax, + request.expectedWalletIdHex + ) + } + } catch (e: CancellationException) { + // The application scope is never cancelled in practice; if it is, the outcome + // is unknown and stays "may have gone through". + throw e + } catch (e: Exception) { + log.error("external send threw; outcome unknown ({})", safeErrorSummary(e)) + } finally { + log.info("external send {} → {} finished: {}", request.source, kindOf(request.destination), kindOf(result)) + if (!isCurrent()) { + // The wallet it was for was wiped: its outcome is not the next wallet's to + // see, and the marker (cleared by the wipe) may already be the next one's. + log.warn("external send: finished after a wallet wipe; outcome dropped") + } else { + // Only Not sent (nothing spent) clears here; Sent keeps the restart + // protection until acknowledged. Cleared BEFORE the outcome is published: a + // later submit (only after this one is acknowledged) can never have its own + // marker cleared by this one. + if (marked && result is ExternalSendResult.NotSent) { + withContext(NonCancellable) { clearMarker() } + } + // Checked again in the update (after the clear's suspension): a wipe that + // bumped the generation, or already reset the state, wins. + val outcome = result + _state.update { if (isCurrent()) ExternalSendExecution.Finished(request, outcome) else it } + } + } + } + return true + } + + /** + * The screen showed the outcome; the executor is free again. A Not sent outcome (marker + * already cleared) becomes Idle at once. Any other outcome is first CLAIMED — atomically + * moved to [ExternalSendExecution.Acknowledging] — so only one acknowledgement clears the + * marker; it becomes Idle only after the clear, so the clear can never race a new send's + * marker. A losing (duplicate) acknowledgement does nothing. + */ + fun acknowledge() { + val current = _state.value + val needsClear = when (current) { + is ExternalSendExecution.Finished -> current.result !is ExternalSendResult.NotSent + ExternalSendExecution.InterruptedByRestart -> true + else -> return + } + if (!needsClear) { + _state.compareAndSet(current, ExternalSendExecution.Idle) + return + } + val acknowledgedIn = generation.get() + if (!_state.compareAndSet(current, ExternalSendExecution.Acknowledging)) return + applicationScope.launch { + // After a wipe the marker is the wipe's (cleared) or the next wallet's: left alone. + if (generation.get() == acknowledgedIn) clearMarker() + _state.compareAndSet(ExternalSendExecution.Acknowledging, ExternalSendExecution.Idle) + } + } + + /** + * Reset Wallet (a wallet-wipe listener, run after the wipe drained every payment hold and + * cleared the configs): forgets every outcome of the wiped wallet. Bumps [generation] first, + * so a send of that wallet still finishing publishes nothing, then clears the in-flight + * marker (again: [DashPayConfig] is cleared by the wipe too, but a send may have written it + * after that) and returns to Idle. + */ + internal suspend fun forgetWalletState() { + generation.incrementAndGet() + // Cleared before Idle, so no send of the next wallet can have set it yet. + clearMarker() + _state.value = ExternalSendExecution.Idle + log.info("external send: state reset for a wallet wipe") + } + + private suspend fun clearMarker() { + try { + marker.clear() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // Left set: the next process warns once more (conservative). + log.warn("external send: could not clear the in-flight marker ({})", safeErrorSummary(e)) + } + } + + private fun kindOf(destination: SendDestination): String = destination::class.java.simpleName + + private fun kindOf(result: ExternalSendResult): String = when (result) { + is ExternalSendResult.Sent -> "Sent" + is ExternalSendResult.NotSent -> "NotSent(${result.reason})" + ExternalSendResult.MayHaveGoneThrough -> "MayHaveGoneThrough" + ExternalSendResult.InterruptedFundsReturnToShielded -> "InterruptedFundsReturnToShielded" + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt new file mode 100644 index 0000000000..4ee8055b4b --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt @@ -0,0 +1,230 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import android.app.Activity +import android.content.ClipboardManager +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.compose.BackHandler +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.fragment.app.Fragment +import androidx.fragment.app.viewModels +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.navigation.fragment.findNavController +import dagger.hilt.android.AndroidEntryPoint +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.ui.transactions.TransactionResultActivity +import de.schildbach.wallet_test.R +import kotlinx.coroutines.launch +import org.bitcoinj.core.Sha256Hash +import org.dash.wallet.common.services.AuthenticationManager +import org.dash.wallet.common.services.LockScreenBroadcaster +import org.dash.wallet.common.ui.LockScreenHost +import org.dash.wallet.common.ui.handleWhenResumed +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.ui.scan.ScanActivity +import javax.inject.Inject + +/** + * The Advanced-mode external send flow (MO-1121), a `nav_home` destination without the bottom + * navigation. Its argument [ExternalSendViewModel.ARG_PREFILL] is an already-validated scanned + * destination; without it the flow starts on the empty address page. + * + * Confirm captures the exact request, then asks for PIN/biometric, then hands it to the + * app-scoped [ExternalSendExecutor]: leaving the screen does not cancel the send. + */ +@AndroidEntryPoint +class ExternalSendFragment : Fragment() { + + private val viewModel by viewModels() + + @Inject + lateinit var authManager: AuthenticationManager + + @Inject + lateinit var lockScreenBroadcaster: LockScreenBroadcaster + + private val scanLauncher = registerForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { result -> + val input = result.data?.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT) + if (result.resultCode == Activity.RESULT_OK && input != null) { + viewModel.onAddressChanged(input) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = + ComposeView(requireContext()).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { + DashWalletTheme { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + BackHandler { onBack() } + // Built once: a new instance per uiState emission (every key press) would + // make every child taking it recompose. + val actions = remember { + ExternalSendActions( + onBack = ::onBack, + onAddressChanged = viewModel::onAddressChanged, + onScanClick = ::scan, + onShowClipboard = ::showClipboard, + onClipboardEntrySelected = viewModel::onClipboardEntrySelected, + onAddressContinue = viewModel::onAddressContinue, + onKeyInput = viewModel::onKeyInput, + onCurrencySelected = viewModel::onCurrencySelected, + onMaxClick = viewModel::onMaxClick, + onShowSourceSheet = viewModel::onShowSourceSheet, + onDismissSourceSheet = viewModel::onDismissSourceSheet, + onSourceSelected = viewModel::onSourceSelected, + onRetryIdentity = viewModel::onRetryIdentity, + onAmountContinue = viewModel::onAmountContinue, + onDismissConfirm = viewModel::onDismissConfirm, + onConfirm = ::authenticateAndSend, + onLeave = ::leave, + onResultClosed = ::onResultClosed + ) + } + ExternalSendScreen(uiState = uiState, actions = actions) + } + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + // A sent outcome with its txid opens the transaction result screen, once, and only while + // this screen is resumed and the wallet unlocked (nothing over the PIN screen). The + // executor keeps the outcome until it is acknowledged, so a screen recreated or returned + // to meanwhile opens it then. Opening acknowledges it in the same turn. + handleWhenResumed( + viewModel.openTransactionResult, + lockScreenBroadcaster.unlocked, + viewModel::takeTransactionResult, + putBack = {} + ) { txId -> + showTransactionResult(txId) + true + } + } + + /** + * Back is ignored while the lock screen covers this screen: the activity's own callback, + * which ignores it too, runs only after this one. While the outcome shows, Back acknowledges + * it, as the dialog it replaced did on dismiss-on-back. + */ + private fun onBack() { + if ((activity as? LockScreenHost)?.lockScreenDisplayed == true) return + val state = viewModel.uiState.value + val txId = state.openTransactionResult + if (txId != null) { + showTransactionResult(txId) + return + } + val status = state.status + if (status is ExternalSendStatus.Done) { + onResultClosed(status.result) + return + } + if (!viewModel.onBack()) leave() + } + + private fun leave() { + val navController = findNavController() + // A second tap while the pop runs would pop the payments screen too. + if (navController.currentDestination?.id == R.id.externalSendFragment) { + navController.popBackStack() + } + } + + private fun scan() { + scanLauncher.launch(ScanActivity.getIntent(activity)) + } + + /** The clipboard is read only here, on the user's tap; its text is never logged. */ + private fun showClipboard() { + val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager + val clip = clipboard?.primaryClip + val text = if (clip != null && clip.itemCount > 0) { + clip.getItemAt(0).coerceToText(requireContext())?.toString() + } else { + null + } + viewModel.onClipboardRead(text) + } + + /** + * Capture what the confirm sheet shows BEFORE authenticating (the + * `captureAuthenticateAndSubmit` contract of the shielded flows), then send exactly that. + * A failed or cancelled authentication sends nothing. + */ + private fun authenticateAndSend() { + val request = viewModel.confirmedRequest() ?: return + viewLifecycleOwner.lifecycleScope.launch { + val activity = activity ?: return@launch + if (authManager.authenticate(activity) == null) return@launch + viewModel.submit(request) + } + } + + /** + * A terminal outcome (sent, or may have gone through — including the one shown after a + * process restart) returns Home, the way a completed send does elsewhere. NotSent stays + * on this screen so the user can try again. + */ + private fun onResultClosed(result: ExternalSendResult) { + viewModel.onResultAcknowledged() + if (result !is ExternalSendResult.NotSent) { + leaveToHome() + } + } + + /** + * Opens the transaction result screen for [txId] (as [de.schildbach.wallet.ui.send.SendCoinsFragment] + * does after a send), acknowledges the outcome and returns Home. Called on the main thread + * with [txId] the current [ExternalSendUIState.openTransactionResult]; acknowledging clears + * it before anything else can run, so it is opened once. + */ + private fun showTransactionResult(txId: String) { + if (!isAdded) return + startActivity(TransactionResultActivity.createIntent(requireActivity(), Sha256Hash.wrap(txId), false)) + viewModel.onResultAcknowledged() + leaveToHome() + } + + /** + * Pops back to Home (the bottom navigation follows the destination change). Falls back + * to [leave] when Home is not on the back stack so the user is never stranded here. + */ + private fun leaveToHome() { + val navController = findNavController() + // A second tap while the pop runs would act on the screen below. + if (navController.currentDestination?.id == R.id.externalSendFragment) { + if (!navController.popBackStack(R.id.walletFragment, false)) { + navController.popBackStack() + } + } + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt new file mode 100644 index 0000000000..b115daa416 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -0,0 +1,1038 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.IdentityResolution +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.SendDestination +import de.schildbach.wallet.service.platform.sdk.SendSupport +import de.schildbach.wallet.service.platform.sdk.balanceKindOf +import de.schildbach.wallet.ui.shielded.toDisplay +import de.schildbach.wallet.ui.shielded.toDisplayString +import de.schildbach.wallet.ui.shielded.toFiatAt +import de.schildbach.wallet_test.R +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.money.Fiat +import org.dash.wallet.common.ui.components.ActionItem +import org.dash.wallet.common.ui.components.AddressField +import org.dash.wallet.common.ui.components.DASH_CURRENCY_CODE +import org.dash.wallet.common.ui.components.DashButton +import org.dash.wallet.common.ui.components.DashWalletTheme +import org.dash.wallet.common.ui.components.EnterAmount +import org.dash.wallet.common.ui.components.Grabber +import org.dash.wallet.common.ui.components.ListItem1 +import org.dash.wallet.common.ui.components.ListItem +import org.dash.wallet.common.ui.components.LocalDashColors +import org.dash.wallet.common.ui.components.Menu +import org.dash.wallet.common.ui.components.MyImages +import org.dash.wallet.common.ui.components.MyTheme +import org.dash.wallet.common.ui.components.Size +import org.dash.wallet.common.ui.components.Style +import org.dash.wallet.common.ui.components.SystemMessage +import org.dash.wallet.common.ui.components.TopIntro +import org.dash.wallet.common.ui.components.TopNavBase +import org.dash.wallet.common.ui.enter_amount.AmountEntryPage +import org.dash.wallet.common.ui.enter_amount.AmountEntryPrimaryButton +import org.dash.wallet.common.ui.enter_amount.decimalSeparatorFor +import org.dash.wallet.common.ui.enter_amount.localizeAmountForDisplay +import java.util.Locale + +/** The callbacks of [ExternalSendScreen], one per user action. */ +class ExternalSendActions( + val onBack: () -> Unit, + val onAddressChanged: (String) -> Unit, + val onScanClick: () -> Unit, + val onShowClipboard: () -> Unit, + val onClipboardEntrySelected: (String) -> Unit, + val onAddressContinue: () -> Unit, + val onKeyInput: (String) -> Unit, + val onCurrencySelected: (dashMode: Boolean) -> Unit, + val onMaxClick: () -> Unit, + val onShowSourceSheet: () -> Unit, + val onDismissSourceSheet: () -> Unit, + val onSourceSelected: (SendBalance) -> Unit, + val onRetryIdentity: () -> Unit, + val onAmountContinue: () -> Unit, + val onDismissConfirm: () -> Unit, + val onConfirm: () -> Unit, + val onLeave: () -> Unit, + val onResultClosed: (ExternalSendResult) -> Unit +) + +/** + * The external send flow (MO-1121, Figma 6860:47472): the address page (7057:48055 / + * 7062:48931 / 7062:48871), the amount page (7058:48231), the source sheet (7076:47424) and the + * confirm sheet (7076:47968 / 7107:48421). Progress and outcome have no frames; they follow the + * shielded flows (a dimmed progress card) and [org.dash.wallet.common.ui.components.ModalDialog]. + */ +@Composable +fun ExternalSendScreen(uiState: ExternalSendUIState, actions: ExternalSendActions) { + val colors = LocalDashColors.current + Box( + modifier = Modifier + .fillMaxSize() + .background(colors.backgroundPrimary) + ) { + when (uiState.step) { + ExternalSendStep.ADDRESS -> AddressPage(uiState, actions) + ExternalSendStep.AMOUNT -> AmountPage(uiState, actions) + } + + if (uiState.showSourceSheet && uiState.step == ExternalSendStep.AMOUNT) { + SourceSheet(uiState, actions) + } + + val confirm = uiState.confirm + if (confirm != null && uiState.status == ExternalSendStatus.Idle) { + ConfirmSheet(uiState, confirm, actions) + } + + when (val status = uiState.status) { + is ExternalSendStatus.Sending -> SendingOverlay(status.shieldedLeg, actions.onLeave) + // A sent outcome with its txid opens the transaction result screen instead (the fragment). + is ExternalSendStatus.Done -> if (uiState.openTransactionResult == null) { + ResultOverlay(status.result, status.afterRestart) { actions.onResultClosed(status.result) } + } + ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} + } + } +} + +// ── Address page ──────────────────────────────────────────────────────────── + +@Composable +private fun AddressPage(uiState: ExternalSendUIState, actions: ExternalSendActions) { + val colors = LocalDashColors.current + Column(modifier = Modifier.fillMaxSize()) { + TopNavBase( + leadingIcon = MyImages.MenuChevron, + leadingContentDescription = stringResource(R.string.external_send_back), + onLeadingClick = actions.onBack, + trailingPart = false, + title = stringResource(R.string.external_send_address_title) + ) + Column( + modifier = Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(start = 20.dp, end = 20.dp, top = 10.dp) + ) { + // Figma "menu" (7057:48065): 6dp card padding + 14dp content inset. + Column( + modifier = Modifier + .fillMaxWidth() + .background(colors.backgroundSecondary, RoundedCornerShape(20.dp)) + .padding(20.dp) + ) { + val errorRes = when (uiState.addressParse) { + de.schildbach.wallet.service.platform.sdk.DestinationParse.WrongNetwork -> + R.string.external_send_wrong_network + de.schildbach.wallet.service.platform.sdk.DestinationParse.Invalid -> + R.string.external_send_invalid_address + else -> null + } + AddressField( + value = uiState.addressInput, + onValueChange = actions.onAddressChanged, + label = stringResource(R.string.external_send_address_label), + placeholder = stringResource(R.string.external_send_address_placeholder), + message = errorRes?.let { stringResource(it) }, + isError = errorRes != null, + onScanClick = actions.onScanClick + ) + + if (uiState.addressInput.isEmpty() && !uiState.clipboardShown) { + Spacer(modifier = Modifier.height(20.dp)) + DashButton( + modifier = Modifier.align(Alignment.CenterHorizontally), + text = stringResource(R.string.external_send_show_clipboard), + style = Style.TintedBlue, + size = Size.Medium, + stretch = false, + onClick = actions.onShowClipboard + ) + } + + if (uiState.clipboardShown) { + Spacer(modifier = Modifier.height(20.dp)) + ClipboardEntries(uiState.clipboardEntries, actions.onClipboardEntrySelected) + } + } + } + // Figma BottomBar (7057:48221): a 300dp button, 20dp above and below. + DashButton( + modifier = Modifier + .fillMaxWidth() + .padding(start = 60.dp, end = 60.dp, top = 20.dp, bottom = 20.dp), + text = stringResource(R.string.button_continue), + style = Style.FilledBlue, + size = Size.Large, + isEnabled = uiState.canContinueAddress, + onClick = actions.onAddressContinue + ) + } +} + +/** Figma 7062:48946: a hint, then each clipboard address as a tappable blue line. */ +@Composable +private fun ClipboardEntries(entries: List, onSelected: (String) -> Unit) { + val colors = LocalDashColors.current + Column(modifier = Modifier.fillMaxWidth()) { + Text( + text = stringResource( + if (entries.isEmpty()) R.string.external_send_clipboard_empty else R.string.external_send_clipboard_hint + ), + style = MyTheme.Typography.BodySmall, + color = colors.textPrimary + ) + if (entries.isNotEmpty()) { + Spacer(modifier = Modifier.height(4.dp)) + } + entries.forEach { entry -> + val description = stringResource(R.string.external_send_clipboard_entry_description, entry) + Text( + text = entry, + style = MyTheme.Typography.BodyMedium, + color = colors.dashBlue, + modifier = Modifier + .fillMaxWidth() + .clickable(role = Role.Button) { onSelected(entry) } + .semantics { contentDescription = description } + ) + } + } +} + +// ── Amount page ───────────────────────────────────────────────────────────── + +/** The amount bar's currencies: Dash, then the fiat currency when there is one. */ +private fun currencyCodesFor(fiatCode: String?): List = + if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE) + +@Composable +private fun AmountPage(uiState: ExternalSendUIState, actions: ExternalSendActions) { + val fiatCode = uiState.fiatCode + val codes = remember(fiatCode) { currencyCodesFor(fiatCode) } + Column(modifier = Modifier.fillMaxSize()) { + TopNavBase( + leadingIcon = MyImages.MenuChevron, + leadingContentDescription = stringResource(R.string.external_send_back), + onLeadingClick = actions.onBack, + trailingPart = false, + centralPart = false + ) + TopIntro(heading = stringResource(R.string.external_send_title)) + AmountEntryPage( + amount = uiState.amountText, + currencyCodes = codes, + selectedCurrencyIndex = if (uiState.dashMode || fiatCode == null) 0 else 1, + onKeyInput = actions.onKeyInput, + modifier = Modifier + .fillMaxWidth() + .weight(1f), + secondaryAmount = uiState.secondaryAmountText, + showPrimaryChevron = false, + keypadEnabled = uiState.formEditable, + onCurrencySelected = if (fiatCode != null && uiState.rate != null) { + { index -> actions.onCurrencySelected(index == 0) } + } else { + null + }, + // Max is offered only when the service knows the max sendable. + onMaxClick = if (uiState.maxSendable != null) actions.onMaxClick else null, + belowAmount = { + Spacer(modifier = Modifier.height(20.dp)) + FromToCards(uiState, actions) + IdentityStatus(uiState, actions.onRetryIdentity) + }, + primaryButton = { + AmountEntryPrimaryButton( + text = stringResource(R.string.button_continue), + enabled = uiState.canContinueAmount, + onClick = actions.onAmountContinue + ) + } + ) + } +} + +/** Figma 7059:48453: the From card over the To card, a small down-arrow badge between them. */ +@Composable +private fun FromToCards(uiState: ExternalSendUIState, actions: ExternalSendActions) { + val colors = LocalDashColors.current + val destination = uiState.destination ?: return + Box(modifier = Modifier.fillMaxWidth()) { + Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { + SendCard { + val balance = uiState.balance + val changeDescription = stringResource(R.string.external_send_change_source) + DirectionRow( + icon = iconFor(uiState.source), + label = stringResource(R.string.external_send_from), + title = stringResource(titleFor(uiState.source)), + modifier = Modifier + .clickable( + enabled = !uiState.finished, + role = Role.Button, + onClick = actions.onShowSourceSheet + ) + .semantics { contentDescription = changeDescription }, + trailing = { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(horizontalAlignment = Alignment.End) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text( + text = balance?.toDisplayString() + ?: stringResource(R.string.external_send_value_unknown), + style = MyTheme.Typography.SubheadMedium, + color = colors.textPrimary + ) + if (balance != null) { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_dash_d_black), + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(12.dp) + ) + } + } + balance?.toFiatAt(uiState.rate)?.let { fiat -> + Text( + text = fiat.toDisplay(), + style = MyTheme.Typography.BodySmall, + color = colors.textSecondary + ) + } + } + Spacer(modifier = Modifier.size(10.dp)) + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_menu_row_arrow), + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(14.dp) + ) + } + } + ) + } + SendCard { + DirectionRow( + icon = iconFor(destination), + label = stringResource(R.string.external_send_to), + title = stringResource(titleFor(destination)), + trailing = { + Text( + text = ExternalSendViewModel.shorten(destination.display), + style = MyTheme.Typography.BodyMedium, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + ) + } + } + // Figma btn-s (7059:48473): 30dp, centred on the 5dp gap between the cards. + Box( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = 58.dp) + .size(30.dp) + .clip(RoundedCornerShape(10.dp)) + .background(colors.backgroundSecondary) + .border(2.dp, colors.backgroundPrimary, RoundedCornerShape(10.dp)), + contentAlignment = Alignment.Center + ) { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_arrow_downward_blue_24dp), + contentDescription = null, + tint = colors.dashBlue, + modifier = Modifier.size(14.dp) + ) + } + } +} + +/** A Figma "menu" card: secondary background, 20dp corners, 6dp padding. */ +@Composable +private fun SendCard(content: @Composable ColumnScope.() -> Unit) { + Column( + modifier = Modifier + .fillMaxWidth() + .background(LocalDashColors.current.backgroundSecondary, RoundedCornerShape(20.dp)) + .padding(6.dp), + content = content + ) +} + +/** Figma "Action item / Var 6" and "list-direction": icon, label over title, trailing content. */ +@Composable +private fun DirectionRow( + @DrawableRes icon: Int, + label: String, + title: String, + modifier: Modifier = Modifier, + trailing: @Composable () -> Unit +) { + val colors = LocalDashColors.current + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .then(modifier) + .padding(horizontal = 10.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Image( + painter = painterResource(icon), + contentDescription = null, + modifier = Modifier.size(30.dp) + ) + Column( + modifier = Modifier + .weight(1f) + .padding(start = 6.dp), + verticalArrangement = Arrangement.spacedBy(1.dp) + ) { + Text(text = label, style = MyTheme.Typography.Footnote, color = colors.textSecondary) + Text(text = title, style = MyTheme.Typography.SubheadMedium, color = colors.textPrimary) + } + trailing() + } +} + +/** The identity check (AC8) under the cards: checking, not found, or a retry. */ +@Composable +private fun IdentityStatus(uiState: ExternalSendUIState, onRetry: () -> Unit) { + if (uiState.destination !is SendDestination.Identity) return + val colors = LocalDashColors.current + when (uiState.identityResolution) { + null -> StatusText(stringResource(R.string.external_send_identity_checking), colors.textSecondary) + IdentityResolution.NotFound -> StatusText(stringResource(R.string.external_send_identity_not_found), colors.red) + IdentityResolution.Unknown -> Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally + ) { + StatusText(stringResource(R.string.external_send_identity_unknown), colors.red) + DashButton( + text = stringResource(R.string.button_retry), + style = Style.TintedBlue, + size = Size.Small, + stretch = false, + onClick = onRetry + ) + } + is IdentityResolution.Found -> {} + } +} + +@Composable +private fun StatusText(text: String, color: Color) { + Text( + text = text, + style = MyTheme.Typography.BodySmall, + color = color, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(top = 10.dp, bottom = 6.dp) + ) +} + +// ── Sheets ────────────────────────────────────────────────────────────────── + +/** + * Dimmed backdrop and a bottom sheet with a grabber, as in the shielded flows. + * + * The sheet keeps clear of the system bars like the app's other Compose sheets + * ([org.dash.wallet.common.ui.dialogs.ComposeBottomSheet]): its background runs under the + * navigation bar (Figma's home indicator), its content stops above it. Under MainActivity's + * fitsSystemWindows root these insets arrive already consumed (zero), so nothing is doubled; + * the padding only matters if the screen is ever hosted edge-to-edge (targetSdk 35+). + */ +@Composable +private fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .statusBarsPadding() + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { + onDismiss() + } + ) { + Column( + modifier = Modifier + .align(Alignment.BottomCenter) + .fillMaxWidth() + .background( + LocalDashColors.current.backgroundPrimary, + RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp) + ) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + .navigationBarsPadding() + ) { + Grabber() + content() + } + } +} + +/** Figma 7076:47424 "Select source": the four balances with a radio; unsupported rows disabled. */ +@Composable +private fun SourceSheet(uiState: ExternalSendUIState, actions: ExternalSendActions) { + SheetOverlay(onDismiss = actions.onDismissSourceSheet) { + TopNavBase( + leadingPart = false, + trailingIcon = MyImages.NavBarClose, + trailingContentDescription = stringResource(R.string.external_send_close), + onTrailingClick = actions.onDismissSourceSheet, + title = stringResource(R.string.external_send_select_source) + ) + Spacer(modifier = Modifier.height(10.dp)) + Menu { + uiState.sources.forEach { source -> + val supported = uiState.supportOf(source) == SendSupport.SUPPORTED + val selected = source == uiState.source + ActionItem( + title = stringResource(titleFor(source)), + icon = iconFor(source), + enabled = supported, + subtitle = if (supported) null else stringResource(R.string.external_send_source_unavailable), + trailingContent = { Radio(selected) }, + onClick = { actions.onSourceSelected(source) } + ) + } + } + Spacer(modifier = Modifier.height(20.dp)) + } +} + +@Composable +private fun Radio(selected: Boolean) { + val colors = LocalDashColors.current + Box( + modifier = Modifier + .size(22.dp) + .border( + width = if (selected) 6.dp else 1.5.dp, + color = if (selected) colors.dashBlue else colors.lightGray, + shape = CircleShape + ) + ) +} + +/** Figma 7076:47968 / 7107:48421: amount, From / To / Network fee / Total, info notes, buttons. */ +@Composable +private fun ConfirmSheet(uiState: ExternalSendUIState, confirm: ExternalSendConfirm, actions: ExternalSendActions) { + val request = confirm.request + val unknown = stringResource(R.string.external_send_value_unknown) + SheetOverlay(onDismiss = actions.onDismissConfirm) { + TopNavBase( + leadingPart = false, + trailingPart = false, + title = stringResource(R.string.external_send_confirm_title) + ) + // Weighted (not filling) so the scrolling details shrink on a short screen or with large + // text and the Cancel/Confirm row below always keeps its height. + Column( + modifier = Modifier + .fillMaxWidth() + .weight(1f, fill = false) + .verticalScroll(rememberScrollState()) + ) { + // What the recipient receives (a Core Max drain: the amount minus the fee, unknown + // while the fee is; a Shielded → Core Max: the amount minus the Core fee). + val recipientAmount = confirm.recipientAmount?.takeIf { !confirm.feeIncluded || !confirm.feeLoading } + ConfirmAmount(recipientAmount, uiState.rate, uiState.fiatCode, unknown) + Spacer(modifier = Modifier.height(20.dp)) + Menu { + ListItem1( + label = stringResource(R.string.external_send_from), + value = stringResource(balanceNameFor(request.source)) + ) + val destination = request.destination + val toValue = when (destination) { + is SendDestination.Identity -> + (uiState.identityResolution as? IdentityResolution.Found)?.username + ?: ExternalSendViewModel.shorten(destination.display) + else -> ExternalSendViewModel.shorten(destination.display) + } + ListItem1(label = stringResource(R.string.external_send_to), value = toValue) + val fee = if (confirm.feeLoading) null else confirm.fee + DashValueRow( + label = stringResource(R.string.external_send_network_fee), + value = fee?.let { approximate(it.fee.toDisplayString(), !it.exact) }, + unknown = unknown + ) + DashValueRow( + label = stringResource(R.string.external_send_total), + // A drain's total is the confirmed amount itself (exact); otherwise amount + fee. + value = confirm.total?.takeIf { fee != null || confirm.feeIncluded }?.let { total -> + approximate(total.toDisplayString(), !confirm.feeIncluded && fee?.exact != true) + }, + unknown = unknown + ) + ConfirmNotes(request.source, destination) + } + } + Row( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.button_cancel), + style = Style.TintedGray, + size = Size.Large, + onClick = actions.onDismissConfirm + ) + DashButton( + modifier = Modifier.weight(1f), + text = stringResource(R.string.button_confirm), + style = Style.FilledBlue, + size = Size.Large, + onClick = actions.onConfirm + ) + } + } +} + +/** A confirm row whose value is a Dash amount: the Dash symbol before it, or [unknown] alone. */ +@Composable +private fun DashValueRow(label: String, value: String?, unknown: String) { + val colors = LocalDashColors.current + ListItem( + label = label, + trailingText = value ?: unknown, + trailingLeadingIcon = if (value != null) { + { + Icon( + painter = painterResource(org.dash.wallet.common.R.drawable.ic_dash_d_black), + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(12.dp) + ) + } + } else { + null + } + ) +} + +@Composable +private fun approximate(value: String, estimate: Boolean): String = + if (estimate) stringResource(R.string.external_send_approximately, value) else value + +/** + * The confirm sheet's amount block (Figma "amount" 380x97): the same bar as the amount page, + * read-only. A null [amount] (not known yet) shows [unknown], as the fee and total rows do. + */ +@Composable +private fun ConfirmAmount(amount: Dash?, rate: Fiat?, fiatCode: String?, unknown: String) { + val separator = remember { decimalSeparatorFor(Locale.getDefault()) } + val fiat = amount?.toFiatAt(rate) + EnterAmount( + primaryAmount = amount?.let { localizeAmountForDisplay(it.toDisplayString(), separator) } ?: unknown, + secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", + currencyCodes = remember(fiatCode) { currencyCodesFor(fiatCode) }, + selectedCurrencyIndex = 0, + showMaxButton = false, + showBalanceButton = false, + showPrimaryChevron = false, + showSecondary = fiat != null, + showCurrencyPicker = false, + modifier = Modifier.padding(horizontal = 20.dp) + ) +} + +/** + * Figma 7107:48594 (in 7107:48421): from the Shielded balance to anywhere but Shielded, two + * System messages: the send is not instant (icon `info-rect-small`), and the amount and + * destination become public (icon `system_message-public`). No other route shows a note. + */ +@Composable +private fun ConfirmNotes(source: SendBalance, destination: SendDestination) { + if (source != SendBalance.SHIELDED || destination is SendDestination.Shielded) return + val publicNote = when (destination) { + is SendDestination.Core -> R.string.external_send_shielded_public_to_core + is SendDestination.Platform -> R.string.external_send_shielded_public_to_platform + else -> R.string.external_send_shielded_public_to_identity + } + val notes = listOf( + R.string.external_send_shielded_not_instant to R.drawable.ic_system_message_info, + publicNote to R.drawable.ic_system_message_public + ) + Column( + modifier = Modifier + .fillMaxWidth() + .padding(start = 10.dp, end = 10.dp, top = 18.dp, bottom = 14.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + notes.forEach { (note, icon) -> + SystemMessage( + description = stringResource(note), + // At the icon's own Figma size, centred in the 30dp leading slot: `iconRes` + // would draw every icon at 18dp. + icon = { Image(painter = painterResource(icon), contentDescription = null) } + ) + } + } +} + +// ── Progress and outcome ──────────────────────────────────────────────────── + +/** + * The send is running on the app scope. Leaving does not cancel it; the outcome shows when the + * user opens the external send again. + */ +@Composable +private fun SendingOverlay(shieldedLeg: Boolean, onLeave: () -> Unit) { + val colors = LocalDashColors.current + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, + contentAlignment = Alignment.Center + ) { + Column( + modifier = Modifier + .padding(horizontal = 40.dp) + .background(colors.backgroundSecondary, RoundedCornerShape(20.dp)) + .padding(30.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + CircularProgressIndicator(color = colors.dashBlue) + Text( + text = stringResource(R.string.external_send_sending_title), + style = MyTheme.Typography.TitleMediumSemibold, + color = colors.textPrimary, + textAlign = TextAlign.Center + ) + Text( + text = stringResource( + if (shieldedLeg) R.string.external_send_sending_shielded_message else R.string.external_send_sending_message + ), + style = MyTheme.Typography.BodyMedium, + color = colors.textSecondary, + textAlign = TextAlign.Center + ) + if (shieldedLeg) { + DashButton( + text = stringResource(R.string.external_send_close), + style = Style.TintedGray, + size = Size.Large, + onClick = onLeave + ) + } + } + } +} + +/** + * The terminal outcome. Only Not sent offers to go back and edit; nothing offers a retry. + * + * Drawn inside the screen, like [SheetOverlay] and [SendingOverlay], rather than as a + * [org.dash.wallet.common.ui.components.ModalDialog]: a dialog is its own window, which stays + * above the lock screen and could be closed without the PIN. In the screen it is covered by the + * lock screen and shows again after unlock. The card copies that dialog's layout so it looks the + * same. Back is handled by the + * fragment, which acknowledges the outcome as the dialog's dismiss-on-back did. + */ +@Composable +private fun ResultOverlay(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { + val colors = LocalDashColors.current + val content = resultContentFor(result, afterRestart) + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { + onClose() + }, + contentAlignment = Alignment.Center + ) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 15.dp) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, + shape = RoundedCornerShape(16.dp), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), + colors = CardDefaults.cardColors( + containerColor = colors.backgroundSecondary, + contentColor = colors.textPrimary + ) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .background(colors.backgroundSecondary) + .padding(start = 20.dp, end = 20.dp, top = 32.dp, bottom = 20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon( + imageVector = ImageVector.vectorResource(content.icon), + contentDescription = null, + tint = Color.Unspecified, + modifier = Modifier.size(46.dp) + ) + Spacer(modifier = Modifier.height(20.dp)) + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + Text( + text = stringResource(content.title), + style = MyTheme.SubtitleSemibold, + textAlign = TextAlign.Center, + color = colors.textPrimary + ) + Text( + text = stringResource(content.message), + style = MyTheme.Body2Regular, + textAlign = TextAlign.Center, + color = colors.textPrimary + ) + Spacer(modifier = Modifier.height(20.dp)) + } + Spacer(modifier = Modifier.height(32.dp)) + DashButton( + text = stringResource(content.button), + onClick = onClose, + modifier = Modifier.fillMaxWidth(), + size = Size.Medium, + style = Style.TintedGray + ) + } + } + } +} + +/** What the outcome dialog shows for [result]. */ +internal data class ResultContent( + @DrawableRes val icon: Int, + @StringRes val title: Int, + @StringRes val message: Int, + @StringRes val button: Int +) + +internal fun resultContentFor(result: ExternalSendResult, afterRestart: Boolean = false): ResultContent = when (result) { + is ExternalSendResult.Sent -> ResultContent( + org.dash.wallet.common.R.drawable.ic_success_green, + R.string.external_send_sent_title, + R.string.external_send_sent_message, + R.string.external_send_close + ) + is ExternalSendResult.NotSent -> ResultContent( + org.dash.wallet.common.R.drawable.ic_error, + R.string.external_send_not_sent_title, + notSentMessageFor(result.reason), + R.string.external_send_edit + ) + ExternalSendResult.MayHaveGoneThrough -> ResultContent( + org.dash.wallet.common.R.drawable.ic_toast_info_warning, + R.string.external_send_ambiguous_title, + if (afterRestart) R.string.external_send_ambiguous_after_restart_message else R.string.external_send_ambiguous_message, + R.string.external_send_close + ) + ExternalSendResult.InterruptedFundsReturnToShielded -> ResultContent( + org.dash.wallet.common.R.drawable.ic_toast_info_warning, + R.string.external_send_interrupted_title, + R.string.external_send_interrupted_message, + R.string.external_send_close + ) +} + +@StringRes +internal fun notSentMessageFor(reason: NotSentReason): Int = when (reason) { + NotSentReason.INSUFFICIENT_FUNDS -> R.string.external_send_not_sent_insufficient_funds + NotSentReason.NOT_SYNCED -> R.string.external_send_not_sent_not_synced + NotSentReason.SIGNER_LOCKED -> R.string.external_send_not_sent_signer_locked + NotSentReason.NOT_SUPPORTED -> R.string.external_send_not_sent_not_supported + NotSentReason.PAYMENT_STILL_CONFIRMING -> R.string.external_send_not_sent_still_confirming + NotSentReason.IN_PROGRESS -> R.string.external_send_not_sent_in_progress + NotSentReason.BALANCE_CHANGED -> R.string.external_send_not_sent_balance_changed + NotSentReason.EARLIER_TOP_UP_COMPLETED -> R.string.external_send_not_sent_earlier_top_up_completed + NotSentReason.GENERIC -> R.string.external_send_not_sent_generic +} + +// ── Icons and names ───────────────────────────────────────────────────────── + +@DrawableRes +internal fun iconFor(source: SendBalance): Int = when (source) { + SendBalance.CORE -> org.dash.wallet.common.R.drawable.ic_dash_blue_filled + SendBalance.SHIELDED -> R.drawable.ic_shielded_balance + SendBalance.PLATFORM -> R.drawable.ic_menu_credits + SendBalance.IDENTITY -> R.drawable.ic_contact +} + +@DrawableRes +internal fun iconFor(destination: SendDestination): Int = iconFor(balanceKindOf(destination)) + +@StringRes +internal fun titleFor(source: SendBalance): Int = when (source) { + SendBalance.CORE -> R.string.external_send_balance_core + SendBalance.SHIELDED -> R.string.external_send_balance_shielded + SendBalance.PLATFORM -> R.string.external_send_balance_platform + SendBalance.IDENTITY -> R.string.external_send_balance_identity +} + +@StringRes +internal fun titleFor(destination: SendDestination): Int = titleFor(balanceKindOf(destination)) + +@StringRes +internal fun balanceNameFor(source: SendBalance): Int = when (source) { + SendBalance.CORE -> R.string.external_send_balance_name_core + SendBalance.SHIELDED -> R.string.external_send_balance_name_shielded + SendBalance.PLATFORM -> R.string.external_send_balance_name_platform + SendBalance.IDENTITY -> R.string.external_send_balance_name_identity +} + +@Preview(showBackground = true, widthDp = 420, heightDp = 926) +@Composable +private fun ExternalSendAmountPreview() { + DashWalletTheme { + ExternalSendScreen( + uiState = ExternalSendUIState( + step = ExternalSendStep.AMOUNT, + destination = SendDestination.Shielded( + "tdash1zqumn3c48sdenak7qr0f8jp3z2d8vg5kafv5snc73tjadg27ajyr7sflp726gtts4u2elrs27eg4a" + ), + amountText = "1", + balance = Dash.COIN * 2L, + maxSendable = Dash.COIN * 2L + ), + actions = previewActions() + ) + } +} + +/** QA's case (MO-1121): a small phone; Cancel/Confirm must stay on screen, the details scroll. */ +@Preview(showBackground = true, widthDp = 320, heightDp = 640) +@Composable +private fun ExternalSendConfirmShieldedToIdentitySmallPreview() { + ConfirmPreview(SendDestination.Identity("3rTvtFT7juaJkxdY3Fh6oQBbeBeXsp9gY8HgKLUPowM5")) +} + +/** Figma 7107:48421 (Shielded → Core) on a small phone. */ +@Preview(showBackground = true, widthDp = 320, heightDp = 640) +@Composable +private fun ExternalSendConfirmShieldedToCoreSmallPreview() { + ConfirmPreview(SendDestination.Core("yjSvwyLB5X4dqQqVMPMu6UdrFpYZ3u9v5U")) +} + +/** Figma 7107:48421 at its own size (420 x 840). */ +@Preview(showBackground = true, widthDp = 420, heightDp = 840) +@Composable +private fun ExternalSendConfirmShieldedToCorePreview() { + ConfirmPreview(SendDestination.Core("yjSvwyLB5X4dqQqVMPMu6UdrFpYZ3u9v5U")) +} + +@Composable +private fun ConfirmPreview(destination: SendDestination) { + val amount = Dash(50_000_000L) + DashWalletTheme { + ExternalSendScreen( + uiState = ExternalSendUIState( + step = ExternalSendStep.AMOUNT, + destination = destination, + source = SendBalance.SHIELDED, + amountText = "0.5", + balance = Dash.COIN * 2L, + confirm = ExternalSendConfirm( + request = ExternalSendRequest( + source = SendBalance.SHIELDED, + destination = destination, + amount = amount, + isMax = false, + expectedWalletIdHex = null + ), + fee = FeeEstimate(Dash(10_000L), exact = false), + feeLoading = false + ) + ), + actions = previewActions() + ) + } +} + +private fun previewActions() = ExternalSendActions( + onBack = {}, onAddressChanged = {}, onScanClick = {}, onShowClipboard = {}, onClipboardEntrySelected = {}, + onAddressContinue = {}, onKeyInput = {}, onCurrencySelected = {}, onMaxClick = {}, onShowSourceSheet = {}, + onDismissSourceSheet = {}, onSourceSelected = {}, onRetryIdentity = {}, onAmountContinue = {}, + onDismissConfirm = {}, onConfirm = {}, onLeave = {}, onResultClosed = {} +) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt new file mode 100644 index 0000000000..6cf197f295 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -0,0 +1,828 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.schildbach.wallet.Constants +import de.schildbach.wallet.service.platform.sdk.DestinationParse +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.ExternalSendService +import de.schildbach.wallet.service.platform.sdk.ExternalSendServiceImpl +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.IdentityResolution +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.SendDestination +import de.schildbach.wallet.service.platform.sdk.SendSupport +import de.schildbach.wallet.service.platform.sdk.WITHDRAWAL_CORE_FEE_DUFFS +import de.schildbach.wallet.service.platform.sdk.balanceKindOf +import de.schildbach.wallet.service.platform.sdk.detectSendDestination +import de.schildbach.wallet.service.platform.sdk.externalSendSupport +import de.schildbach.wallet.service.platform.sdk.maxBoundsAmount +import de.schildbach.wallet.ui.shielded.parseDashOrNull +import de.schildbach.wallet.ui.shielded.parseDecimalOrNull +import de.schildbach.wallet.ui.shielded.toDashAt +import de.schildbach.wallet.ui.shielded.toFiatAt +import de.schildbach.wallet.ui.shielded.toKeypadString +import de.schildbach.wallet.ui.shielded.toKeypadStringTwoDecimals +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.transformLatest +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import org.dash.wallet.common.data.WalletUIConfig +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.money.Fiat +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.services.ExchangeRatesProvider +import org.dash.wallet.common.ui.enter_amount.processAmountKeyInput +import org.dash.wallet.common.util.toFiat +import javax.inject.Inject + +private fun Char.isHexDigitChar(): Boolean = this in '0'..'9' || this in 'a'..'f' || this in 'A'..'F' + +/** The two pages of the external send flow. */ +enum class ExternalSendStep { ADDRESS, AMOUNT } + +/** What the screen shows for the external send the [ExternalSendExecutor] runs. */ +sealed class ExternalSendStatus { + /** Whether a previous process left a send in flight is still being read; nothing can be sent. */ + object Restoring : ExternalSendStatus() + + object Idle : ExternalSendStatus() + + /** In flight; [shieldedLeg] = a ~30 s proof is involved. */ + data class Sending(val shieldedLeg: Boolean) : ExternalSendStatus() + + /** + * Terminal until acknowledged. [afterRestart]: the app was closed while a send may have + * been in flight ([result] is then [ExternalSendResult.MayHaveGoneThrough]). + */ + data class Done(val result: ExternalSendResult, val afterRestart: Boolean = false) : ExternalSendStatus() +} + +/** + * The confirm sheet: [request] is exactly what Confirm sends. [fee] null with [feeLoading] false + * means the fee cannot be known before the send (never fabricated). + */ +data class ExternalSendConfirm( + val request: ExternalSendRequest, + val fee: FeeEstimate? = null, + val feeLoading: Boolean = true +) { + /** + * A Core → Core Max is the SDK drain: the fee comes OUT of [ExternalSendRequest.amount] + * (the Basic send's `sendAllBalance` semantics: delivered = amount − fee, total = amount). + */ + val feeIncluded: Boolean + get() = request.isMax && request.source == SendBalance.CORE && request.destination is SendDestination.Core + + /** + * A Shielded → Core Max withdraws [ExternalSendRequest.amount] itself, and DPP takes the asset + * unlock's Core fee ([WITHDRAWAL_CORE_FEE_DUFFS]) out of it: the recipient receives the amount + * minus that fee. Every other withdrawal to Core withdraws the fee on top of the amount. + */ + val coreFeeIncluded: Boolean + get() = request.isMax && request.source == SendBalance.SHIELDED && request.destination is SendDestination.Core + + /** + * What the recipient receives: the amount; for a drain the amount minus the fee (null while + * the fee is loading or unknown: the gross amount would overstate it); for a Shielded → Core + * Max the amount minus the Core fee. + */ + val recipientAmount: Dash? + get() = when { + feeIncluded -> fee?.let { request.amount - it.fee } + coreFeeIncluded -> request.amount - Dash(WITHDRAWAL_CORE_FEE_DUFFS) + else -> request.amount + } + + /** + * What leaves the balance: what the recipient receives plus the fee (null while the fee is + * unknown), or for a drain the amount. + */ + val total: Dash? + get() = if (feeIncluded) request.amount else recipientAmount?.let { amount -> fee?.let { amount + it.fee } } +} + +/** + * Single UI state of the Advanced-mode external send (MO-1121). + * + * @property balance the selected [source]'s spendable balance; null = unknown (shown as a + * placeholder, never as 0, and it blocks Continue). + * @property maxSendable null = unknown: Max is unavailable and the [balance] bounds the amount. + * @property maxPending Max was set when the source changed: it follows the new [source] once + * that source's [maxSendable] is known (or is dropped when it has none). Meanwhile the amount + * is zero, so the old source's Max can never be confirmed against the new source. + * @property pinnedAmount the exact amount while [amountText] is only its rendering (a currency + * switch rounds fiat to two decimals, a dropped Max leaves its text): never re-parsed until + * the user edits the amount (see `ShieldedTransferViewModel`'s pinnedAmount). + * @property identityResolution for an identity destination: null while checking. + * @property sourceChosenByUser the user picked [source] in the sheet; until then the first + * supported source is chosen automatically as the inputs arrive. + * @property finished the user acknowledged a terminal outcome other than not-sent: the flow is + * over and the form, which still holds the sent amount, stays inert while the screen leaves + * (the executor returning to Idle must not re-enable it). + */ +data class ExternalSendUIState( + val step: ExternalSendStep = ExternalSendStep.ADDRESS, + val addressInput: String = "", + val addressParse: DestinationParse = DestinationParse.Empty, + val clipboardShown: Boolean = false, + val clipboardEntries: List = emptyList(), + val destination: SendDestination? = null, + val amountText: String = "0", + val dashMode: Boolean = true, + val maxAmount: Dash? = null, + val maxPending: Boolean = false, + val pinnedAmount: Dash? = null, + val fiatCode: String? = null, + val rate: Fiat? = null, + val source: SendBalance = SendBalance.CORE, + val sourceChosenByUser: Boolean = false, + val hasIdentity: Boolean? = null, + val destinationIsOwnIdentity: Boolean? = null, + val identityResolution: IdentityResolution? = null, + val balance: Dash? = null, + val maxSendable: Dash? = null, + val showSourceSheet: Boolean = false, + val confirm: ExternalSendConfirm? = null, + val status: ExternalSendStatus = ExternalSendStatus.Idle, + val finished: Boolean = false +) { + /** + * The txid of a sent outcome that is shown by the transaction result screen (the fragment + * opens it once, then acknowledges) instead of the in-screen result. Null for every other + * outcome, for a Sent without a well-formed txid (64 hex characters, so `Sha256Hash.wrap` + * cannot throw), and once acknowledged ([finished]). + */ + val openTransactionResult: String? + get() = if (finished) { + null + } else { + ((status as? ExternalSendStatus.Done)?.result as? ExternalSendResult.Sent)?.txIdOrNull + ?.takeIf { txId -> txId.length == 64 && txId.all { it.isHexDigitChar() } } + } + + /** The form can be edited: no send running or unacknowledged, and the flow not over. */ + val formEditable: Boolean + get() = status == ExternalSendStatus.Idle && !finished + + /** A non-blank input that is not a destination of this network. */ + val addressError: Boolean + get() = addressParse is DestinationParse.WrongNetwork || addressParse is DestinationParse.Invalid + + val canContinueAddress: Boolean + get() = addressParse is DestinationParse.Valid && !finished + + /** The sources the sheet lists, in order; Identity only for a user who has one. */ + val sources: List + get() = SendBalance.entries.filter { it != SendBalance.IDENTITY || hasIdentity == true } + + /** Whether [source] can pay [destination]; null before a destination is set. */ + fun supportOf(source: SendBalance): SendSupport? = destination?.let { + externalSendSupport(source, it, hasIdentity == true, destinationIsOwnIdentity) + } + + /** Max is set: the exact [maxAmount], whatever the currency shown. */ + val isMax: Boolean + get() = maxAmount != null + + /** The amount in Dash (fiat converted at [rate]); zero when unparseable or no rate. */ + val amount: Dash + get() = maxAmount ?: pinnedAmount ?: if (dashMode) { + parseDashOrNull(amountText) ?: Dash.ZERO + } else { + val code = fiatCode + if (code == null) Dash.ZERO else parseDecimalOrNull(amountText)?.toFiat(code)?.toDashAt(rate) ?: Dash.ZERO + } + + /** The amount in the other currency, '.'-separated for the amount page; null without a rate. */ + val secondaryAmountText: String? + get() = if (dashMode) { + amount.toFiatAt(rate)?.toKeypadStringTwoDecimals() ?: if (rate == null) null else "0" + } else { + amount.toKeypadString() + } + + /** + * What the amount may not exceed: the max sendable when known, else the balance; for a + * pair whose Max is its bound ([maxBoundsAmount]) the max sendable only (null blocks). + */ + val limit: Dash? + get() = if (maxIsTheBound) maxSendable else maxSendable ?: balance + + private val maxIsTheBound: Boolean + get() = destination?.let { maxBoundsAmount(source, balanceKindOf(it)) } == true + + val exceedsBalance: Boolean + get() = limit?.let { amount.isGreaterThan(it) } == true + + /** An identity destination must be confirmed to exist (AC8); NotFound or Unknown blocks. */ + val identityBlocks: Boolean + get() = destination is SendDestination.Identity && identityResolution !is IdentityResolution.Found + + val canContinueAmount: Boolean + get() = step == ExternalSendStep.AMOUNT && + destination != null && + supportOf(source) == SendSupport.SUPPORTED && + amount.isPositive && + !maxPending && + balance != null && + limit != null && + !exceedsBalance && + (dashMode || rate != null || pinnedAmount != null || maxAmount != null) && + !identityBlocks && + formEditable +} + +/** + * The Advanced-mode external send flow (MO-1121): address, then amount and source, then + * confirm → PIN/biometric (the fragment) → [ExternalSendExecutor]. Nothing optimistic: the send + * state is mirrored from the executor. + */ +@OptIn(ExperimentalCoroutinesApi::class) +@HiltViewModel +class ExternalSendViewModel internal constructor( + private val service: ExternalSendService, + private val executor: ExternalSendExecutor, + walletUIConfig: WalletUIConfig, + exchangeRates: ExchangeRatesProvider, + private val savedState: SavedStateHandle, + private val network: AddressNetwork, + private val maxRetryDelayMs: Long = ExternalSendServiceImpl.BALANCE_POLL_MS +) : ViewModel() { + + @Inject + constructor( + service: ExternalSendService, + executor: ExternalSendExecutor, + walletUIConfig: WalletUIConfig, + exchangeRates: ExchangeRatesProvider, + savedState: SavedStateHandle + ) : this( + service, + executor, + walletUIConfig, + exchangeRates, + savedState, + AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id) + ) + + companion object { + /** Nav argument: a scanned/typed destination (address, identity id or `dash:` URI). */ + const val ARG_PREFILL = "prefill" + + internal const val KEY_SEEDED = "external_send_seeded" + internal const val KEY_ADDRESS = "external_send_address" + internal const val KEY_STEP = "external_send_step" + internal const val KEY_AMOUNT = "external_send_amount" + internal const val KEY_DASH_MODE = "external_send_dash_mode" + internal const val KEY_MAX_DUFFS = "external_send_max_duffs" + internal const val KEY_MAX_PENDING = "external_send_max_pending" + internal const val KEY_PINNED_DUFFS = "external_send_pinned_duffs" + internal const val KEY_SOURCE = "external_send_source" + internal const val KEY_SOURCE_CHOSEN = "external_send_source_chosen" + internal const val KEY_FINISHED = "external_send_finished" + + private const val DASH_DECIMALS = 8 + private const val FIAT_DECIMALS = 2 + private const val MAX_CLIPBOARD_ENTRIES = 3 + + /** "tdash1z...lrs27eg4" — the first 7 and last 8 characters of a long address or id. */ + fun shorten(value: String, head: Int = 7, tail: Int = 8): String = + if (value.length <= head + tail + 3) value else "${value.take(head)}...${value.takeLast(tail)}" + + /** Whether a send from [source] to [destination] involves a ~30 s shielded proof. */ + fun hasShieldedLeg(source: SendBalance, destination: SendDestination): Boolean = + source == SendBalance.SHIELDED || destination is SendDestination.Shielded + } + + private val _uiState = MutableStateFlow(ExternalSendUIState()) + val uiState: StateFlow = _uiState.asStateFlow() + + /** + * [ExternalSendUIState.openTransactionResult] as its own flow, for the fragment's + * resumed-and-unlocked delivery. It may lag [uiState] by a dispatch; [takeTransactionResult] + * checks the live state. + */ + val openTransactionResult: StateFlow = _uiState + .map { it.openTransactionResult } + .distinctUntilChanged() + .stateIn(viewModelScope, SharingStarted.Eagerly, null) + + private var balanceJob: Job? = null + private var balanceGeneration = 0 + private var identityJob: Job? = null + private var ownIdentityJob: Job? = null + private var feeJob: Job? = null + + init { + restoreOrSeed() + if (savedState.get(KEY_FINISHED) == true) { + _uiState.update { it.copy(finished = true) } + } + + service.observeHasIdentity() + .onEach { has -> + _uiState.update { it.copy(hasIdentity = has) } + autoPickSource() + } + .launchIn(viewModelScope) + + walletUIConfig.observe(WalletUIConfig.SELECTED_CURRENCY) + .filterNotNull() + .onEach { code -> _uiState.update { it.copy(fiatCode = code) } } + .flatMapLatest(exchangeRates::observeExchangeRate) + .onEach { rate -> _uiState.update { it.copy(rate = rate?.fiat) } } + .launchIn(viewModelScope) + + // Finish an interrupted Core → Platform send, if any (background, app-scoped). + executor.resumePendingPlatformFunding() + + executor.state + .onEach { execution -> + val status = when (execution) { + ExternalSendExecution.Restoring -> ExternalSendStatus.Restoring + ExternalSendExecution.InterruptedByRestart -> + ExternalSendStatus.Done(ExternalSendResult.MayHaveGoneThrough, afterRestart = true) + ExternalSendExecution.Idle -> ExternalSendStatus.Idle + // An outcome being dismissed: no dialog, nothing can be sent yet. + ExternalSendExecution.Acknowledging -> ExternalSendStatus.Restoring + is ExternalSendExecution.Sending -> ExternalSendStatus.Sending( + hasShieldedLeg(execution.request.source, execution.request.destination) + ) + is ExternalSendExecution.Finished -> ExternalSendStatus.Done(execution.result) + } + _uiState.update { it.copy(status = status) } + } + .launchIn(viewModelScope) + } + + private fun restoreOrSeed() { + if (savedState.get(KEY_SEEDED) != true) { + savedState[KEY_SEEDED] = true + val prefill = savedState.get(ARG_PREFILL) + if (!prefill.isNullOrBlank()) { + onAddressChanged(prefill) + val parse = _uiState.value.addressParse + if (parse is DestinationParse.Valid) { + enterAmountStep(parse.destination, parse.amount) + } + } + return + } + // Process restore: rebuild from what was saved. + val address = savedState.get(KEY_ADDRESS).orEmpty() + onAddressChanged(address) + val parse = _uiState.value.addressParse + if (savedState.get(KEY_STEP) == ExternalSendStep.AMOUNT.name && parse is DestinationParse.Valid) { + val source = savedState.get(KEY_SOURCE) + ?.let { name -> SendBalance.entries.firstOrNull { it.name == name } } + val chosen = savedState.get(KEY_SOURCE_CHOSEN) == true && source != null + // Read before enterAmountStep, which saves its own (reset) amount. + val amountText = savedState.get(KEY_AMOUNT) ?: "0" + val dashMode = savedState.get(KEY_DASH_MODE) ?: true + val maxAmount = savedState.get(KEY_MAX_DUFFS)?.let(::Dash) + val maxPending = maxAmount == null && savedState.get(KEY_MAX_PENDING) == true + val pinnedAmount = savedState.get(KEY_PINNED_DUFFS)?.let(::Dash) + enterAmountStep(parse.destination, amount = null) + if (chosen && source != null) { + selectSource(source, byUser = true) + } + // After the source: restoring the source must not turn the saved Max into a pending one. + _uiState.update { + it.copy( + amountText = amountText, + dashMode = dashMode, + maxAmount = maxAmount, + maxPending = maxPending, + pinnedAmount = pinnedAmount + ) + } + saveAmount() + // The source's Max may already have been read before the pending Max was restored: + // read it again so the restored pending Max resolves. + if (maxPending) restartBalance() + } + } + + // ── Address step ───────────────────────────────────────────────────────── + + fun onAddressChanged(input: String) { + val parse = detectSendDestination(input, network) + _uiState.update { + it.copy( + addressInput = input, + addressParse = parse, + clipboardShown = it.clipboardShown && input.isEmpty() + ) + } + savedState[KEY_ADDRESS] = input + } + + /** + * The user tapped "Show clipboard": [text] is the clipboard's text, read only on that tap. + * Only tokens that are destinations of this network are offered. + */ + fun onClipboardRead(text: String?) { + val entries = text.orEmpty() + .split(Regex("\\s+")) + .filter { it.isNotEmpty() && detectSendDestination(it, network) is DestinationParse.Valid } + .distinct() + .take(MAX_CLIPBOARD_ENTRIES) + _uiState.update { it.copy(clipboardShown = true, clipboardEntries = entries) } + } + + fun onClipboardEntrySelected(entry: String) { + onAddressChanged(entry) + _uiState.update { it.copy(clipboardShown = false, clipboardEntries = emptyList()) } + } + + fun onAddressContinue() { + if (!_uiState.value.canContinueAddress) return + val parse = _uiState.value.addressParse + if (parse is DestinationParse.Valid) { + enterAmountStep(parse.destination, parse.amount) + } + } + + private fun enterAmountStep(destination: SendDestination, amount: Dash?) { + val previous = _uiState.value.destination + val sameDestination = previous == destination + _uiState.update { + it.copy( + step = ExternalSendStep.AMOUNT, + destination = destination, + destinationIsOwnIdentity = if (sameDestination) it.destinationIsOwnIdentity else null, + identityResolution = if (sameDestination) it.identityResolution else null, + sourceChosenByUser = it.sourceChosenByUser && sameDestination, + amountText = amount?.toKeypadString() ?: if (sameDestination) it.amountText else "0", + dashMode = if (amount != null) true else it.dashMode, + // A new destination (or a URI amount) resets the amount, Max and a pending Max with it. + maxAmount = if (sameDestination && amount == null) it.maxAmount else null, + maxPending = sameDestination && amount == null && it.maxPending, + // A URI amount is exact; it stays pinned until the user edits it. + pinnedAmount = amount ?: if (sameDestination) it.pinnedAmount else null, + confirm = null, + showSourceSheet = false + ) + } + savedState[KEY_STEP] = ExternalSendStep.AMOUNT.name + saveAmount() + if (!sameDestination || _uiState.value.identityResolution == null) { + checkIdentity(destination) + } + if (!autoPickSource()) { + restartBalance() + } + } + + // ── Amount step ────────────────────────────────────────────────────────── + + fun onKeyInput(key: String) { + val state = _uiState.value + if (!state.formEditable) return + // Editing a Max amount edits what is on show. + val base = if (state.isMax) displayTextFor(state.amount, state.dashMode, state.rate) else state.amountText + val decimals = if (state.dashMode) DASH_DECIMALS else FIAT_DECIMALS + val text = processAmountKeyInput(base, key, decimals) + // A key the keypad rejected (text unchanged) keeps the exact amount; any key cancels a + // pending Max (the user is entering an amount themselves). + if (text == state.amountText && !state.isMax && !state.maxPending) return + _uiState.update { it.copy(amountText = text, maxAmount = null, maxPending = false, pinnedAmount = null) } + saveAmount() + } + + fun onCurrencySelected(dashMode: Boolean) { + val state = _uiState.value + if (state.dashMode == dashMode) return + if (!dashMode && state.rate == null) return + val amount = state.amount + val text = if (amount.isZero) "0" else displayTextFor(amount, dashMode, state.rate) + // Switching the currency shown never changes what is sent: the exact amount stays + // pinned (Max already is) until the user edits it. + _uiState.update { + it.copy( + dashMode = dashMode, + amountText = text, + pinnedAmount = if (amount.isZero || state.isMax) null else amount + ) + } + saveAmount() + } + + fun onMaxClick() { + val state = _uiState.value + val max = state.maxSendable ?: return + if (!state.formEditable) return + _uiState.update { + it.copy( + maxAmount = max, + maxPending = false, + pinnedAmount = null, + amountText = displayTextFor(max, it.dashMode, it.rate) + ) + } + saveAmount() + } + + fun onShowSourceSheet() { + if (_uiState.value.finished) return + _uiState.update { it.copy(showSourceSheet = true) } + } + + fun onDismissSourceSheet() { + _uiState.update { it.copy(showSourceSheet = false) } + } + + /** Only a source that is listed and can pay the destination can be picked. */ + fun onSourceSelected(source: SendBalance) { + val state = _uiState.value + if (state.finished) return + if (source !in state.sources || state.supportOf(source) != SendSupport.SUPPORTED) return + selectSource(source, byUser = true) + _uiState.update { it.copy(showSourceSheet = false) } + } + + fun onRetryIdentity() { + val destination = _uiState.value.destination as? SendDestination.Identity ?: return + _uiState.update { it.copy(identityResolution = null) } + checkIdentity(destination) + } + + private fun selectSource(source: SendBalance, byUser: Boolean) { + val changed = _uiState.value.source != source + _uiState.update { + // Max follows the source: the old source's Max is never kept as an amount for the new + // one. Until the new source's Max is read the amount is zero (Continue stays disabled). + val followMax = changed && (it.isMax || it.maxPending) + it.copy( + source = source, + sourceChosenByUser = it.sourceChosenByUser || byUser, + maxAmount = if (changed) null else it.maxAmount, + maxPending = if (changed) followMax else it.maxPending, + pinnedAmount = if (followMax) null else it.pinnedAmount, + amountText = if (followMax) "0" else it.amountText, + balance = if (changed) null else it.balance, + maxSendable = if (changed) null else it.maxSendable + ) + } + saveAmount() + savedState[KEY_SOURCE] = source.name + savedState[KEY_SOURCE_CHOSEN] = _uiState.value.sourceChosenByUser + if (changed || balanceJob == null) { + restartBalance() + } + } + + /** + * Until the user picks a source: the first supported one in Core, Shielded, Platform, + * Identity order. A user's pick that is no longer listed (identity gone) is dropped. + * Returns whether the balance observation was restarted. + */ + private fun autoPickSource(): Boolean { + val state = _uiState.value + if (state.destination == null) return false + if (state.sourceChosenByUser && state.source in state.sources) return false + val pick = state.sources.firstOrNull { state.supportOf(it) == SendSupport.SUPPORTED } + ?: state.sources.first() + if (state.sourceChosenByUser) { + _uiState.update { it.copy(sourceChosenByUser = false) } + } + if (pick == state.source && balanceJob != null) return false + selectSource(pick, byUser = false) + return true + } + + /** Observe the selected source's balance and re-read Max on every balance change. */ + private fun restartBalance() { + balanceJob?.cancel() + val state = _uiState.value + val destinationKind = balanceKindOf(state.destination ?: return) + val source = state.source + val generation = ++balanceGeneration + balanceJob = service.observeBalance(source) + .onEach { balance -> + if (generation == balanceGeneration) _uiState.update { it.copy(balance = balance) } + } + .transformLatest { balance -> + if (balance == null) { + emit(balance to null) + return@transformLatest + } + var max = service.maxSendable(source, destinationKind) + emit(balance to max) + // For a pair whose Max is its bound, an unknown Max blocks Continue, and the + // balance feed is distinct: an unchanged balance never re-reads it. So a failed + // read is retried on the balance poll cadence until it is known. + while (max == null && maxBoundsAmount(source, destinationKind)) { + delay(maxRetryDelayMs) + max = service.maxSendable(source, destinationKind) + if (max != null) emit(balance to max) + } + } + .onEach { (balance, max) -> + if (generation == balanceGeneration) onMaxSendable(balance, max) + } + .launchIn(viewModelScope) + } + + /** + * The selected source's [max] was read for its [balance] (null: the balance is not known yet). + * A pending Max becomes that Max, exactly as [onMaxClick] sets it; a source with a known + * balance but no positive Max drops the pending Max and leaves the amount at zero. + */ + private fun onMaxSendable(balance: Dash?, max: Dash?) { + val before = _uiState.value.maxPending + _uiState.update { + when { + !it.maxPending || balance == null -> it.copy(maxSendable = max) + max != null && max.isPositive -> it.copy( + maxSendable = max, + maxAmount = max, + maxPending = false, + pinnedAmount = null, + amountText = displayTextFor(max, it.dashMode, it.rate) + ) + else -> it.copy(maxSendable = max, maxPending = false, amountText = "0", pinnedAmount = null) + } + } + if (before) saveAmount() + } + + private fun checkIdentity(destination: SendDestination) { + identityJob?.cancel() + ownIdentityJob?.cancel() + if (destination !is SendDestination.Identity) return + val id = destination.identityIdBase58 + identityJob = viewModelScope.launch { + val resolution = service.resolveIdentity(id) + if (_uiState.value.destination == destination) { + _uiState.update { it.copy(identityResolution = resolution) } + } + } + ownIdentityJob = viewModelScope.launch { + val own = service.isOwnIdentity(id) + if (_uiState.value.destination == destination) { + _uiState.update { it.copy(destinationIsOwnIdentity = own) } + autoPickSource() + } + } + } + + // ── Confirm and send ───────────────────────────────────────────────────── + + fun onAmountContinue() { + val state = _uiState.value + if (!state.canContinueAmount) return + val destination = state.destination ?: return + // The SDK wallet is captured here, without suspending: the send is refused unless the + // same wallet is still bound when it runs. + val request = ExternalSendRequest( + state.source, + destination, + state.amount, + state.isMax, + service.currentWalletIdOrNull() + ) + _uiState.update { it.copy(confirm = ExternalSendConfirm(request)) } + feeJob?.cancel() + feeJob = viewModelScope.launch { + val fee = service.estimateFee(request.source, balanceKindOf(request.destination)) + _uiState.update { state -> + val confirm = state.confirm + if (confirm?.request == request) { + state.copy(confirm = confirm.copy(fee = fee, feeLoading = false)) + } else { + state + } + } + } + } + + fun onDismissConfirm() { + feeJob?.cancel() + _uiState.update { it.copy(confirm = null) } + } + + /** + * The request the confirm sheet shows, captured BEFORE authentication so the send is + * exactly what the user confirmed; null when there is nothing to confirm. + */ + fun confirmedRequest(): ExternalSendRequest? { + val state = _uiState.value + return state.confirm?.request?.takeIf { state.canContinueAmount } + } + + /** + * Authenticated: send [request]. Refused unless it is still the request on the confirm + * sheet (the sheet was dismissed or replaced while authenticating). + */ + fun submit(request: ExternalSendRequest): Boolean { + if (_uiState.value.confirm?.request != request) return false + if (!executor.submit(request)) return false + _uiState.update { it.copy(confirm = null) } + return true + } + + /** + * Whether [txId] is still the sent outcome to open in the transaction result screen. The + * caller opens it and then calls [onResultAcknowledged] in the same main-thread turn, which + * clears it, so it is opened once. + */ + fun takeTransactionResult(txId: String): Boolean = _uiState.value.openTransactionResult == txId + + /** + * The user closed the outcome. Not sent → back to editing the amount; every other outcome + * is terminal and the flow ends (the fragment leaves). + */ + fun onResultAcknowledged() { + val status = _uiState.value.status as? ExternalSendStatus.Done ?: return + if (status.result is ExternalSendResult.NotSent) { + executor.acknowledge() + // Max is chosen again deliberately; the amount it was stays exact. + _uiState.update { + it.copy( + maxAmount = null, + maxPending = false, + pinnedAmount = if (it.isMax) it.amount else it.pinnedAmount + ) + } + saveAmount() + } else { + // Set before the executor can reach Idle, so the form never lights up in between. + savedState[KEY_FINISHED] = true + _uiState.update { it.copy(finished = true, showSourceSheet = false, confirm = null) } + executor.acknowledge() + } + } + + /** + * Back inside the flow: closes a sheet, or returns from the amount to the address page. + * Returns false when the screen itself should be left (the send, if any, continues). + */ + fun onBack(): Boolean { + val state = _uiState.value + return when { + state.status is ExternalSendStatus.Sending -> false + // The flow is over: leave, never back to an editable address page. + state.finished -> false + state.confirm != null -> { + onDismissConfirm() + true + } + state.showSourceSheet -> { + onDismissSourceSheet() + true + } + state.step == ExternalSendStep.AMOUNT -> { + _uiState.update { it.copy(step = ExternalSendStep.ADDRESS) } + savedState[KEY_STEP] = ExternalSendStep.ADDRESS.name + true + } + else -> false + } + } + + private fun displayTextFor(amount: Dash, dashMode: Boolean, rate: Fiat?): String = + if (dashMode) amount.toKeypadString() else amount.toFiatAt(rate)?.toKeypadStringTwoDecimals() ?: "0" + + private fun saveAmount() { + val state = _uiState.value + savedState[KEY_AMOUNT] = state.amountText + savedState[KEY_DASH_MODE] = state.dashMode + savedState[KEY_MAX_DUFFS] = state.maxAmount?.duffs + savedState[KEY_MAX_PENDING] = state.maxPending + savedState[KEY_PINNED_DUFFS] = state.pinnedAmount?.duffs + } +} diff --git a/wallet/src/de/schildbach/wallet/ui/transactions/TransactionResultActivity.kt b/wallet/src/de/schildbach/wallet/ui/transactions/TransactionResultActivity.kt index 93f9174de7..e3bbce99d9 100644 --- a/wallet/src/de/schildbach/wallet/ui/transactions/TransactionResultActivity.kt +++ b/wallet/src/de/schildbach/wallet/ui/transactions/TransactionResultActivity.kt @@ -109,6 +109,19 @@ class TransactionResultActivity : LockScreenActivity() { } } + /** + * For a send that reports only its txid (no dashj [Transaction] in hand), e.g. an SDK-built + * asset lock. [txId] is the transaction hash as [Transaction.getTxId] returns it + * (`Sha256Hash.wrap` of the display-order hex). + */ + @JvmStatic + fun createIntent(context: Context, txId: Sha256Hash, userAuthorized: Boolean): Intent { + return Intent(context, TransactionResultActivity::class.java).apply { + putExtra(EXTRA_TX_ID, txId) + putExtra(EXTRA_USER_AUTHORIZED, userAuthorized) + } + } + @JvmStatic fun createIntent(context: Context, action: String?, transaction: Transaction, userAuthorized: Boolean, userData: UsernameSearchResult?): Intent { diff --git a/wallet/test/de/schildbach/wallet/service/platform/IdentityConditionalWriteTest.kt b/wallet/test/de/schildbach/wallet/service/platform/IdentityConditionalWriteTest.kt index a1651ce2c7..f4f4cf8ae2 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/IdentityConditionalWriteTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/IdentityConditionalWriteTest.kt @@ -139,10 +139,12 @@ class IdentityConditionalWriteTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = mockk(relaxed = true), shieldedBalanceService = mockk(relaxed = true), + platformAddressSyncService = mockk(relaxed = true), cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { mockk(relaxed = true) }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { mockk(relaxed = true) } diff --git a/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt b/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt index 2dc0151e5b..4f5d454f0a 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt @@ -88,10 +88,12 @@ class IdentityDiscoveryLatchTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = mockk(relaxed = true), shieldedBalanceService = mockk(relaxed = true), + platformAddressSyncService = mockk(relaxed = true), cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { mockk(relaxed = true) }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { mockk(relaxed = true) } diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt index 1eca5f2588..3620e9d925 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt @@ -114,10 +114,12 @@ class PlatformSyncContactGuardTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = mockk(relaxed = true), shieldedBalanceService = mockk(relaxed = true), + platformAddressSyncService = mockk(relaxed = true), cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { mockk(relaxed = true) }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { mockk(relaxed = true) } diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt index 1d6114b887..b9690bee6c 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt @@ -17,12 +17,16 @@ package de.schildbach.wallet.service.platform import de.schildbach.wallet.service.platform.sdk.L1ShadowSyncService +import de.schildbach.wallet.service.platform.sdk.PlatformAddressSyncService +import de.schildbach.wallet.service.platform.sdk.PlatformAddressSyncSource import de.schildbach.wallet.service.platform.sdk.SdkWalletBinder import de.schildbach.wallet.service.platform.sdk.ShieldedBalanceService import de.schildbach.wallet.service.platform.sdk.WalletUnlock +import de.schildbach.wallet.ui.payments.send.ExternalSendExecutor import io.mockk.coVerify import io.mockk.every import io.mockk.mockk +import io.mockk.verify import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking @@ -65,6 +69,25 @@ class PlatformSyncEngineRestartTest { private val l1ShadowSyncService = mockk(relaxed = true) private val shieldedBalanceService = mockk(relaxed = true) private val identityRepository = mockk(relaxed = true) + private val externalSendExecutor = mockk(relaxed = true) + + /** The real start/stop fencing over a fake SDK seam (ready, not running). */ + private class FakePlatformAddressSource : PlatformAddressSyncSource { + @Volatile var starts = 0 + @Volatile var stops = 0 + override suspend fun ready() = true + override suspend fun isRunning() = false + override suspend fun start() { starts++ } + override suspend fun stop() { stops++ } + } + private val platformAddressSource = FakePlatformAddressSource() + private val platformAddressSyncService = PlatformAddressSyncService(platformAddressSource) + + private suspend fun awaitPlatformAddressStarts(expected: Int) { + val deadline = System.currentTimeMillis() + kickTimeoutMs + while (platformAddressSource.starts < expected && System.currentTimeMillis() < deadline) delay(20) + org.junit.Assert.assertEquals(expected, platformAddressSource.starts) + } /** The engine kick is asynchronous (`syncScope.launch { bindJob.join(); … }`). */ private val kickTimeoutMs = 10_000L @@ -100,10 +123,12 @@ class PlatformSyncEngineRestartTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = l1ShadowSyncService, shieldedBalanceService = shieldedBalanceService, + platformAddressSyncService = platformAddressSyncService, cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { externalSendExecutor }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { mockk(relaxed = true) } @@ -232,4 +257,109 @@ class PlatformSyncEngineRestartTest { coVerify(exactly = 0) { l1ShadowSyncService.startIfEnabled() } Unit } + + /** + * The pending Core → Platform External Send sweep runs at app start, not only when the + * External Send screen opens: every kick (init from WalletApplication, resume from the + * foreground service) starts it once its bind pass has finished — the trigger the pending + * wallet-shield sweep uses. + */ + @Test + fun everyKick_startsThePendingExternalPlatformFundingSweep() = runBlocking { + val service = service() + + service.init() + verify(timeout = kickTimeoutMs, exactly = 1) { externalSendExecutor.resumePendingPlatformFunding() } + + service.resume() + verify(timeout = kickTimeoutMs, exactly = 2) { externalSendExecutor.resumePendingPlatformFunding() } + Unit + } + + /** The sweep needs the bound wallet: nothing starts it before the kick's bind pass ends. */ + @Test + fun pendingExternalPlatformFundingSweep_waitsForTheBindPass() = runBlocking { + val bind = CompletableDeferred() + val binder = mockk(relaxed = true) + every { binder.bindInBackground(any WalletUnlock?>()) } returns bind + val service = service(sdkWalletBinder = binder) + + service.init() + delay(500) + verify(exactly = 0) { externalSendExecutor.resumePendingPlatformFunding() } + + bind.complete(Unit) + verify(timeout = kickTimeoutMs, exactly = 1) { externalSendExecutor.resumePendingPlatformFunding() } + Unit + } + + /** A kick a stop cancelled while it waited on its bind starts no sweep either. */ + @Test + fun stopSdkEngines_cancelsTheSweepOfAKickStillWaitingOnItsBind() = runBlocking { + val bind = CompletableDeferred() + val binder = mockk(relaxed = true) + every { binder.bindInBackground(any WalletUnlock?>()) } returns bind + val service = service(sdkWalletBinder = binder) + + service.resume() + service.stopSdkEngines() + bind.complete(Unit) + delay(500) + + verify(exactly = 0) { externalSendExecutor.resumePendingPlatformFunding() } + Unit + } + + /** A failure to reach the executor is logged; the rest of the kick still runs. */ + @Test + fun aFailingExecutor_doesNotBreakTheKick() = runBlocking { + every { externalSendExecutor.resumePendingPlatformFunding() } throws IllegalStateException("boom") + val binder = mockk(relaxed = true) + val service = service(sdkWalletBinder = binder) + + service.resume() + + // The step the kick runs after the sweep. + verify(timeout = kickTimeoutMs, exactly = 1) { binder.provisionContactAccountsInBackground(force = true) } + Unit + } + + /** + * The Platform-address balance sync shares the L1 engine's lifetime: init() (a possibly + * background process) does not start it, resume() (the foreground service) does, after the + * bind pass, and every service restart starts it again. + */ + @Test + fun platformAddressSync_startsFromResumeOnly_andRestartsAfterAnEngineStop() = runBlocking { + val service = service() + + service.init() + delay(500) + org.junit.Assert.assertEquals(0, platformAddressSource.starts) + + service.resume() + awaitPlatformAddressStarts(1) + + service.stopSdkEngines() + org.junit.Assert.assertEquals(1, platformAddressSource.stops) + + service.resume() + awaitPlatformAddressStarts(2) + } + + /** A stop that lands while the kick waits on its bind leaves the Platform-address loop down. */ + @Test + fun stopSdkEngines_beforeTheBindCompletes_startsNoPlatformAddressSync() = runBlocking { + val bind = CompletableDeferred() + val binder = mockk(relaxed = true) + every { binder.bindInBackground(any WalletUnlock?>()) } returns bind + val service = service(sdkWalletBinder = binder) + + service.resume() + service.stopSdkEngines() + bind.complete(Unit) + delay(500) + + org.junit.Assert.assertEquals(0, platformAddressSource.starts) + } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt index 1b0ae24854..7ceb966e7b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt @@ -17,6 +17,7 @@ package de.schildbach.wallet.service.platform import de.schildbach.wallet.service.platform.sdk.L1ShadowSyncService +import de.schildbach.wallet.service.platform.sdk.PlatformAddressSyncService import de.schildbach.wallet.service.platform.sdk.ShieldedBalanceService import io.mockk.coEvery import io.mockk.coVerify @@ -44,6 +45,7 @@ class PlatformSyncEngineTeardownTest { private val l1ShadowSyncService = mockk(relaxed = true) private val shieldedBalanceService = mockk(relaxed = true) + private val platformAddressSyncService = mockk(relaxed = true) private val identityRepository = mockk(relaxed = true) private fun service() = PlatformSynchronizationService( @@ -75,10 +77,12 @@ class PlatformSyncEngineTeardownTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = l1ShadowSyncService, shieldedBalanceService = shieldedBalanceService, + platformAddressSyncService = platformAddressSyncService, cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { mockk(relaxed = true) }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { mockk(relaxed = true) } @@ -92,6 +96,7 @@ class PlatformSyncEngineTeardownTest { coVerify(exactly = 1) { l1ShadowSyncService.stop() } coVerify(exactly = 1) { shieldedBalanceService.stop() } + coVerify(exactly = 1) { platformAddressSyncService.stop() } } @Test @@ -100,6 +105,7 @@ class PlatformSyncEngineTeardownTest { coVerify(exactly = 1) { l1ShadowSyncService.stop() } coVerify(exactly = 1) { shieldedBalanceService.stop() } + coVerify(exactly = 1) { platformAddressSyncService.stop() } } @Test @@ -111,4 +117,14 @@ class PlatformSyncEngineTeardownTest { coVerify(exactly = 1) { shieldedBalanceService.stop() } } + + @Test + fun stopSdkEngines_failingEngineStopsStillStopThePlatformAddressSync() = runBlocking { + coEvery { l1ShadowSyncService.stop() } throws RuntimeException("rust client stop failed") + coEvery { shieldedBalanceService.stop() } throws RuntimeException("shielded stop failed") + + service().stopSdkEngines() + + coVerify(exactly = 1) { platformAddressSyncService.stop() } + } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt index 43a732b7ef..89ef89ad7e 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt @@ -148,10 +148,12 @@ class PlatformSyncIntegrityPassTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = mockk(relaxed = true), shieldedBalanceService = mockk(relaxed = true), + platformAddressSyncService = mockk(relaxed = true), cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { mockk(relaxed = true) }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { mockk(relaxed = true) } diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt index 9d6d47df0e..24fc828080 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt @@ -133,10 +133,12 @@ class PlatformUsernameReconcileTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = mockk(relaxed = true), shieldedBalanceService = mockk(relaxed = true), + platformAddressSyncService = mockk(relaxed = true), cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { mockk(relaxed = true) }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus(), transparentUsernameCreation = javax.inject.Provider { transparentUsernameCreation } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolverWalletScopeTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolverWalletScopeTest.kt index 27facd642b..74b090d30b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolverWalletScopeTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolverWalletScopeTest.kt @@ -118,6 +118,53 @@ class AssetLockKindResolverWalletScopeTest { assertArrayEquals(walletIdFromHex(walletIdHex), binds[1] as ByteArray) } + @Test + fun platformAddressFundingType_resolvesToPlatformWithoutTheAccountProbe() = runTest { + // `AssetLockFundingType::AssetLockAddressTopUp` — the Core → Platform-address send. + every { db.assetLockDao() } returns mockk { + coEvery { fundingTypeForTxid(hex) } returns ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP + } + every { sdkService.loadedWalletIds() } returns setOf(walletIdHex) + + assertEquals(AssetLockKind.PLATFORM, resolver().kindFor(hex)) + // The durable funding type answered: no credit-account fallback ran. + verify(exactly = 0) { readable.query(any()) } + } + + @Test + fun seededPlatformKind_winsBeforeTheSdkRowLands() = runTest { + every { sdkService.loadedWalletIds() } returns setOf(walletIdHex) + val resolver = resolver() + resolver.seed(hex.uppercase(), AssetLockKind.PLATFORM) + + assertEquals(AssetLockKind.PLATFORM, resolver.kindFor(hex)) + coVerify(exactly = 0) { transactionDao.transactionKindForDisplayTxid(any()) } + } + + @Test + fun seededExternalShieldKind_winsBeforeTheSdkRowLands() = runTest { + // Core → third-party Shielded send: only the authoring path knows the recipient + // was external, so the in-memory seed is what makes the row read as a send. + every { sdkService.loadedWalletIds() } returns setOf(walletIdHex) + val resolver = resolver() + resolver.seed(hex, AssetLockKind.SHIELD_EXTERNAL) + + assertEquals(AssetLockKind.SHIELD_EXTERNAL, resolver.kindFor(hex)) + coVerify(exactly = 0) { transactionDao.transactionKindForDisplayTxid(any()) } + } + + @Test + fun shieldFundingType_withoutASeed_resolvesToTheOwnShield() = runTest { + // The documented limit: funding type 5 cannot tell own from third-party, so + // after a restart (no seed) an external shield reads SHIELD again. + every { db.assetLockDao() } returns mockk { + coEvery { fundingTypeForTxid(hex) } returns 5 + } + every { sdkService.loadedWalletIds() } returns setOf(walletIdHex) + + assertEquals(AssetLockKind.SHIELD, resolver().kindFor(hex)) + } + @Test fun noLoadedWallet_failsClosedAndIsNotNegativeCached() = runTest { every { sdkService.loadedWalletIds() } returns emptySet() diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt index 792f598d72..333fbbd55b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt @@ -231,15 +231,15 @@ class CutoverUiDataServiceTest { @Test fun rowPlan_externalUnshieldKeepsReceiveSemantics() { - // An AssetUnlock this wallet's pool did not author (a foreign pool's - // unshield, or a Platform identity credit withdrawal) is a genuine - // receive: "Unshielded Withdrawal", the green inbound arrow, Received + // An AssetUnlock this wallet's pool did not author (a Platform address + // or identity credit withdrawal, or a foreign pool's unshield) is a + // genuine receive: "Withdrawal", the green inbound arrow, Received // treatment and the coins-received notification. val plan = planL1TxRow( record(net = 300_000, context = 1, direction = 0), AssetLockKind.UNSHIELD_EXTERNAL ) - assertEquals(R.string.transaction_row_unshielded_withdrawal, plan.titleRes) + assertEquals(R.string.transaction_row_withdrawal, plan.titleRes) assertEquals(TxDisplayCacheEntry.ICON_RECEIVED, plan.iconType) assertEquals(TxDisplayCacheEntry.BG_RECEIVED, plan.iconBgType) assertEquals(TxDisplayCacheEntry.FLAG_RECEIVED, plan.filterFlags) @@ -270,7 +270,9 @@ class CutoverUiDataServiceTest { val expected = mapOf( AssetLockKind.UPGRADE to R.string.dashpay_upgrade_fee, AssetLockKind.TOPUP to R.string.dashpay_topup_fee, - AssetLockKind.INVITE to R.string.transaction_row_invitation + AssetLockKind.INVITE to R.string.transaction_row_invitation, + AssetLockKind.PLATFORM to R.string.transaction_row_platform, + AssetLockKind.SHIELD_EXTERNAL to R.string.transaction_row_shielded ) for ((kind, title) in expected) { val plan = planL1TxRow(outgoingAssetLock(), kind) @@ -329,6 +331,88 @@ class CutoverUiDataServiceTest { assertTrue(plan.notifyIncoming.isEmpty()) } + @Test + fun platformAddressSend_isASendNotAPoolTransfer() { + // A Core → Platform-address External Send (funding type 4): a payment to a + // third party, so it applies to the OUTGOING row and keeps the sent arrow. + assertTrue(AssetLockKind.PLATFORM.appliesToOutgoing) + assertFalse(AssetLockKind.PLATFORM.isPoolTransfer) + assertEquals(R.string.transaction_row_platform, assetLockTitleRes(AssetLockKind.PLATFORM)) + } + + @Test + fun externalShieldSend_isASendNotAPoolTransfer() { + // A Core → third-party Shielded External Send: a payment, so the sent arrow, + // titled "Shielded" like the own shield; the own shield keeps the transfer look. + assertTrue(AssetLockKind.SHIELD_EXTERNAL.appliesToOutgoing) + assertFalse(AssetLockKind.SHIELD_EXTERNAL.isPoolTransfer) + assertTrue(AssetLockKind.SHIELD.isPoolTransfer) + assertEquals(R.string.transaction_row_shielded, assetLockTitleRes(AssetLockKind.SHIELD_EXTERNAL)) + } + + @Test + fun rowPlan_internalExternalShieldLock_isASendTitledShielded() { + val plan = planL1TxRow(record(net = -300_000, context = 1, direction = 2), AssetLockKind.SHIELD_EXTERNAL) + assertEquals(R.string.transaction_row_shielded, plan.titleRes) + assertEquals(TxDisplayCacheEntry.ICON_SENT, plan.iconType) + assertEquals(TxDisplayCacheEntry.BG_SENT, plan.iconBgType) + assertEquals(TxDisplayCacheEntry.FLAG_SENT, plan.filterFlags) + assertFalse(plan.isIncoming) + // The own-pool shield in the same shape keeps the double-arrows transfer icon. + val own = planL1TxRow(record(net = -300_000, context = 1, direction = 2), AssetLockKind.SHIELD) + assertEquals(TxDisplayCacheEntry.ICON_INTERNAL, own.iconType) + } + + @Test + fun syncPlan_externalShieldCachedAsInternal_isRelabelledAsAShieldedSend() { + val r = outgoingAssetLock(firstByte = 0x54) + val existing = cacheEntry( + rowId = r.txidHex, + title = resolve(R.string.transaction_row_status_sent_internally) + ) + val plan = planL1DisplaySync( + listOf(r), mapOf(existing.rowId to existing), emptySet(), resolve, now, + kindByTxid = mapOf(r.txidHex to AssetLockKind.SHIELD_EXTERNAL) + ) + val row = plan.updates.single() + assertEquals(resolve(R.string.transaction_row_shielded), row.title) + assertEquals(-3_000_000L, row.valueSatoshis) + assertEquals(TxDisplayCacheEntry.ICON_SENT, row.iconType) + assertEquals(TxDisplayCacheEntry.FLAG_SENT, row.filterFlags) + assertTrue(plan.notifyIncoming.isEmpty()) + } + + @Test + fun rowPlan_internalPlatformAddressLock_isASendTitledPlatform() { + // Before the store walker corrects it to OUTGOING, the lock can be recorded INTERNAL: + // it must not keep the "Internal" double-arrows treatment either. + val plan = planL1TxRow(record(net = -300_000, context = 1, direction = 2), AssetLockKind.PLATFORM) + assertEquals(R.string.transaction_row_platform, plan.titleRes) + assertEquals(TxDisplayCacheEntry.ICON_SENT, plan.iconType) + assertEquals(TxDisplayCacheEntry.BG_SENT, plan.iconBgType) + assertEquals(TxDisplayCacheEntry.FLAG_SENT, plan.filterFlags) + assertFalse(plan.isIncoming) + } + + @Test + fun syncPlan_platformAddressSendCachedAsInternal_isRelabelledAsPlatformSend() { + val r = outgoingAssetLock(firstByte = 0x53) + val existing = cacheEntry( + rowId = r.txidHex, + title = resolve(R.string.transaction_row_status_sent_internally) + ) + val plan = planL1DisplaySync( + listOf(r), mapOf(existing.rowId to existing), emptySet(), resolve, now, + kindByTxid = mapOf(r.txidHex to AssetLockKind.PLATFORM) + ) + val row = plan.updates.single() + assertEquals(resolve(R.string.transaction_row_platform), row.title) + assertEquals(-3_000_000L, row.valueSatoshis) + assertEquals(TxDisplayCacheEntry.ICON_SENT, row.iconType) + assertEquals(TxDisplayCacheEntry.FLAG_SENT, row.filterFlags) + assertTrue(plan.notifyIncoming.isEmpty()) + } + @Test fun syncPlan_outgoingAssetLockCachedAsSent_isRelabelledOnce() { val r = outgoingAssetLock(firstByte = 0x52) @@ -509,7 +593,7 @@ class CutoverUiDataServiceTest { mapOf(cached.rowId to cached), emptySet(), resolve, now, kindByTxid = mapOf(displayHex(7) to AssetLockKind.UNSHIELD_EXTERNAL) ) - assertEquals(resolve(R.string.transaction_row_unshielded_withdrawal), plan.updates.single().title) + assertEquals(resolve(R.string.transaction_row_withdrawal), plan.updates.single().title) } @Test @@ -920,7 +1004,7 @@ class CutoverUiDataServiceTest { val richTitles = listOf( R.string.transaction_row_shielded, R.string.transaction_row_unshielded, - R.string.transaction_row_unshielded_withdrawal, + R.string.transaction_row_withdrawal, R.string.transaction_row_invitation, R.string.dashpay_upgrade_fee, R.string.dashpay_topup_fee, diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt new file mode 100644 index 0000000000..2360e66515 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -0,0 +1,491 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform.sdk + +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.Base58 +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ExternalSendModelsTest { + + private val main = AddressNetwork.DASH_MAINNET + private val test = AddressNetwork.DASH_TESTNET + private val hash20 = ByteArray(20) { (it + 1).toByte() } + private val raw43 = ByteArray(43) { (it * 3 + 7).toByte() } + private val id32 = ByteArray(32) { (255 - it).toByte() } + + private val coreMainP2pkh = Base58.encodeChecked(main.addressHeader, hash20) + private val coreMainP2sh = Base58.encodeChecked(main.p2shHeader, hash20) + private val coreTestP2pkh = Base58.encodeChecked(test.addressHeader, hash20) + private val coreTestP2sh = Base58.encodeChecked(test.p2shHeader, hash20) + + private fun bech(hrp: String, type: Int, payload: ByteArray): String = + requireNotNull(Bech32m.encode(hrp, byteArrayOf(type.toByte()) + payload)) + + private val platformMainP2pkh = bech("dash", 0xb0, hash20) + private val platformMainP2sh = bech("dash", 0x80, hash20) + private val platformTestP2pkh = bech("tdash", 0xb0, hash20) + private val platformTestP2sh = bech("tdash", 0x80, hash20) + private val shieldedMain = bech("dash", 0x10, raw43) + private val shieldedTest = bech("tdash", 0x10, raw43) + private val identityId = Base58.encode(id32) + + private fun valid(input: String, network: AddressNetwork): SendDestination { + val parsed = detectSendDestination(input, network) + assertTrue("expected Valid, got $parsed", parsed is DestinationParse.Valid) + return (parsed as DestinationParse.Valid).destination + } + + // ── Core ────────────────────────────────────────────────────────── + + @Test + fun core_bothTypesBothNetworks_areValid() { + assertEquals(coreMainP2pkh.first(), 'X') + assertEquals(coreMainP2sh.first(), '7') + assertEquals(coreTestP2pkh.first(), 'y') + assertEquals(coreTestP2sh.first(), '8') + assertEquals(SendDestination.Core(coreMainP2pkh), valid(coreMainP2pkh, main)) + assertEquals(SendDestination.Core(coreMainP2sh), valid(coreMainP2sh, main)) + assertEquals(SendDestination.Core(coreTestP2pkh), valid(coreTestP2pkh, test)) + assertEquals(SendDestination.Core(coreTestP2sh), valid(coreTestP2sh, test)) + // Devnets share testnet's address space. + assertEquals(SendDestination.Core(coreTestP2pkh), valid(coreTestP2pkh, AddressNetwork.DASH_DEVNET)) + } + + @Test + fun core_otherNetwork_isWrongNetwork() { + assertEquals(DestinationParse.WrongNetwork, detectSendDestination(coreTestP2pkh, main)) + assertEquals(DestinationParse.WrongNetwork, detectSendDestination(coreMainP2sh, test)) + } + + @Test + fun core_badChecksum_isInvalid() { + val last = coreMainP2pkh.last() + val tampered = coreMainP2pkh.dropLast(1) + (if (last == 'a') 'b' else 'a') + assertEquals(DestinationParse.Invalid, detectSendDestination(tampered, main)) + } + + @Test + fun core_bitcoinAddress_isInvalidNotWrongNetwork() { + // A version byte of no Dash network (Bitcoin P2PKH = 0). + val btc = Base58.encodeChecked(0, hash20) + assertEquals(DestinationParse.Invalid, detectSendDestination(btc, main)) + } + + // ── Platform / Shielded ─────────────────────────────────────────── + + @Test + fun platform_bothTypesBothNetworks_areValid() { + assertTrue(platformMainP2pkh.startsWith("dash1k")) + assertTrue(platformMainP2sh.startsWith("dash1s")) + assertTrue(platformTestP2pkh.startsWith("tdash1k")) + assertTrue(platformTestP2sh.startsWith("tdash1s")) + assertEquals(SendDestination.Platform(platformMainP2pkh), valid(platformMainP2pkh, main)) + assertEquals(SendDestination.Platform(platformMainP2sh), valid(platformMainP2sh, main)) + assertEquals(SendDestination.Platform(platformTestP2pkh), valid(platformTestP2pkh, test)) + assertEquals(SendDestination.Platform(platformTestP2sh), valid(platformTestP2sh, test)) + } + + @Test + fun shielded_bothNetworks_areValid() { + assertTrue(shieldedMain.startsWith("dash1z")) + assertTrue(shieldedTest.startsWith("tdash1z")) + assertEquals(SendDestination.Shielded(shieldedMain), valid(shieldedMain, main)) + assertEquals(SendDestination.Shielded(shieldedTest), valid(shieldedTest, test)) + } + + @Test + fun bech32m_otherNetwork_isWrongNetwork() { + assertEquals(DestinationParse.WrongNetwork, detectSendDestination(platformTestP2pkh, main)) + assertEquals(DestinationParse.WrongNetwork, detectSendDestination(platformMainP2sh, test)) + assertEquals(DestinationParse.WrongNetwork, detectSendDestination(shieldedTest, main)) + assertEquals(DestinationParse.WrongNetwork, detectSendDestination(shieldedMain, test)) + } + + @Test + fun bech32m_badChecksum_isInvalid() { + for (address in listOf(platformMainP2pkh, shieldedMain)) { + val last = address.last() + val tampered = address.dropLast(1) + (if (last == 'q') 'p' else 'q') + assertEquals(DestinationParse.Invalid, detectSendDestination(tampered, main)) + } + } + + @Test + fun bech32m_mixedCase_isInvalid_upperCase_isValidAndLowercased() { + val mixed = platformMainP2pkh.substring(0, 6).uppercase() + platformMainP2pkh.substring(6) + assertEquals(DestinationParse.Invalid, detectSendDestination(mixed, main)) + assertEquals(SendDestination.Platform(platformMainP2pkh), valid(platformMainP2pkh.uppercase(), main)) + assertEquals(SendDestination.Shielded(shieldedMain), valid(shieldedMain.uppercase(), main)) + } + + @Test + fun sharedDash1Prefix_isToldApartByTypeByteAndLength() { + // Platform type byte with an Orchard-length payload, and the Orchard byte with a + // Platform-length payload, are neither. + assertEquals(DestinationParse.Invalid, detectSendDestination(bech("dash", 0xb0, raw43), main)) + assertEquals(DestinationParse.Invalid, detectSendDestination(bech("dash", 0x10, hash20), main)) + // Unknown type byte. + assertEquals(DestinationParse.Invalid, detectSendDestination(bech("dash", 0x00, hash20), main)) + // Another HRP. + assertEquals(DestinationParse.Invalid, detectSendDestination(bech("bc", 0xb0, hash20), main)) + } + + @Test + fun decodePlatformAddress_mapsTypeBytesToStorageTypes() { + val p2pkh = requireNotNull(decodePlatformAddress(platformMainP2pkh, main)) + assertEquals(0, p2pkh.addressType) + assertArrayEquals(hash20, p2pkh.hash) + assertEquals(1, requireNotNull(decodePlatformAddress(platformTestP2sh, test)).addressType) + assertNull(decodePlatformAddress(platformTestP2sh, main)) + } + + // ── Identity ────────────────────────────────────────────────────── + + @Test + fun identity_32Bytes_isValidOnBothNetworks() { + assertEquals(SendDestination.Identity(identityId), valid(identityId, main)) + assertEquals(SendDestination.Identity(identityId), valid(identityId, test)) + } + + @Test + fun identity_wrongLength_isInvalid() { + assertEquals(DestinationParse.Invalid, detectSendDestination(Base58.encode(ByteArray(31) { 9 }), main)) + assertEquals(DestinationParse.Invalid, detectSendDestination(Base58.encode(ByteArray(33) { 9 }), main)) + assertEquals(DestinationParse.Invalid, detectSendDestination("not-base58-0OIl", main)) + } + + // ── Whitespace / empty ──────────────────────────────────────────── + + @Test + fun whitespace_isTrimmed_blankIsEmpty() { + assertEquals(DestinationParse.Empty, detectSendDestination("", main)) + assertEquals(DestinationParse.Empty, detectSendDestination(" \n\t", main)) + assertEquals(SendDestination.Core(coreMainP2pkh), valid(" $coreMainP2pkh\n", main)) + assertEquals(SendDestination.Platform(platformMainP2pkh), valid("\t$platformMainP2pkh ", main)) + assertEquals(SendDestination.Identity(identityId), valid(" $identityId ", main)) + } + + // ── dash: URI ───────────────────────────────────────────────────── + + @Test + fun dashUri_withAmount_isCoreWithAmount() { + val parsed = detectSendDestination("dash:$coreTestP2pkh?amount=0.25", test) + assertEquals(DestinationParse.Valid(SendDestination.Core(coreTestP2pkh), Dash(25_000_000L)), parsed) + } + + @Test + fun dashUri_withoutAmount_isCore() { + assertEquals( + DestinationParse.Valid(SendDestination.Core(coreMainP2pkh), null), + detectSendDestination("dash:$coreMainP2pkh", main) + ) + } + + @Test + fun dashUri_wrongNetwork_bip70_andGarbage() { + assertEquals(DestinationParse.WrongNetwork, detectSendDestination("dash:$coreTestP2pkh", main)) + assertEquals( + DestinationParse.Invalid, + detectSendDestination("dash:$coreMainP2pkh?r=https%3A%2F%2Fexample.com%2Fi", main) + ) + assertEquals(DestinationParse.Invalid, detectSendDestination("dash:notanaddress", main)) + } + + @Test + fun destinations_toString_isRedacted() { + for (d in listOf( + SendDestination.Core(coreMainP2pkh), + SendDestination.Platform(platformMainP2pkh), + SendDestination.Shielded(shieldedMain), + SendDestination.Identity(identityId) + )) { + assertFalse(d.toString().contains(d.display)) + } + } + + // ── Support matrix ──────────────────────────────────────────────── + + private val core = SendDestination.Core(coreMainP2pkh) + private val shielded = SendDestination.Shielded(shieldedMain) + private val platform = SendDestination.Platform(platformMainP2pkh) + private val identity = SendDestination.Identity(identityId) + + private fun support(source: SendBalance, dest: SendDestination, own: Boolean? = false, hasIdentity: Boolean = true) = + externalSendSupport(source, dest, hasIdentity, own) + + @Test + fun matrix_core() { + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, core)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, shielded)) + // fundFromAssetLockExternal: P2PKH only (either network's HRP; the network is checked by the parser). + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, platform)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, SendDestination.Platform(platformTestP2pkh))) + assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.CORE, SendDestination.Platform(platformMainP2sh))) + assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.CORE, SendDestination.Platform(platformTestP2sh))) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, platform, hasIdentity = false)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, identity, own = true)) + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.CORE, identity, own = false)) + // Could not tell: fail closed. + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.CORE, identity, own = null)) + // The Core source does not need an identity. + assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, core, hasIdentity = false)) + } + + @Test + fun matrix_shielded() { + for (dest in listOf(core, shielded, platform, identity)) { + assertEquals(SendSupport.SUPPORTED, support(SendBalance.SHIELDED, dest)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.SHIELDED, dest, own = null, hasIdentity = false)) + } + } + + @Test + fun matrix_platform() { + // int37: the partial-amount withdrawal and the Type 15 shield to a recipient. + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, core)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, shielded)) + // A P2SH Platform destination is a plain transfer output. + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, SendDestination.Platform(platformMainP2sh))) + // The Platform source needs no identity. + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, core, hasIdentity = false)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, platform)) + // Any identity: topUpFromAddresses for a managed one, the external top-up + // (platform#5860) for anyone else's; the send picks the call (and refuses when it + // cannot tell), so the matrix does not depend on ownership. + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity, own = true)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity, own = false)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity, own = null)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity, hasIdentity = false)) + } + + @Test + fun maxBoundsAmount_onlyForThePlatformPairsWithAFeeReserve() { + for (source in SendBalance.entries) { + for (destination in SendBalance.entries) { + val expected = source == SendBalance.PLATFORM && + (destination == SendBalance.CORE || destination == SendBalance.IDENTITY) + assertEquals("$source → $destination", expected, maxBoundsAmount(source, destination)) + } + } + } + + @Test + fun matrix_identity() { + assertEquals(SendSupport.SUPPORTED, support(SendBalance.IDENTITY, core)) + // int37: the Type 21 shield to a recipient. + assertEquals(SendSupport.SUPPORTED, support(SendBalance.IDENTITY, shielded)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.IDENTITY, platform)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.IDENTITY, identity, own = false)) + // To itself: moves nothing. + assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.IDENTITY, identity, own = true)) + for (dest in listOf(core, shielded, platform, identity)) { + assertEquals(SendSupport.NO_IDENTITY, support(SendBalance.IDENTITY, dest, hasIdentity = false)) + } + } + + // ── Review round 1 regressions ──────────────────────────────────── + + @Test + fun dashUri_ofAShieldedPlatformOrIdentityDestination_isThatDestination_withItsAmount() { + val cases = listOf( + shieldedTest to SendDestination.Shielded(shieldedTest), + platformTestP2pkh to SendDestination.Platform(platformTestP2pkh), + platformTestP2sh to SendDestination.Platform(platformTestP2sh), + identityId to SendDestination.Identity(identityId) + ) + for ((address, destination) in cases) { + assertEquals( + DestinationParse.Valid(destination, Dash(12_345_678L)), + detectSendDestination("dash:$address?amount=0.12345678", test) + ) + assertEquals(DestinationParse.Valid(destination, null), detectSendDestination("dash:$address", test)) + // Optional parameters are ignored; a zero amount is no amount. + assertEquals( + DestinationParse.Valid(destination, null), + detectSendDestination("dash:$address?label=x&amount=0", test) + ) + } + assertEquals( + DestinationParse.Valid(SendDestination.Shielded(shieldedTest), Dash(100_000_000L)), + detectSendDestination("DASH:${shieldedTest.uppercase()}?amount=1", test) + ) + } + + @Test + fun dashUri_ofANonCoreDestination_isReadStrictly() { + for (query in listOf( + "amount=1&amount=2", + "amount=-1", + "amount=1.123456789", + "amount=1e3", + "amount=abc", + "amount=", + "amount=99999999", + "r=https%3A%2F%2Fexample.com%2Fi", + "req-foo=1" + )) { + assertEquals(query, DestinationParse.Invalid, detectSendDestination("dash:$shieldedTest?$query", test)) + } + assertEquals(DestinationParse.WrongNetwork, detectSendDestination("dash:$shieldedMain?amount=1", test)) + assertEquals(DestinationParse.Invalid, detectSendDestination("dash:tdash1notanaddress?amount=1", test)) + } + + @Test + fun dashUri_roundTripsAdvancedReceivesAmountRequests() { + val amount = org.dash.wallet.common.money.Coin.valueOf(123_456_789L) + for (address in listOf(shieldedTest, platformTestP2pkh, identityId, coreTestP2pkh)) { + val payload = de.schildbach.wallet.ui.payments.ReceiveViewModel.amountRequestPayload(address, amount) + val parsed = detectSendDestination(payload, test) + assertTrue("$parsed", parsed is DestinationParse.Valid) + parsed as DestinationParse.Valid + assertEquals(address, parsed.destination.display) + assertEquals(Dash(123_456_789L), parsed.amount) + } + } + + @Test + fun anEmptyBase58CheckPayload_isInvalid_neverACrash() { + // "3QJmnh" is the Base58Check encoding of zero bytes: a valid checksum, no version byte. + for (input in listOf("3QJmnh", "dash:3QJmnh", "dash:3QJmnh?amount=1")) { + assertEquals(input, DestinationParse.Invalid, detectSendDestination(input, test)) + } + } + + @Test + fun detectSendDestination_neverThrows() { + val random = java.util.Random(7) + val alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0OIl:?&=-.%+ tdash1z" + repeat(5_000) { + val input = buildString { repeat(random.nextInt(60)) { append(alphabet[random.nextInt(alphabet.length)]) } } + detectSendDestination(input, test) + detectSendDestination("dash:$input", test) + } + } + + // ── Core → Platform record and arithmetic ───────────────────────── + + private val outPoint = "ab".repeat(32) + ":0" + + private fun record(outPointHex: String? = outPoint) = PendingPlatformFunding( + id = "a7c1e3d2-0000-4000-8000-000000000001", + walletIdHex = "cd".repeat(32), + lockDuffs = 162_000L, + destination = PlatformAddressBytes(0, hash20), + explicitCredits = 100_000_000L, + remainder = PlatformAddressBytes(0, ByteArray(20) { 9 }), + outPointHex = outPointHex + ) + + @Test + fun pendingPlatformFunding_roundTrips_withAndWithoutAnOutPoint() { + for (original in listOf(record(), record(outPointHex = null))) { + val decoded = PendingPlatformFunding.decode(original.encode()) + assertTrue(decoded.sameAs(original)) + } + assertTrue(record(null).withOutPoint(outPoint).sameAs(record())) + assertFalse(record(null).sameAs(record())) + } + + @Test + fun pendingPlatformFunding_completionUnconfirmed_roundTrips_andOldRecordsDecodeUnmarked() { + // An unmarked record keeps the original ten-field form earlier builds wrote. + val unmarked = record().encode() + assertEquals(10, unmarked.split('|').size) + assertFalse(PendingPlatformFunding.decode(unmarked).completionUnconfirmed) + + val marked = record().asCompletionUnconfirmed() + val decoded = PendingPlatformFunding.decode(marked.encode()) + assertTrue(decoded.completionUnconfirmed) + assertTrue(decoded.sameAs(marked)) + assertFalse(decoded.sameAs(record())) + assertFalse(record().toString().contains("completionUnconfirmed=true")) + + // Only a built lock can be marked; any other eleventh field is malformed. + try { + record(null).asCompletionUnconfirmed() + throw AssertionError("marked a record without a lock") + } catch (e: IllegalArgumentException) { + // expected + } + for (text in listOf(unmarked + "|x", unmarked + "|", record(null).encode() + "|u")) { + try { + PendingPlatformFunding.decode(text) + throw AssertionError("decoded a malformed record") + } catch (e: IllegalStateException) { + // expected + } + } + } + + @Test + fun pendingPlatformFunding_malformed_isAnError_neverAbsent() { + val good = record().encode() + val malformed = listOf( + "", + "2" + good.substring(1), + good.replace("|162000|", "|-1|"), + good.replace("|162000|", "|x|"), + good + "|extra", + good.replace(":0", ":"), + good.substringBeforeLast('|') + "|" + "ab".repeat(31) + ":0", + // A P2SH recipient can never be persisted. + good.replaceFirst("|0|", "|1|") + ) + for (text in malformed) { + try { + PendingPlatformFunding.decode(text) + throw AssertionError("decoded a malformed record") + } catch (e: IllegalStateException) { + // expected + } + } + } + + @Test + fun pendingPlatformFunding_refusesARemainderThatIsThePayee_andRedactsItself() { + try { + PendingPlatformFunding("id", "cd".repeat(32), 1L, PlatformAddressBytes(0, hash20), 1L, PlatformAddressBytes(0, hash20), null) + throw AssertionError("accepted the payee as the remainder") + } catch (e: IllegalArgumentException) { + // expected + } + val text = record().toString() + assertFalse(text.contains("162000")) + assertFalse(text.contains("cdcd")) + assertFalse(text.contains("abab")) + } + + @Test + fun coreToPlatform_arithmetic() { + assertEquals(62_000L, PLATFORM_FUNDING_FEE_MARGIN_DUFFS) + assertEquals(162_000L, platformFundingLockDuffs(100_000L)) + // The L1 reserve ((n * 148 + 300) * 2, at least 1000 duffs) plus the margin. + assertEquals(1_000L + 62_000L, coreToPlatformFeeDuffs(1)) + assertEquals(1_192L + 62_000L, coreToPlatformFeeDuffs(2)) + assertEquals(1L, coreToPlatformMaxDuffs(63_193L, 2)) + assertNull(coreToPlatformMaxDuffs(63_192L, 2)) + assertNull(coreToPlatformMaxDuffs(0L, 2)) + } +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt new file mode 100644 index 0000000000..f8cddbbfc2 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -0,0 +1,2248 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.service.platform.sdk + +import de.schildbach.wallet.payments.FundingSelectionLock +import de.schildbach.wallet.payments.SendEngineNotSyncedException +import de.schildbach.wallet.ui.shielded.assetLockMaxFeeReserve +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.yield +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.Base58 +import org.dash.wallet.common.services.PaymentSubmissionPendingException +import org.dash.wallet.common.services.WalletSession +import org.dash.wallet.common.util.retryReadErrors +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.credits.FundingInput +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ExternalSendServiceImplTest { + + private val walletA = "ab".repeat(32) + private val walletB = "cd".repeat(32) + private val hash20 = ByteArray(20) { (it + 1).toByte() } + private val ownId = ByteArray(32) { 3 } + private val otherId = ByteArray(32) { 9 } + private val ownIdBase58 = Base58.encode(ownId) + private val otherIdBase58 = Base58.encode(otherId) + + private val core = SendDestination.Core(Base58.encodeChecked(AddressNetwork.DASH_TESTNET.addressHeader, hash20)) + private val shielded = SendDestination.Shielded( + requireNotNull(Bech32m.encode("tdash", byteArrayOf(0x10) + ByteArray(43) { 5 })) + ) + private val platform = SendDestination.Platform( + requireNotNull(Bech32m.encode("tdash", byteArrayOf(0xb0.toByte()) + hash20)) + ) + private val platformP2sh = SendDestination.Platform( + requireNotNull(Bech32m.encode("tdash", byteArrayOf(0x80.toByte()) + hash20)) + ) + private val ownIdentity = SendDestination.Identity(ownIdBase58) + private val otherIdentity = SendDestination.Identity(otherIdBase58) + + /** 0.001 DASH = 100_000 duffs = 100_000_000 credits. */ + private val amount = Dash(100_000L) + private val amountCredits = 100_000_000L + + private class FakeSource( + var bound: MutableList, + var ownIdentity: String?, + var managed: List + ) : ExternalSendSource { + val calls = mutableListOf() + var cutover: () -> Boolean = { true } + var shieldedOn: () -> Boolean = { true } + var coreMax: Long? = 5_000_000L + var coreEligible: Long? = 5_000_000L + var utxoCount: Int? = 2 + var shieldedBalance: Dash? = Dash(1_000_000L) + var platformBalances: () -> List = { emptyList() } + var shieldedResult: (Dash) -> SdkWriteResult = { SdkWriteResult.Broadcast(Unit) } + var shieldFromCoreResult: (Dash) -> SdkWriteResult = + { SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.COMPLETED, SHIELD_LOCK_TXID)) } + var coreTopUpResult: () -> SdkWriteResult = + { SdkWriteResult.Broadcast(TopUpOutcome(1L, TOP_UP_LOCK_TXID)) } + var coreSend: () -> String = { "txid" } + var nativeWrite: suspend () -> Unit = {} + val shieldedAmounts = mutableListOf() + var lastCoreEmptyWallet: Boolean? = null + var lastSession: WalletSession? = null + var lastCredits: Long? = null + var lastPlatformTo: PlatformAddressBytes? = null + var lastInputs: List? = null + var lastToId: ByteArray? = null + var lastFromId: ByteArray? = null + var lastDuffs: Long? = null + val session = WalletSession(Any()) + + private fun nextBound(): String? = if (bound.size > 1) bound.removeAt(0) else bound.firstOrNull() + + override fun currentCoreSession(): WalletSession? = session + override suspend fun boundWalletIdOrNull(): String? = nextBound() + override fun currentBoundWalletIdOrNull(): String? = bound.firstOrNull() + override suspend fun cutoverCommittedOrThrow(): Boolean = cutover() + override suspend fun shieldedEnabledOrThrow(): Boolean = shieldedOn() + override suspend fun ownIdentityIdOrThrow(): String? = ownIdentity + var identityFlow: Flow>? = null + override fun observeOwnIdentityId(): Flow> = identityFlow ?: flowOf(Result.success(ownIdentity)) + var managedRead: () -> List = { managed } + override suspend fun managedIdentityIds(walletIdHex: String): List = managedRead() + override fun observeCoreMaxSendableDuffs(): Flow = flowOf(coreMax) + override suspend fun coreAssetLockEligibleDuffs(): Long? = coreEligible + var shieldedFlow: Flow? = null + override fun observeShieldedBalance(): Flow = shieldedFlow ?: flowOf(shieldedBalance) + override suspend fun platformAddressBalances(walletIdHex: String): List = platformBalances() + var identityBalanceReads = 0 + override suspend fun identityBalanceCredits(identityIdBase58: String): Long? { + identityBalanceReads++ + return 2_000_000_000L + } + override suspend fun identityExists(identityIdBase58: String): Boolean = identityIdBase58 == ownIdentity + override suspend fun usernameOf(identityIdBase58: String): String? = "alice" + override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = 2_000_500L + override suspend fun spendableUtxoCount(): Int? = utxoCount + + override suspend fun sendCore(address: String, amount: Dash, emptyWallet: Boolean, session: WalletSession?): String { + calls += "sendCore" + lastCoreEmptyWallet = emptyWallet + lastSession = session + return coreSend() + } + + private fun shielded(name: String, amount: Dash): SdkWriteResult { + calls += name + shieldedAmounts += amount + return shieldedResult(amount) + } + + override suspend fun shieldedWithdrawToCore(walletIdHex: String, address: String, amount: Dash) = + shielded("shieldedWithdrawToCore", amount) + override suspend fun shieldedTransfer(walletIdHex: String, address: String, amount: Dash) = + shielded("shieldedTransfer", amount) + override suspend fun shieldedUnshield(walletIdHex: String, address: String, amount: Dash) = + shielded("shieldedUnshield", amount) + override suspend fun shieldedTopUpIdentity(walletIdHex: String, identityId: ByteArray, amount: Dash): SdkWriteResult { + lastToId = identityId + return shielded("shieldedTopUpIdentity", amount) + } + + override suspend fun shieldFromCore( + walletIdHex: String, + address: String, + amount: Dash + ): SdkWriteResult { + calls += "shieldFromCore" + shieldedAmounts += amount + return shieldFromCoreResult(amount) + } + + override suspend fun coreTopUpIdentity( + identityIdBase58: String, + amountDuffs: Long + ): SdkWriteResult { + calls += "coreTopUpIdentity" + lastDuffs = amountDuffs + return coreTopUpResult() + } + + override suspend fun platformTransfer(walletIdHex: String, to: PlatformAddressBytes, amountCredits: Long) { + calls += "platformTransfer" + lastPlatformTo = to + lastCredits = amountCredits + nativeWrite() + } + + override suspend fun platformTopUpIdentity(walletIdHex: String, identityId: ByteArray, inputs: List) { + calls += "platformTopUpIdentity" + lastToId = identityId + lastInputs = inputs + nativeWrite() + } + + override suspend fun platformTopUpExternalIdentity( + walletIdHex: String, + identityId: ByteArray, + inputs: List + ) { + calls += "platformTopUpExternalIdentity" + lastToId = identityId + lastInputs = inputs + nativeWrite() + } + + override suspend fun identityWithdraw(walletIdHex: String, fromId: ByteArray, amountCredits: Long, coreAddress: String) { + calls += "identityWithdraw" + lastFromId = fromId + lastCredits = amountCredits + nativeWrite() + } + + override suspend fun identityTransferToAddress( + walletIdHex: String, + fromId: ByteArray, + to: PlatformAddressBytes, + amountCredits: Long + ) { + calls += "identityTransferToAddress" + lastFromId = fromId + lastPlatformTo = to + lastCredits = amountCredits + nativeWrite() + } + + override suspend fun identityTransfer(walletIdHex: String, fromId: ByteArray, toId: ByteArray, amountCredits: Long) { + calls += "identityTransfer" + lastFromId = fromId + lastToId = toId + lastCredits = amountCredits + nativeWrite() + } + + // Platform → Core, → Shielded (third party) + var withdrawalPreflight: () -> PlatformWithdrawalPreflight = { PlatformWithdrawalPreflight(true, 400_500_000L) } + var minInput: () -> Long = { 100_000L } + var lastCoreAddress: String? = null + var lastShieldAddress: String? = null + + override suspend fun platformWithdrawalPreflight(walletIdHex: String) = withdrawalPreflight() + override suspend fun platformMinInputCredits(walletIdHex: String): Long = minInput() + + override suspend fun platformWithdraw(walletIdHex: String, coreAddress: String, inputs: List) { + calls += "platformWithdraw" + lastCoreAddress = coreAddress + lastInputs = inputs + nativeWrite() + } + + override suspend fun platformShieldTo(walletIdHex: String, address: String, amount: Dash): SdkWriteResult { + lastShieldAddress = address + return shielded("platformShieldTo", amount) + } + + override suspend fun identityShieldTo( + walletIdHex: String, + fromId: ByteArray, + address: String, + amount: Dash + ): SdkWriteResult { + lastFromId = fromId + lastShieldAddress = address + return shielded("identityShieldTo", amount) + } + + // Core → Platform + var gateOpen: () -> Boolean = { true } + var freshFundingAllowed = true + var remainder: PlatformAddressBytes? = PlatformAddressBytes(0, remainderHash) + var lastRemainderExclude: ByteArray? = null + var fund: (PendingPlatformFunding, (String) -> Unit) -> Unit = { _, built -> built(OUT_POINT) } + var resume: (PendingPlatformFunding) -> Unit = {} + var lockStatus: () -> Int? = { 2 } + var unconsumedLocks: () -> Boolean = { false } + var lastExcludedOutPoints: Set? = null + val funded = mutableListOf() + val resumed = mutableListOf() + + override fun coreFundingGateOpen(): Boolean = gateOpen() + override suspend fun withFreshCoreFunding(build: suspend () -> T): T? = + if (freshFundingAllowed) build() else null + + override suspend fun ownPlatformRemainderAddress(walletIdHex: String, excludeHash: ByteArray): PlatformAddressBytes? { + lastRemainderExclude = excludeHash + return remainder + } + + override suspend fun fundPlatformExternal(record: PendingPlatformFunding, onAssetLockBuilt: (String) -> Unit) { + calls += "fundPlatformExternal" + funded += record + fund(record, onAssetLockBuilt) + } + + override suspend fun resumePlatformFundingExternal(record: PendingPlatformFunding) { + calls += "resumePlatformFundingExternal" + resumed += record + resume(record) + } + + override suspend fun trackedAssetLockStatus(walletIdHex: String, outPointHex: String): Int? = lockStatus() + override suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String, excludingOutPoints: Set): Boolean { + lastExcludedOutPoints = excludingOutPoints + return unconsumedLocks() + } + } + + private class FakeStore : PlatformFundingStore { + var record: PendingPlatformFunding? = null + var failRead = false + var failWrite = false + var failBlocking = false + val writes = mutableListOf() + + override suspend fun read(): PendingPlatformFunding? { + if (failRead) throw java.io.IOException("datastore") + return record + } + + override suspend fun write(record: PendingPlatformFunding) { + if (failWrite) throw java.io.IOException("datastore") + this.record = record + writes += record + } + + override fun writeBlocking(record: PendingPlatformFunding) { + if (failBlocking) throw java.io.IOException("datastore") + this.record = record + writes += record + } + + override suspend fun clear(id: String) { + if (record?.id == id) record = null + } + + // Stored encoded, like DashPayConfig, so a "restart" reads them back through decode. + val unconfirmed = mutableSetOf() + var failMark = false + var failReadUnconfirmed = false + + override suspend fun markCompletionUnconfirmed(id: String) { + if (failMark) throw java.io.IOException("datastore") + val current = record + if (current != null && current.id == id && current.outPointHex != null) { + unconfirmed += current.asCompletionUnconfirmed().encode() + record = null + } + } + + override suspend fun readCompletionUnconfirmed(): List { + if (failReadUnconfirmed) throw java.io.IOException("datastore") + return unconfirmed.map(PendingPlatformFunding::decode) + } + } + + private fun source( + bound: List = listOf(walletA), + ownIdentity: String? = ownIdBase58, + managed: List = listOf(ownId) + ) = FakeSource(bound.toMutableList(), ownIdentity, managed) + + private fun service( + source: FakeSource, + store: PlatformFundingStore = FakeStore(), + fundingSelection: FundingSelectionLock = FundingSelectionLock() + ) = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + store, + ioDispatcher = Dispatchers.Unconfined, + fundingSelection = fundingSelection + ) + + /** A send confirmed while [walletA] was bound (the ViewModel's capture). */ + private suspend fun ExternalSendServiceImpl.send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean + ): ExternalSendResult = send(source, destination, amount, isMax, walletA) + + // ── Each supported pair: right seam, right units ────────────────── + + @Test + fun coreToCore_sendsThroughTheCoreFunnel_withTheCapturedSession_andMaxAsSendAll() = runBlocking { + val source = source() + // A Max is the whole max-sendable balance the user confirmed. + val result = service(source).send(SendBalance.CORE, core, Dash(5_000_000L), isMax = true) + assertEquals(ExternalSendResult.Sent("txid"), result) + assertEquals(listOf("sendCore"), source.calls) + assertEquals(true, source.lastCoreEmptyWallet) + assertTrue(source.lastSession === source.session) + } + + @Test + fun coreToShielded_completed_isSent_pendingRetry_isInterrupted() = runBlocking { + val source = source() + assertEquals( + ExternalSendResult.Sent(SHIELD_LOCK_TXID), + service(source).send(SendBalance.CORE, shielded, amount, false) + ) + // The lock is the amount plus the pool fee (ceil(2_000_500 credits) + 50_000 duffs). + assertEquals(listOf(amount + Dash(52_001L)), source.shieldedAmounts) + + source.shieldFromCoreResult = { + SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY)) + } + assertEquals( + ExternalSendResult.InterruptedFundsReturnToShielded, + service(source).send(SendBalance.CORE, shielded, amount, false) + ) + } + + @Test + fun coreToShielded_lockTxIdMissingOrMalformed_isStillSent_withoutATxId() = runBlocking { + for (txId in listOf(null, "", "not-a-txid", SHIELD_LOCK_TXID.dropLast(1), "zz" + SHIELD_LOCK_TXID.drop(2))) { + val source = source().apply { + shieldFromCoreResult = { + SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.COMPLETED, txId)) + } + } + assertEquals( + "txid $txId", + ExternalSendResult.Sent(null), + service(source).send(SendBalance.CORE, shielded, amount, false) + ) + } + } + + @Test + fun coreToOwnIdentity_topsUpInDuffs_reportingTheTopUpLockTxId() = runBlocking { + val source = source() + assertEquals( + ExternalSendResult.Sent(TOP_UP_LOCK_TXID), + service(source).send(SendBalance.CORE, ownIdentity, amount, false) + ) + assertEquals(listOf("coreTopUpIdentity"), source.calls) + assertEquals(100_000L, source.lastDuffs) + } + + @Test + fun coreToOwnIdentity_lockTxIdUnknown_isStillSent_andFailuresKeepTheirClass() = runBlocking { + val source = source().apply { coreTopUpResult = { SdkWriteResult.Broadcast(TopUpOutcome(1L, null)) } } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.CORE, ownIdentity, amount, false)) + + source.coreTopUpResult = { SdkWriteResult.Ambiguous(IllegalStateException("unknown")) } + assertEquals( + ExternalSendResult.MayHaveGoneThrough, + service(source).send(SendBalance.CORE, ownIdentity, amount, false) + ) + source.coreTopUpResult = { SdkWriteResult.NotBroadcast("a top-up is already in progress") } + assertTrue(service(source).send(SendBalance.CORE, ownIdentity, amount, false) is ExternalSendResult.NotSent) + } + + @Test + fun coreToOwnIdentity_anEarlierTopUpCompletedInstead_isNotSent_neverReportedAsThisSend() = runBlocking { + val source = source().apply { + coreTopUpResult = { + SdkWriteResult.Broadcast(TopUpOutcome(1L, TOP_UP_LOCK_TXID, resumedEarlier = true)) + } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.EARLIER_TOP_UP_COMPLETED), + service(source).send(SendBalance.CORE, ownIdentity, amount, false) + ) + assertEquals(listOf("coreTopUpIdentity"), source.calls) + } + + @Test + fun shieldedToEachDestination_callsItsShieldedWrite() = runBlocking { + val expected = mapOf( + core to "shieldedWithdrawToCore", + shielded to "shieldedTransfer", + platform to "shieldedUnshield", + otherIdentity to "shieldedTopUpIdentity" + ) + for ((dest, call) in expected) { + val source = source() + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.SHIELDED, dest, amount, false)) + assertEquals(listOf(call), source.calls) + // To Core the asset unlock's Core fee is withdrawn on top: the recipient gets `amount`. + val expectedValue = if (dest == core) Dash(amount.duffs + WITHDRAWAL_CORE_FEE_DUFFS) else amount + assertEquals(listOf(expectedValue), source.shieldedAmounts) + } + } + + @Test + fun shieldedToCoreMax_withdrawsTheMaxItself_andIsAvailableOnlyAboveTheWithdrawalMinimum() = runBlocking { + val source = source() + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.SHIELDED, core, amount, isMax = true)) + assertEquals(listOf(amount), source.shieldedAmounts) + + // Pool fee 2 001 duffs: 3 191 − 2 001 = 1 190 duffs, exactly DPP's gross minimum. + source.shieldedBalance = Dash(3_191L) + assertEquals(Dash(1_190L), service(source).maxSendable(SendBalance.SHIELDED, balanceKindOf(core))) + source.shieldedBalance = Dash(3_190L) + assertNull(service(source).maxSendable(SendBalance.SHIELDED, balanceKindOf(core))) + // Other destinations keep the plain positive bound. + assertEquals(Dash(1_189L), service(source).maxSendable(SendBalance.SHIELDED, balanceKindOf(shielded))) + } + + @Test + fun shieldedToIdentity_passesThe32ByteId() = runBlocking { + val source = source() + service(source).send(SendBalance.SHIELDED, otherIdentity, amount, false) + assertArrayEquals(otherId, source.lastToId) + } + + @Test + fun platformToPlatform_transfersCredits_toTheDecodedAddress() = runBlocking { + val source = source() + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, platform, amount, false)) + assertEquals(amountCredits, source.lastCredits) + assertEquals(0, source.lastPlatformTo?.addressType) + assertArrayEquals(hash20, source.lastPlatformTo?.hash) + } + + @Test + fun platformToIdentity_spendsExactlyTheAmount_fromTheAddresses() = runBlocking { + val source = source().apply { + platformBalances = { + listOf(FundingInput(0, ByteArray(20) { 1 }, 460_000_000L), FundingInput(0, ByteArray(20) { 2 }, 70_000_000L)) + } + } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, ownIdentity, amount, false)) + assertEquals(amountCredits, source.lastInputs?.sumOf { it.credits }) + assertArrayEquals(ownId, source.lastToId) + } + + // ── Platform → Identity fee reserve and Max ─────────────────────── + + @Test + fun platformToIdentity_feePayerKeepsTheReserve_forBothTopUpCalls() = runBlocking { + for ((to, call) in listOf(ownIdentity to "platformTopUpIdentity", otherIdentity to "platformTopUpExternalIdentity")) { + // 0x01 sorts first: it pays the fee from what it keeps, so it keeps the reserve. + val source = source().apply { platformBalances = { listOf(address(1, 450_000_000L), address(2, 80_000_000L)) } } + assertEquals("$to", ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, to, amount, false)) + assertEquals("$to", listOf(call), source.calls) + val inputs = requireNotNull(source.lastInputs) + assertEquals(amountCredits, inputs.sumOf { it.credits }) + val payer = inputs.first { it.hash[0] == 1.toByte() } + assertTrue("$to", 450_000_000L - payer.credits >= PLATFORM_TOP_UP_FEE_RESERVE_CREDITS) + } + } + + @Test + fun platformToIdentity_anAmountThatWouldEmptyTheFeePayer_isRefusedBeforeTheCall() = runBlocking { + // One address: everything it holds would leave nothing for the fee. + for (to in listOf(ownIdentity, otherIdentity)) { + val source = source().apply { platformBalances = { listOf(address(1, 500_000_000L)) } } + assertEquals( + "$to", + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(source).send(SendBalance.PLATFORM, to, Dash(500_000L), false) + ) + assertTrue("$to", source.calls.isEmpty()) + } + } + + @Test + fun platformToIdentityMax_isWhatTheSendAccepts_forBothTopUpCalls() = runBlocking { + val balances = listOf(address(1, 2_039_398_000L), address(2, 300_000_000L)) + val expected = (2_039_398_000L - PLATFORM_TOP_UP_FEE_RESERVE_CREDITS + 300_000_000L) / 1_000L + for ((to, call) in listOf(ownIdentity to "platformTopUpIdentity", otherIdentity to "platformTopUpExternalIdentity")) { + val source = source().apply { platformBalances = { balances } } + val max = requireNotNull(service(source).maxSendable(SendBalance.PLATFORM, balanceKindOf(to))) + assertEquals("$to", expected, max.duffs) + assertEquals("$to", ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, to, max, true)) + assertEquals("$to", listOf(call), source.calls) + assertEquals("$to", max.duffs * 1_000L, source.lastInputs?.sumOf { it.credits }) + + val over = source().apply { platformBalances = { balances } } + assertEquals( + "$to", + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(over).send(SendBalance.PLATFORM, to, Dash(max.duffs + 1), false) + ) + assertTrue("$to", over.calls.isEmpty()) + } + } + + @Test + fun platformToIdentityMax_unknownOrTooSmall_isNull() = runBlocking { + val cases = listOf<(FakeSource) -> Unit>( + { s -> s.platformBalances = { throw IllegalStateException("SDK wallet not loaded") } }, + { s -> + s.platformBalances = { listOf(address(1, 900_000_000L)) } + s.minInput = { throw IllegalStateException("SDK wallet not loaded") } + }, + { s -> + s.platformBalances = { listOf(address(1, 900_000_000L)) } + s.minInput = { 0L } + }, + // No address can keep the reserve, or what is left is below the funding minimum. + { s -> s.platformBalances = { listOf(address(1, PLATFORM_TOP_UP_FEE_RESERVE_CREDITS + 50_000L)) } }, + { s -> s.platformBalances = { listOf(address(1, PLATFORM_TOP_UP_FEE_RESERVE_CREDITS + 199_999L)) } }, + { s -> s.platformBalances = { emptyList() } } + ) + for ((index, setUp) in cases.withIndex()) { + val source = source().apply(setUp) + assertNull("case $index", service(source).maxSendable(SendBalance.PLATFORM, balanceKindOf(otherIdentity))) + assertTrue(source.calls.isEmpty()) + } + assertNull(service(source(bound = listOf(null))).maxSendable(SendBalance.PLATFORM, balanceKindOf(ownIdentity))) + // The smallest top-up DPP accepts: exactly the funding minimum. + val atMin = source().apply { platformBalances = { listOf(address(1, PLATFORM_TOP_UP_FEE_RESERVE_CREDITS + 200_000L)) } } + assertEquals(Dash(200L), service(atMin).maxSendable(SendBalance.PLATFORM, balanceKindOf(otherIdentity))) + } + + @Test + fun platformToIdentity_unreadableMinimumInput_orBelowTheFundingMinimum_isNotSent() = runBlocking { + val unreadable = source().apply { + platformBalances = { listOf(address(1, 900_000_000L)) } + minInput = { throw IllegalStateException("SDK wallet not loaded") } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(unreadable).send(SendBalance.PLATFORM, otherIdentity, amount, false) + ) + assertTrue(unreadable.calls.isEmpty()) + val tiny = source().apply { platformBalances = { listOf(address(1, 900_000_000L)) } } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(tiny).send(SendBalance.PLATFORM, otherIdentity, Dash(199L), false) + ) + assertTrue(tiny.calls.isEmpty()) + } + + @Test + fun platformToManagedIdentity_usesTopUpFromAddresses() = runBlocking { + val source = source().apply { platformBalances = { listOf(address(1, 900_000_000L)) } } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, ownIdentity, amount, false)) + assertEquals(listOf("platformTopUpIdentity"), source.calls) + assertArrayEquals(ownId, source.lastToId) + assertEquals(amountCredits, source.lastInputs?.sumOf { it.credits }) + } + + @Test + fun platformToSomeoneElsesIdentity_usesTheExternalTopUp() = runBlocking { + val source = source().apply { platformBalances = { listOf(address(1, 900_000_000L)) } } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, otherIdentity, amount, false)) + assertEquals(listOf("platformTopUpExternalIdentity"), source.calls) + assertArrayEquals(otherId, source.lastToId) + assertEquals(amountCredits, source.lastInputs?.sumOf { it.credits }) + } + + @Test + fun platformToIdentity_theSdkWalletDoesNotManage_usesTheExternalTopUp() = runBlocking { + // No identity at all, or the user's identity record without the SDK wallet managing + // it: either way the managed top-up would not find it; the external one fetches it. + for ((src, to) in listOf( + source(ownIdentity = null, managed = emptyList()) to otherIdentity, + source(ownIdentity = null, managed = emptyList()) to ownIdentity, + source(managed = emptyList()) to ownIdentity + )) { + src.platformBalances = { listOf(address(1, 900_000_000L)) } + assertEquals("$to", ExternalSendResult.Sent(null), service(src).send(SendBalance.PLATFORM, to, amount, false)) + assertEquals("$to", listOf("platformTopUpExternalIdentity"), src.calls) + } + } + + @Test + fun platformToIdentity_managedSetUnreadable_isNotSent_withNoCall() = runBlocking { + val source = source().apply { + platformBalances = { listOf(address(1, 900_000_000L)) } + managedRead = { throw IllegalStateException("wallet not loaded") } + } + for (to in listOf(ownIdentity, otherIdentity)) { + assertEquals( + "$to", + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, to, amount, false) + ) + } + assertTrue(source.calls.isEmpty()) + } + + @Test + fun platformToSomeoneElsesIdentity_platformHasNoSuchIdentity_isNotSent() = runBlocking { + val source = source().apply { + platformBalances = { listOf(address(1, 900_000_000L)) } + nativeWrite = { throw DashSdkError.NotFound("Identity not found: $otherIdBase58", null) } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, otherIdentity, amount, false) + ) + assertEquals(listOf("platformTopUpExternalIdentity"), source.calls) + } + + @Test + fun platformToIdentity_cannotCover_isInsufficient_noCall() = runBlocking { + val source = source().apply { platformBalances = { listOf(FundingInput(0, ByteArray(20) { 1 }, 1_000L)) } } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(source).send(SendBalance.PLATFORM, ownIdentity, amount, false) + ) + assertTrue(source.calls.isEmpty()) + } + + @Test + fun identitySource_callsEachCreditsWrite_fromTheOwnIdentity() = runBlocking { + val expected = mapOf(core to "identityWithdraw", platform to "identityTransferToAddress", otherIdentity to "identityTransfer") + for ((dest, call) in expected) { + val source = source() + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.IDENTITY, dest, amount, false)) + assertEquals(listOf(call), source.calls) + assertArrayEquals(ownId, source.lastFromId) + // A withdrawal to Core withdraws the Core fee on top: the recipient gets `amount`. + val expectedCredits = if (dest == core) amountCredits + WITHDRAWAL_CORE_FEE_CREDITS else amountCredits + assertEquals(expectedCredits, source.lastCredits) + } + } + + @Test + fun identityToCore_outsideTheWithdrawalBounds_isNotSent_withNoCall() = runBlocking { + // 999 duffs + the 190-duff Core fee is below 1 000 000 + 190 000 credits. + for (outside in listOf(Dash(999L), Dash(PLATFORM_MAX_WITHDRAWAL_CREDITS / 1_000L))) { + val source = source() + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.IDENTITY, core, outside, false) + ) + assertTrue(source.calls.isEmpty()) + } + val source = source() + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.IDENTITY, core, Dash(1_000L), false)) + assertEquals(PLATFORM_MIN_WITHDRAWAL_CREDITS, source.lastCredits) + } + + @Test + fun coreWithdrawalCredits_addsTheCoreFee_andBoundsTheGrossAmount() { + assertEquals(190L, WITHDRAWAL_CORE_FEE_DUFFS) + assertEquals(190_000L, WITHDRAWAL_CORE_FEE_CREDITS) + assertEquals(amountCredits + 190_000L, coreWithdrawalCreditsOrNull(amountCredits)) + assertEquals(PLATFORM_MIN_WITHDRAWAL_CREDITS, coreWithdrawalCreditsOrNull(1_000_000L)) + assertNull(coreWithdrawalCreditsOrNull(999_999L)) + assertEquals( + PLATFORM_MAX_WITHDRAWAL_CREDITS, + coreWithdrawalCreditsOrNull(PLATFORM_MAX_WITHDRAWAL_CREDITS - WITHDRAWAL_CORE_FEE_CREDITS) + ) + assertNull(coreWithdrawalCreditsOrNull(PLATFORM_MAX_WITHDRAWAL_CREDITS - WITHDRAWAL_CORE_FEE_CREDITS + 1)) + assertNull(coreWithdrawalCreditsOrNull(Long.MAX_VALUE)) + } + + // ── int37 pairs: Platform → Core, Platform / Identity → Shielded ── + + /** A P2PKH Platform-address balance whose 20-byte hash is all [b]. */ + private fun address(b: Int, credits: Long) = FundingInput(0, ByteArray(20) { b.toByte() }, credits) + + @Test + fun platformToCore_withdrawsExactlyTheAmount_feePayerKeepsTheReserve() = runBlocking { + val reserve = 400_500_000L + val source = source().apply { + // Hash 0x01 sorts first: it pays the fee, so it must keep the reserve. + platformBalances = { listOf(address(1, 450_000_000L), address(2, 80_000_000L)) } + } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, core, amount, false)) + assertEquals(listOf("platformWithdraw"), source.calls) + assertEquals(core.address, source.lastCoreAddress) + val inputs = requireNotNull(source.lastInputs) + // The amount plus the Core fee DPP takes out of the withdrawal: the recipient gets `amount`. + assertEquals(amountCredits + WITHDRAWAL_CORE_FEE_CREDITS, inputs.sumOf { it.credits }) + val payer = inputs.first { it.hash[0] == 1.toByte() } + assertTrue(450_000_000L - payer.credits >= reserve) + assertTrue(inputs.all { input -> input.credits <= (if (input.hash[0] == 1.toByte()) 450_000_000L else 80_000_000L) }) + } + + @Test + fun platformToCore_refusals_beforeAnythingIsSigned_areNotSent_withNoCall() = runBlocking { + val funded = listOf(address(1, 900_000_000L)) + val cases = listOf Unit, ExternalSendResult>>( + // Cannot cover amount + the fee payer's reserve. + { s: FakeSource -> s.platformBalances = { listOf(address(1, 450_000_000L)) } } to + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + { s: FakeSource -> + s.platformBalances = { funded } + s.withdrawalPreflight = { PlatformWithdrawalPreflight(false, 0L) } + } to ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + // A zero fee estimate is unknown, never free. + { s: FakeSource -> + s.platformBalances = { funded } + s.withdrawalPreflight = { PlatformWithdrawalPreflight(true, 0L) } + } to ExternalSendResult.NotSent(NotSentReason.GENERIC), + { s: FakeSource -> + s.platformBalances = { funded } + s.withdrawalPreflight = { throw java.io.IOException("dapi") } + } to ExternalSendResult.NotSent(NotSentReason.GENERIC), + { s: FakeSource -> + s.platformBalances = { funded } + s.minInput = { throw IllegalStateException("SDK wallet not loaded") } + } to ExternalSendResult.NotSent(NotSentReason.GENERIC), + { s: FakeSource -> s.platformBalances = { throw IllegalStateException("SDK wallet not loaded") } } to + ExternalSendResult.NotSent(NotSentReason.GENERIC) + ) + for ((setUp, expected) in cases) { + val source = source().apply(setUp) + assertEquals(expected, service(source).send(SendBalance.PLATFORM, core, amount, false)) + assertTrue(source.calls.isEmpty()) + } + } + + @Test + fun platformToCore_belowTheWithdrawalMinimum_isNotSent_withNoRead() = runBlocking { + var read = false + val source = source().apply { + platformBalances = { + read = true + listOf(address(1, 900_000_000L)) + } + } + // 999 duffs + the 190-duff Core fee withdrawn on top = 1 189 000 credits < 1 000 000 + 190 × 1 000. + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, core, Dash(999L), false) + ) + // Above 500 DASH gross (500 DASH + the Core fee). + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, core, Dash(PLATFORM_MAX_WITHDRAWAL_CREDITS / 1_000L), false) + ) + assertTrue(source.calls.isEmpty()) + assertTrue(!read) + // Exactly at the minimum (gross) is sent. + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, core, Dash(1_000L), false)) + assertEquals(PLATFORM_MIN_WITHDRAWAL_CREDITS, source.lastInputs?.sumOf { it.credits }) + } + + @Test + fun platformToCore_outcomes_mapLikeTheOtherCreditsWrites() = runBlocking { + val source = source().apply { + platformBalances = { listOf(address(1, 900_000_000L)) } + nativeWrite = { throw RuntimeException("connection reset") } + } + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source).send(SendBalance.PLATFORM, core, amount, false)) + + source.nativeWrite = { throw DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed("unconfirmed") } + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source).send(SendBalance.PLATFORM, core, amount, false)) + + source.nativeWrite = { throw DashSdkError.InvalidParameter("bad address") } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, core, amount, false) + ) + } + + @Test + fun platformAndIdentityToShielded_callTheirShieldWrite_withTheRecipient() = runBlocking { + val platformSource = source() + assertEquals(ExternalSendResult.Sent(null), service(platformSource).send(SendBalance.PLATFORM, shielded, amount, false)) + assertEquals(listOf("platformShieldTo"), platformSource.calls) + assertEquals(shielded.address, platformSource.lastShieldAddress) + assertEquals(listOf(amount), platformSource.shieldedAmounts) + + val identitySource = source() + assertEquals(ExternalSendResult.Sent(null), service(identitySource).send(SendBalance.IDENTITY, shielded, amount, false)) + assertEquals(listOf("identityShieldTo"), identitySource.calls) + assertEquals(shielded.address, identitySource.lastShieldAddress) + assertArrayEquals(ownId, identitySource.lastFromId) + assertEquals(listOf(amount), identitySource.shieldedAmounts) + } + + @Test + fun toShielded_outcomes_ambiguousIsMayHaveGoneThrough_notBroadcastIsNotSent_neverRetried() = runBlocking { + for (from in listOf(SendBalance.PLATFORM, SendBalance.IDENTITY)) { + val ambiguous = source().apply { + shieldedResult = { + SdkWriteResult.Ambiguous(DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed("unconfirmed")) + } + } + // Even a Max is never retried for these sources. + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(ambiguous).send(from, shielded, amount, true)) + assertEquals(1, ambiguous.shieldedAmounts.size) + + val notBroadcast = source().apply { + shieldedResult = { + SdkWriteResult.NotBroadcast( + "pre-broadcast", + RuntimeException("Insufficient shielded balance: available 1, required 2") + ) + } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(notBroadcast).send(from, shielded, amount, true) + ) + assertEquals(1, notBroadcast.shieldedAmounts.size) + } + val debitPending = source().apply { + shieldedResult = { classifyBroadcastFailure(DashSdkError.PlatformWallet.ShieldedIdentityDebitPending("pending")) } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), + service(debitPending).send(SendBalance.IDENTITY, shielded, amount, false) + ) + } + + @Test + fun toShielded_gates_shieldedFlagOff_orWalletChanged_callNothing() = runBlocking { + for (from in listOf(SendBalance.PLATFORM, SendBalance.IDENTITY)) { + val flagOff = source().apply { shieldedOn = { false } } + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), service(flagOff).send(from, shielded, amount, false)) + assertTrue(flagOff.calls.isEmpty()) + + val changed = source(bound = listOf(walletA, walletB)) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), service(changed).send(from, shielded, amount, false)) + assertTrue(changed.calls.isEmpty()) + } + val changed = source(bound = listOf(walletA, walletB)).apply { platformBalances = { listOf(address(1, 900_000_000L)) } } + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), service(changed).send(SendBalance.PLATFORM, core, amount, false)) + assertTrue(changed.calls.isEmpty()) + } + + @Test + fun int37Pairs_haveNoPreSendFee_andNoMax_butPlatformToCore() = runBlocking { + val service = service(source().apply { platformBalances = { listOf(address(1, 900_000_000L)) } }) + for ((from, to) in listOf(SendBalance.PLATFORM to shielded, SendBalance.IDENTITY to shielded)) { + assertNull("$from → $to", service.estimateFee(from, balanceKindOf(to))) + assertNull("$from → $to", service.maxSendable(from, balanceKindOf(to))) + } + assertNull(service.estimateFee(SendBalance.PLATFORM, balanceKindOf(core))) + assertNotNull(service.maxSendable(SendBalance.PLATFORM, balanceKindOf(core))) + } + + // ── Platform → Core Max ─────────────────────────────────────────── + + @Test + fun platformToCoreMax_isWhatTheSendAccepts_qaCase() = runBlocking { + // MO-1121 QA: one address with 0.02039398 DASH. The fee payer keeps the preflight's + // 400 500 000-credit reserve and DPP takes the 190-duff Core fee out of the withdrawal: + // (2 039 398 000 − 400 500 000 − 190 000) / 1000 = 1 638 708 duffs. + val source = source().apply { platformBalances = { listOf(address(1, 2_039_398_000L)) } } + val max = service(source).maxSendable(SendBalance.PLATFORM, balanceKindOf(core)) + assertEquals(Dash(1_638_708L), max) + + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, core, Dash(1_638_708L), true)) + assertEquals(2_039_398_000L - 400_500_000L, source.lastInputs?.sumOf { it.credits }) + + // One duff over, and QA's 0.01739398, are refused before anything is signed. + for (over in listOf(Dash(1_638_709L), Dash(1_739_398L))) { + val refused = source().apply { platformBalances = { listOf(address(1, 2_039_398_000L)) } } + assertEquals( + "$over", + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(refused).send(SendBalance.PLATFORM, core, over, false) + ) + assertTrue(refused.calls.isEmpty()) + } + } + + @Test + fun platformToCoreMax_followsTheFeePayerRule() = runBlocking { + // 0x01 sorts first and can pay the reserve: it and every later address join. + val both = source().apply { platformBalances = { listOf(address(1, 450_000_000L), address(2, 80_000_000L)) } } + val bothMax = requireNotNull(service(both).maxSendable(SendBalance.PLATFORM, balanceKindOf(core))) + assertEquals((450_000_000L - 400_500_000L + 80_000_000L - WITHDRAWAL_CORE_FEE_CREDITS) / 1_000L, bothMax.duffs) + assertEquals(ExternalSendResult.Sent(null), service(both).send(SendBalance.PLATFORM, core, bothMax, true)) + + // 0x01 sorts first but cannot pay the reserve: only 0x02 alone can withdraw. + val payerLast = source().apply { platformBalances = { listOf(address(1, 100_000_000L), address(2, 900_000_000L)) } } + val lastMax = requireNotNull(service(payerLast).maxSendable(SendBalance.PLATFORM, balanceKindOf(core))) + assertEquals((900_000_000L - 400_500_000L - WITHDRAWAL_CORE_FEE_CREDITS) / 1_000L, lastMax.duffs) + assertEquals(ExternalSendResult.Sent(null), service(payerLast).send(SendBalance.PLATFORM, core, lastMax, true)) + val overLast = source().apply { platformBalances = { listOf(address(1, 100_000_000L), address(2, 900_000_000L)) } } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(overLast).send(SendBalance.PLATFORM, core, Dash(lastMax.duffs + 1), false) + ) + } + + @Test + fun platformToCoreMax_unknownOrTooSmall_isNull() = runBlocking { + val funded = listOf(address(1, 900_000_000L)) + val cases = listOf<(FakeSource) -> Unit>( + { s -> s.platformBalances = { throw IllegalStateException("SDK wallet not loaded") } }, + { s -> + s.platformBalances = { funded } + s.withdrawalPreflight = { throw java.io.IOException("dapi") } + }, + { s -> + s.platformBalances = { funded } + s.minInput = { throw IllegalStateException("SDK wallet not loaded") } + }, + { s -> + s.platformBalances = { funded } + s.withdrawalPreflight = { PlatformWithdrawalPreflight(false, 0L) } + }, + // A zero fee estimate is unknown, never free. + { s -> + s.platformBalances = { funded } + s.withdrawalPreflight = { PlatformWithdrawalPreflight(true, 0L) } + }, + // Below DPP's minimum withdrawal once the reserve and the Core fee are off. + { s -> s.platformBalances = { listOf(address(1, 401_600_000L)) } }, + { s -> s.platformBalances = { emptyList() } } + ) + for ((index, setUp) in cases.withIndex()) { + val source = source().apply(setUp) + assertNull("case $index", service(source).maxSendable(SendBalance.PLATFORM, balanceKindOf(core))) + assertTrue(source.calls.isEmpty()) + } + // No bound wallet: unknown. + assertNull(service(source(bound = listOf(null))).maxSendable(SendBalance.PLATFORM, balanceKindOf(core))) + } + + @Test + fun maxPlatformWithdrawalCredits_matchesTheSelectorsLimits() { + val reserve = 1_000L + // At most 16 inputs: the payer and the 15 largest after it. + val many = (1..20).map { address(it, 10_000L + it) } + val max = requireNotNull(maxPlatformWithdrawalCredits(many, reserve, minInputCredits = 100L)) + // The best payer is 0x05: a later payer has fewer than 15 addresses after it. + assertEquals(10_005L - reserve + (6..20).sumOf { 10_000L + it }, max) + assertNotNull(selectPlatformWithdrawalInputs(many, max, reserve, 100L)) + assertNull(selectPlatformWithdrawalInputs(many, max + 1, reserve, 100L)) + // Inputs below the minimum and P2SH addresses never count. + val mixed = listOf(address(1, 5_000L), address(2, 50L), FundingInput(1, ByteArray(20) { 3 }, 9_000L)) + assertEquals(4_000L, maxPlatformWithdrawalCredits(mixed, reserve, minInputCredits = 100L)) + // No address can pay the reserve. + assertNull(maxPlatformWithdrawalCredits(listOf(address(1, 1_050L)), reserve, minInputCredits = 100L)) + } + + // ── selectPlatformWithdrawalInputs ──────────────────────────────── + + @Test + fun withdrawalSelection_singleInput_whenThePayerCoversAmountAndReserve() { + val inputs = requireNotNull( + selectPlatformWithdrawalInputs(listOf(address(5, 1_000L), address(9, 300L)), 600L, 400L, 10L) + ) + assertEquals(1, inputs.size) + assertEquals(600L, inputs.single().credits) + assertEquals(5.toByte(), inputs.single().hash[0]) + } + + @Test + fun withdrawalSelection_theFirstSortingInputPays_andKeepsTheReserve_othersMayBeDrained() { + // Neither address covers 1 000 + reserve alone. Hash 0x01 sorts first, so it pays; + // 0x02 is drained in full. + val inputs = requireNotNull( + selectPlatformWithdrawalInputs(listOf(address(2, 600L), address(1, 900L)), 1_000L, 400L, 10L) + ) + assertEquals(1_000L, inputs.sumOf { it.credits }) + val payer = inputs.first() + assertEquals(1.toByte(), payer.hash[0]) + assertTrue(900L - payer.credits >= 400L) + assertEquals(600L, inputs.first { it.hash[0] == 2.toByte() }.credits) + } + + @Test + fun withdrawalSelection_unsignedHashOrder_decidesThePayer() { + // 0x80 sorts AFTER 0x01 unsigned (signed it would sort before). Only 0x01 can keep the + // reserve, so it must be the first-sorting input of the set. + val inputs = requireNotNull( + selectPlatformWithdrawalInputs(listOf(address(0x80, 500L), address(1, 700L)), 700L, 400L, 10L) + ) + assertEquals(1.toByte(), inputs.first().hash[0]) + assertTrue(700L - inputs.first().credits >= 400L) + assertEquals(700L, inputs.sumOf { it.credits }) + } + + @Test + fun withdrawalSelection_refuses_whatItCannotCoverExactly() { + // Not enough once the payer keeps its reserve. + assertNull(selectPlatformWithdrawalInputs(listOf(address(1, 1_000L)), 700L, 400L, 10L)) + // Below the minimum input, below the minimum per input, P2SH only, non-positive target. + assertNull(selectPlatformWithdrawalInputs(listOf(address(1, 1_000L)), 5L, 400L, 10L)) + assertNull(selectPlatformWithdrawalInputs(listOf(address(1, 1_000L), address(2, 9L)), 605L, 400L, 10L)) + assertNull(selectPlatformWithdrawalInputs(listOf(FundingInput(1, ByteArray(20) { 1 }, 1_000L)), 100L, 0L, 10L)) + assertNull(selectPlatformWithdrawalInputs(listOf(address(1, 1_000L)), 0L, 0L, 10L)) + // At most maxInputs inputs. + val many = (1..5).map { address(it, 100L) } + assertNull(selectPlatformWithdrawalInputs(many, 450L, 0L, 10L, maxInputs = 4)) + assertEquals(450L, selectPlatformWithdrawalInputs(many, 450L, 0L, 10L, maxInputs = 5)?.sumOf { it.credits }) + } + + @Test + fun withdrawalSelection_neverTakesMoreThanABalance_andEveryInputClearsTheMinimum() { + val candidates = listOf(address(3, 250L), address(1, 520L), address(2, 120L), address(4, 75L)) + val balances = candidates.associate { it.hash[0] to it.credits } + for (target in 10L..560L step 7L) { + val inputs = selectPlatformWithdrawalInputs(candidates, target, 100L, 20L) ?: continue + assertEquals(target, inputs.sumOf { it.credits }) + assertTrue(inputs.all { it.credits >= 20L && it.credits <= requireNotNull(balances[it.hash[0]]) }) + val payer = inputs.minWith { a, b -> (a.hash[0].toInt() and 0xff) - (b.hash[0].toInt() and 0xff) } + assertTrue(requireNotNull(balances[payer.hash[0]]) - payer.credits >= 100L) + assertTrue(inputs.first() === payer) + } + } + + // ── Outcome classification ──────────────────────────────────────── + + @Test + fun notBroadcast_isNotSent_withAMappedReason() = runBlocking { + val source = source().apply { + shieldedResult = { SdkWriteResult.NotBroadcast("shielded runtime not ready") } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), + service(source).send(SendBalance.SHIELDED, core, amount, false) + ) + } + + @Test + fun ambiguous_isMayHaveGoneThrough() = runBlocking { + val source = source().apply { shieldedResult = { SdkWriteResult.Ambiguous(RuntimeException("timeout")) } } + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source).send(SendBalance.SHIELDED, core, amount, false)) + } + + @Test + fun nativeWrite_unknownThrow_isMayHaveGoneThrough_preBroadcastThrow_isNotSent() = runBlocking { + val source = source().apply { nativeWrite = { throw RuntimeException("connection reset") } } + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source).send(SendBalance.PLATFORM, platform, amount, false)) + + source.nativeWrite = { throw org.dashfoundation.dashsdk.errors.DashSdkError.InvalidParameter("bad") } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, platform, amount, false) + ) + } + + @Test + fun coreSend_pendingSubmission_isMayHaveGoneThrough_notSynced_isNotSent() = runBlocking { + val source = source().apply { coreSend = { throw PaymentSubmissionPendingException("unknown", null) } } + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source).send(SendBalance.CORE, core, amount, false)) + + source.coreSend = { throw SendEngineNotSyncedException("gate closed") } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), + service(source).send(SendBalance.CORE, core, amount, false) + ) + } + + @Test + fun shieldedMax_shortByTheFee_retriesOnceWithTheDeficit() = runBlocking { + val source = source().apply { + shieldedResult = { value -> + if (value == amount) { + SdkWriteResult.NotBroadcast( + "pre-broadcast", + RuntimeException("Insufficient shielded balance: available 100000000, required 100500000") + ) + } else { + SdkWriteResult.Broadcast(Unit) + } + } + } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.SHIELDED, core, amount, isMax = true)) + assertEquals(listOf(amount, Dash(99_500L)), source.shieldedAmounts) + } + + @Test + fun shieldedNotMax_shortByTheFee_doesNotRetry() = runBlocking { + val source = source().apply { + shieldedResult = { + SdkWriteResult.NotBroadcast( + "pre-broadcast", + RuntimeException("Insufficient shielded balance: available 100000000, required 100500000") + ) + } + } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service(source).send(SendBalance.SHIELDED, core, amount, isMax = false) + ) + assertEquals(1, source.shieldedAmounts.size) + } + + // ── safeErrorSummary ────────────────────────────────────────────── + + @Test + fun safeErrorSummary_namesTheClassesAndNativeCode_neverAMessage() { + val secret = "Identity not found: $otherIdBase58" + val summary = safeErrorSummary( + IllegalStateException(secret, DashSdkError.PlatformWallet.Generic(7, secret, DashSdkError.NotFound(secret, null))) + ) + assertEquals("IllegalStateException <- Generic(code 7) <- NotFound", summary) + assertFalse(summary.contains(otherIdBase58)) + assertEquals("none", safeErrorSummary(null)) + } + + // ── Gates: nothing is called ────────────────────────────────────── + + @Test + fun unsupportedPairs_areNotSupported_withNoSeamCall() = runBlocking { + val pairs = listOf( + // The SDK funds P2PKH Platform addresses only. + SendBalance.CORE to platformP2sh, + SendBalance.IDENTITY to ownIdentity, + // Someone else's identity from Core: the resume gate cannot protect it. + SendBalance.CORE to otherIdentity + ) + for ((from, to) in pairs) { + val source = source() + assertEquals( + "$from → $to", + ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), + service(source).send(from, to, amount, false) + ) + assertTrue("$from → $to", source.calls.isEmpty()) + } + } + + @Test + fun identitySource_withoutAnIdentity_isNotSupported() = runBlocking { + val source = source(ownIdentity = null) + assertEquals( + ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), + service(source).send(SendBalance.IDENTITY, core, amount, false) + ) + assertTrue(source.calls.isEmpty()) + } + + @Test + fun walletChangedBetweenCaptureAndSubmit_isNotSent_withNoNativeCall() = runBlocking { + for ((from, to) in listOf( + SendBalance.CORE to core, + SendBalance.CORE to shielded, + SendBalance.CORE to platform, + SendBalance.SHIELDED to core, + SendBalance.PLATFORM to platform, + SendBalance.IDENTITY to core + )) { + // Captured A; the re-check right before the write reads B. + val source = source(bound = listOf(walletA, walletB)) + assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.GENERIC), service(source).send(from, to, amount, false)) + assertTrue("$from → $to", source.calls.isEmpty()) + } + } + + @Test + fun cutoverUnreadable_orNotCommitted_isNotSent_withNoCall() = runBlocking { + val unreadable = source().apply { cutover = { throw java.io.IOException("datastore") } } + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), service(unreadable).send(SendBalance.CORE, core, amount, false)) + assertTrue(unreadable.calls.isEmpty()) + + val notCommitted = source().apply { cutover = { false } } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), + service(notCommitted).send(SendBalance.CORE, core, amount, false) + ) + assertTrue(notCommitted.calls.isEmpty()) + } + + @Test + fun shieldedFlagOff_blocksEveryShieldedLeg() = runBlocking { + for ((from, to) in listOf(SendBalance.SHIELDED to core, SendBalance.CORE to shielded)) { + val source = source().apply { shieldedOn = { false } } + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), service(source).send(from, to, amount, false)) + assertTrue(source.calls.isEmpty()) + } + } + + @Test + fun wrongNetworkDestination_isRefused_withNoCall() = runBlocking { + val source = source() + val mainnetPlatform = SendDestination.Platform( + requireNotNull(Bech32m.encode("dash", byteArrayOf(0xb0.toByte()) + hash20)) + ) + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source).send(SendBalance.PLATFORM, mainnetPlatform, amount, false) + ) + assertTrue(source.calls.isEmpty()) + } + + @Test + fun concurrentSend_isInProgress() = runBlocking { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val source = source() + source.shieldedResult = { SdkWriteResult.Broadcast(Unit) } + val service = service(source) + val slow = object : ExternalSendSource by source { + override suspend fun shieldedTransfer(walletIdHex: String, address: String, amount: Dash): SdkWriteResult { + entered.complete(Unit) + release.await() + return SdkWriteResult.Broadcast(Unit) + } + } + val gated = ExternalSendServiceImpl( + slow, + AddressNetwork.DASH_TESTNET, + FakeStore(), + ioDispatcher = Dispatchers.Unconfined, + fundingSelection = FundingSelectionLock() + ) + try { + val first = async(start = CoroutineStart.UNDISPATCHED) { + gated.send(SendBalance.SHIELDED, shielded, amount, false) + } + entered.await() + assertEquals( + ExternalSendResult.NotSent(NotSentReason.IN_PROGRESS), + gated.send(SendBalance.SHIELDED, core, amount, false) + ) + release.complete(Unit) + assertEquals(ExternalSendResult.Sent(null), first.await()) + } finally { + release.complete(Unit) + } + // The other instance is unaffected. + assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.SHIELDED, core, amount, false)) + } + + // ── Reads ───────────────────────────────────────────────────────── + + @Test + fun unknownBalances_areNull_neverZero() = runBlocking { + val source = source().apply { + coreMax = null + shieldedBalance = null + platformBalances = { throw IllegalStateException("SDK wallet not loaded") } + } + val service = service(source) + assertNull(service.observeBalance(SendBalance.CORE).first()) + assertNull(service.observeBalance(SendBalance.SHIELDED).first()) + assertNull(service.observeBalance(SendBalance.PLATFORM).first()) + assertNull(service(source(ownIdentity = null)).observeBalance(SendBalance.IDENTITY).first()) + assertNull(service.maxSendable(SendBalance.SHIELDED, balanceKindOf(core))) + } + + @Test + fun knownBalances_areConvertedWithTheRightUnits() = runBlocking { + val source = source().apply { platformBalances = { listOf(FundingInput(0, hash20, 1_500_999L)) } } + val service = service(source) + assertEquals(Dash(5_000_000L), service.observeBalance(SendBalance.CORE).first()) + // Credits floor to duffs. + assertEquals(Dash(1_500L), service.observeBalance(SendBalance.PLATFORM).first()) + assertEquals(Dash(2_000_000L), service.observeBalance(SendBalance.IDENTITY).first()) + // Shielded max: balance − ceil(2_000_500 credits) = 1_000_000 − 2_001 duffs. + assertEquals(Dash(997_999L), service.maxSendable(SendBalance.SHIELDED, balanceKindOf(core))) + assertNull(service.maxSendable(SendBalance.PLATFORM, balanceKindOf(platform))) + } + + @Test + fun fees_areNullWhereNoPreSendFigureExists() = runBlocking { + val service = service(source()) + // The size-based reserve over the spendable UTXO count (2). + assertEquals(FeeEstimate(Dash(sendAllFeeReserveDuffs(2)), exact = false), service.estimateFee(SendBalance.CORE, balanceKindOf(core))) + // Shielded → Core: the pool fee plus the asset unlock's Core fee withdrawn on top. + assertEquals(FeeEstimate(Dash(2_191L), exact = false), service.estimateFee(SendBalance.SHIELDED, balanceKindOf(core))) + assertEquals(FeeEstimate(Dash(2_001L), exact = false), service.estimateFee(SendBalance.SHIELDED, balanceKindOf(platform))) + assertNull(service.estimateFee(SendBalance.PLATFORM, balanceKindOf(platform))) + assertNull(service.estimateFee(SendBalance.IDENTITY, balanceKindOf(core))) + } + + @Test + fun coreToIdentity_fee_isOnlyTheL1AssetLockReserve_nullWhenTheUtxoCountIsUnknown() = runBlocking { + val source = source() + val service = service(source) + // The top-up locks exactly the amount: the L1 reserve is on top, with no Platform margin + // (Platform's top-up fee comes out of the locked amount). + assertEquals( + FeeEstimate(assetLockMaxFeeReserve(2), exact = false), + service.estimateFee(SendBalance.CORE, balanceKindOf(ownIdentity)) + ) + source.utxoCount = 10 + assertEquals( + FeeEstimate(assetLockMaxFeeReserve(10), exact = false), + service.estimateFee(SendBalance.CORE, balanceKindOf(ownIdentity)) + ) + // Fail closed: an unknown UTXO count is no fee figure, never zero. + source.utxoCount = null + assertNull(service.estimateFee(SendBalance.CORE, balanceKindOf(ownIdentity))) + // Max stays unavailable for Core → Identity. + source.utxoCount = 2 + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(ownIdentity))) + } + + @Test + fun identityLookups() = runBlocking { + val service = service(source()) + assertEquals(IdentityResolution.Found("alice"), service.resolveIdentity(ownIdBase58)) + assertEquals(IdentityResolution.NotFound, service.resolveIdentity(otherIdBase58)) + assertEquals(true, service.isOwnIdentity(ownIdBase58)) + assertEquals(false, service.isOwnIdentity(otherIdBase58)) + assertEquals(true, service.observeHasIdentity().first()) + assertEquals(false, service(source(ownIdentity = null)).observeHasIdentity().first()) + } + + // ── Review round 1 regressions ──────────────────────────────────── + + @Test + fun coreToShielded_theRecipientReceivesTheConfirmedAmount_feeAndMaxAreConsistent() = runBlocking { + val source = source() + val service = service(source) + val poolFee = Dash(52_001L) + // The fee shown is exactly what the lock adds on top of the amount. + assertEquals(FeeEstimate(poolFee, exact = false), service.estimateFee(SendBalance.CORE, balanceKindOf(shielded))) + // Max: the eligible balance less the L1 reserve is locked; the recipient receives it + // minus the pool fee. + val max = requireNotNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) + assertEquals(Dash(5_000_000L) - assetLockMaxFeeReserve(2) - poolFee, max) + assertEquals( + ExternalSendResult.Sent(SHIELD_LOCK_TXID), + service.send(SendBalance.CORE, shielded, max, isMax = true) + ) + assertEquals(listOf(Dash(5_000_000L) - assetLockMaxFeeReserve(2)), source.shieldedAmounts) + } + + @Test + fun coreToShieldedMax_comesFromTheAssetLockEligibleBalance_notThePooledCoreFigure() = runBlocking { + val poolFee = Dash(52_001L) + // Unconfirmed / receival-account funds inflate the pooled figure; Max ignores them. + val source = source().apply { + coreMax = 9_000_000L + coreEligible = 3_000_000L + } + val service = service(source) + assertEquals( + Dash(3_000_000L) - assetLockMaxFeeReserve(2) - poolFee, + service.maxSendable(SendBalance.CORE, balanceKindOf(shielded)) + ) + // Fail closed: an unknown eligible balance or UTXO count is no Max. + source.coreEligible = null + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) + source.coreEligible = 3_000_000L + source.utxoCount = null + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) + // Too small to cover the reserve and the pool fee: no Max, never negative. + source.utxoCount = 2 + source.coreEligible = assetLockMaxFeeReserve(2).duffs + poolFee.duffs + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) + } + + @Test + fun coreToShieldedMax_selectionShort_isNotSent_withoutARetry() = runBlocking { + val source = source().apply { + shieldFromCoreResult = { SdkWriteResult.NotBroadcast("asset lock coin selection is short") } + } + val service = service(source) + val max = requireNotNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) + assertEquals( + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + service.send(SendBalance.CORE, shielded, max, isMax = true) + ) + assertEquals(1, source.shieldedAmounts.size) + } + + @Test + fun coreToCoreMax_tinyBalance_isUnavailable_soTheRecipientAmountIsNeverZeroOrNegative() = runBlocking { + val source = source() + val service = service(source) + val reserve = sendAllFeeReserveDuffs(2) + source.coreMax = reserve + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(core))) + source.coreMax = 1L + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(core))) + // Just above the reserve: Max is the gross figure, and amount − fee stays positive. + source.coreMax = reserve + 1 + val max = requireNotNull(service.maxSendable(SendBalance.CORE, balanceKindOf(core))) + val fee = requireNotNull(service.estimateFee(SendBalance.CORE, balanceKindOf(core))).fee + assertEquals(Dash(reserve + 1), max) + assertTrue((max - fee).isPositive) + // Unknown UTXO count: the flat reserve applies to both the fee and the Max gate. + source.utxoCount = null + source.coreMax = SEND_ALL_FEE_RESERVE_DUFFS + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(core))) + assertEquals( + FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false), + service.estimateFee(SendBalance.CORE, balanceKindOf(core)) + ) + } + + @Test + fun coreToShielded_poolFeeUnknown_isNotSent_withNoCall() = runBlocking { + val source = object : ExternalSendSource by source() { + override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = null + } + val result = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + FakeStore(), + ioDispatcher = Dispatchers.Unconfined, + fundingSelection = FundingSelectionLock() + ) + .send(SendBalance.CORE, shielded, amount, false, walletA) + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), result) + } + + @Test + fun coreMax_drainsOnlyWhileTheBalanceIsWhatTheUserConfirmed() = runBlocking { + // Confirmed 1 DASH as Max; 5 DASH more arrived meanwhile: nothing is drained. + val source = source().apply { coreMax = 600_000_000L } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.BALANCE_CHANGED), + service(source).send(SendBalance.CORE, core, Dash(100_000_000L), isMax = true) + ) + assertTrue(source.calls.isEmpty()) + + source.coreMax = null + assertEquals( + ExternalSendResult.NotSent(NotSentReason.BALANCE_CHANGED), + service(source).send(SendBalance.CORE, core, Dash(100_000_000L), isMax = true) + ) + assertTrue(source.calls.isEmpty()) + + // A non-Max send of the same amount is not a drain and is not gated on it. + source.coreMax = 600_000_000L + assertEquals(ExternalSendResult.Sent("txid"), service(source).send(SendBalance.CORE, core, amount, isMax = false)) + assertEquals(false, source.lastCoreEmptyWallet) + } + + @Test + fun theWalletCapturedAtConfirmation_mustBeTheBoundOne_beforeAnything() = runBlocking { + val pairs = listOf( + SendBalance.CORE to core, + SendBalance.CORE to shielded, + SendBalance.CORE to ownIdentity, + SendBalance.CORE to platform, + SendBalance.SHIELDED to core, + SendBalance.PLATFORM to platform, + SendBalance.PLATFORM to ownIdentity, + SendBalance.IDENTITY to core + ) + for ((from, to) in pairs) { + // Confirmed with wallet A; B is bound by the time the send runs (and stays bound). + val replaced = source(bound = listOf(walletB)) + assertEquals( + "$from → $to", + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(replaced).send(from, to, amount, false, walletA) + ) + assertTrue("$from → $to", replaced.calls.isEmpty()) + + val none = source() + assertEquals( + "$from → $to", + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(none).send(from, to, amount, false, null) + ) + assertTrue("$from → $to", none.calls.isEmpty()) + } + assertEquals(walletA, service(source()).currentWalletIdOrNull()) + } + + @Test + fun observations_recoverAfterATransientReadError() = runBlocking { + var identityReads = 0 + var shieldedReads = 0 + val source = source().apply { + identityFlow = flow { + if (identityReads++ == 0) throw java.io.IOException("datastore") + emit(Result.success(ownIdBase58)) + } + shieldedFlow = flow { + if (shieldedReads++ == 0) throw java.io.IOException("datastore") + emit(Dash(7L)) + } + } + val service = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + FakeStore(), + ioDispatcher = Dispatchers.Unconfined, + retryDelayMs = { 0L }, + fundingSelection = FundingSelectionLock() + ) + assertEquals(listOf(null, true), service.observeHasIdentity().take(2).toList()) + assertEquals(listOf(null, Dash(7L)), service.observeBalance(SendBalance.SHIELDED).take(2).toList()) + } + + @Test + fun identityBalance_aReEmittedSameIdentity_doesNotRestartThePoll() = runBlocking { + val reEmitted = CompletableDeferred() + val source = source().apply { + identityFlow = flow { + // An unrelated config write re-emits the unchanged identity record. + repeat(3) { + emit(Result.success(ownIdBase58)) + delay(50) + } + reEmitted.complete(Unit) + awaitCancellation() + } + } + val service = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + FakeStore(), + ioDispatcher = Dispatchers.Unconfined, + balancePollMs = 60_000L, + fundingSelection = FundingSelectionLock() + ) + val values = mutableListOf() + val job = launch { service.observeBalance(SendBalance.IDENTITY).collect { values += it } } + reEmitted.await() + job.cancelAndJoin() + assertEquals(listOf(Dash(2_000_000L)), values) + assertEquals(1, source.identityBalanceReads) + } + + @Test + fun retryReadErrors_emitsUnknown_thenResubscribes_andNeverCompletesOnAnError() = runBlocking { + var reads = 0 + val values = flow { + reads++ + if (reads <= 2) throw IllegalStateException("unknown creation state") + emit(Result.success("id")) + }.retryReadErrors( + Result.failure(IllegalStateException("unknown")), + retryDelayMs = { 0L }, + onError = logReadRetry("identity record") { 0L } + ) + .take(3) + .toList() + assertTrue(values[0].isFailure) + assertTrue(values[1].isFailure) + assertEquals("id", values[2].getOrNull()) + } + // ── Core → Platform (fundFromAssetLockExternal) ─────────────────── + + private fun pendingRecord(outPointHex: String? = OUT_POINT, wallet: String = walletA) = PendingPlatformFunding( + id = "earlier", + walletIdHex = wallet, + lockDuffs = 162_000L, + destination = PlatformAddressBytes(0, hash20), + explicitCredits = amountCredits, + remainder = PlatformAddressBytes(0, remainderHash), + outPointHex = outPointHex + ) + + @Test + fun coreToPlatform_paysTheExactAmount_remainderToAnOwnAddress_lockCarriesTheMargin() = runBlocking { + val source = source() + val store = FakeStore() + var persistedBeforeTheCall: PendingPlatformFunding? = null + var outPointDurableInTheCallback: String? = null + source.fund = { record, built -> + persistedBeforeTheCall = store.record + assertTrue(requireNotNull(persistedBeforeTheCall).sameAs(record)) + built(OUT_POINT) + outPointDurableInTheCallback = store.record?.outPointHex + } + val result = service(source, store).send(SendBalance.CORE, platform, amount, false) + + // The lock's display txid: the outpoint without its vout. + assertEquals(ExternalSendResult.Sent(OUT_POINT.substringBefore(':')), result) + assertEquals(listOf("fundPlatformExternal"), source.calls) + val record = source.funded.single() + // Persisted before the call, without an outpoint; the outpoint was durable before the callback returned. + assertNull(requireNotNull(persistedBeforeTheCall).outPointHex) + assertEquals(OUT_POINT, outPointDurableInTheCallback) + // The payee gets exactly the amount; the lock adds the Platform-fee margin. + assertEquals(100_000L + PLATFORM_FUNDING_FEE_MARGIN_DUFFS, record.lockDuffs) + assertEquals(walletA, record.walletIdHex) + assertEquals( + listOf( + org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.FundRecipient(0, hash20, amountCredits), + org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.FundRecipient(0, remainderHash, null) + ), + record.recipients + ) + // The remainder is never the payee's address. + assertArrayEquals(hash20, source.lastRemainderExclude) + // Success clears the record. + assertNull(store.record) + } + + @Test + fun coreToPlatform_seedsThePlatformKindForTheBuiltLock_inTheCallback() = runBlocking { + val seeds = mutableListOf>() + var seededInTheCallback = false + val source = source().apply { + fund = { _, built -> + built(OUT_POINT) + seededInTheCallback = seeds.isNotEmpty() + } + } + val service = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + FakeStore(), + ioDispatcher = Dispatchers.Unconfined, + seedAssetLockKind = { hex, kind -> seeds += hex to kind }, + fundingSelection = FundingSelectionLock() + ) + assertEquals(ExternalSendResult.Sent(LOCK_TXID), service.send(SendBalance.CORE, platform, amount, false)) + // Keyed by the lock's display txid (the outpoint without its vout), before broadcast. + assertEquals(listOf(OUT_POINT.substringBefore(':') to AssetLockKind.PLATFORM), seeds) + assertTrue(seededInTheCallback) + } + + @Test + fun coreToPlatform_aFailingKindSeed_neverFailsTheSend() = runBlocking { + val source = source().apply { fund = { _, built -> built(OUT_POINT) } } + val store = FakeStore() + val service = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + store, + ioDispatcher = Dispatchers.Unconfined, + seedAssetLockKind = { _, _ -> throw IllegalStateException("seed") }, + fundingSelection = FundingSelectionLock() + ) + assertEquals(ExternalSendResult.Sent(LOCK_TXID), service.send(SendBalance.CORE, platform, amount, false)) + assertNull(store.record) + } + + @Test + fun coreToPlatform_malformedOutPoint_isStillSent_withoutATxId() = runBlocking { + for (outPoint in listOf("garbage", ":1", "0123:1", "zz" + OUT_POINT.drop(2))) { + val source = source().apply { fund = { _, built -> built(outPoint) } } + val store = FakeStore() + assertEquals( + "outpoint $outPoint", + ExternalSendResult.Sent(null), + service(source, store).send(SendBalance.CORE, platform, amount, false) + ) + assertNull(store.record) + } + } + + @Test + fun coreToPlatform_p2shDestination_isNotSent_beforeAnythingIsBuiltOrPersisted() = runBlocking { + val source = source() + val store = FakeStore() + assertEquals( + ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), + service(source, store).send(SendBalance.CORE, platformP2sh, amount, false) + ) + assertTrue(source.calls.isEmpty()) + assertTrue(store.writes.isEmpty()) + } + + @Test + fun coreToPlatform_failureAfterTheLockWasBuilt_isNeverNotSent_andKeepsTheRecord() = runBlocking { + // A pre-broadcast-looking error AFTER onAssetLockBuilt: the lock exists all the same. + for (error in listOf(RuntimeException("no private key stored"), RuntimeException("platform timeout"))) { + val source = source().apply { + fund = { _, built -> + built(OUT_POINT) + throw error + } + } + val store = FakeStore() + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source, store).send(SendBalance.CORE, platform, amount, false)) + val kept = requireNotNull(store.record) + assertEquals(OUT_POINT, kept.outPointHex) + assertTrue(kept.sameAs(source.funded.single().withOutPoint(OUT_POINT))) + } + } + + @Test + fun coreToPlatform_outPointWriteFailedInTheCallback_isRecordedAfterTheCall() = runBlocking { + val source = source().apply { + fund = { _, built -> + built(OUT_POINT) + throw RuntimeException("platform timeout") + } + } + val store = FakeStore().apply { failBlocking = true } + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source, store).send(SendBalance.CORE, platform, amount, false)) + assertEquals(OUT_POINT, store.record?.outPointHex) + } + + @Test + fun coreToPlatform_failureBeforeTheLockWasBuilt_isNotSent_andClearsTheRecord() = runBlocking { + val source = source().apply { fund = { _, _ -> throw RuntimeException("no private key stored") } } + val store = FakeStore() + val result = service(source, store).send(SendBalance.CORE, platform, amount, false) + assertTrue(result is ExternalSendResult.NotSent) + assertEquals(1, store.writes.size) + assertNull(store.record) + } + + @Test + fun coreToPlatform_ambiguousBeforeTheLockWasBuilt_isMayHaveGoneThrough_andKeepsTheRecordForTheSweep() = runBlocking { + val source = source().apply { fund = { _, _ -> throw RuntimeException("platform timeout") } } + val store = FakeStore() + assertEquals(ExternalSendResult.MayHaveGoneThrough, service(source, store).send(SendBalance.CORE, platform, amount, false)) + assertNull(requireNotNull(store.record).outPointHex) + } + + @Test + fun coreToPlatform_aPendingRecord_blocksTheNextSend_withNothingBuilt() = runBlocking { + val source = source() + val store = FakeStore().apply { record = pendingRecord() } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), + service(source, store).send(SendBalance.CORE, platform, amount, false) + ) + assertTrue(source.calls.isEmpty()) + assertEquals("earlier", store.record?.id) + + // Unreadable (or malformed) is not "none": fail closed. + val unreadable = FakeStore().apply { failRead = true } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source, unreadable).send(SendBalance.CORE, platform, amount, false) + ) + assertTrue(source.calls.isEmpty()) + } + + @Test + fun coreToPlatform_refusals_beforeTheCall_persistNothingOrClearIt() = runBlocking { + // The recipients cannot be persisted: nothing is built. + var source = source() + var store = FakeStore().apply { failWrite = true } + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), service(source, store).send(SendBalance.CORE, platform, amount, false)) + assertTrue(source.calls.isEmpty()) + + // L1 funding gate closed. + source = source().apply { gateOpen = { false } } + store = FakeStore() + assertEquals(ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), service(source, store).send(SendBalance.CORE, platform, amount, false)) + assertTrue(source.calls.isEmpty()) + assertTrue(store.writes.isEmpty()) + + // No own Platform address for the remainder. + source = source().apply { remainder = null } + assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), service(source, store).send(SendBalance.CORE, platform, amount, false)) + assertTrue(source.calls.isEmpty()) + assertTrue(store.writes.isEmpty()) + + // Below Platform's minimum output (500 000 credits = 500 duffs). + source = source() + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service(source, store).send(SendBalance.CORE, platform, Dash(499L), false) + ) + assertTrue(source.calls.isEmpty()) + assertTrue(store.writes.isEmpty()) + + // An unprotected earlier payment blocks the fresh build: the record is cleared again. + source = source().apply { freshFundingAllowed = false } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), + service(source, store).send(SendBalance.CORE, platform, amount, false) + ) + assertTrue(source.calls.isEmpty()) + assertEquals(1, store.writes.size) + assertNull(store.record) + } + + @Test + fun coreToPlatform_feeAndMax_carryTheL1ReserveAndThePlatformMargin() = runBlocking { + val source = source() + val service = service(source) + val fee = Dash(assetLockMaxFeeReserve(2).duffs + PLATFORM_FUNDING_FEE_MARGIN_DUFFS) + assertEquals(FeeEstimate(fee, exact = false), service.estimateFee(SendBalance.CORE, balanceKindOf(platform))) + assertEquals(Dash(5_000_000L) - fee, service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) + + // Unknown figures are no Max / no fee, never zero. + source.coreEligible = null + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) + source.coreEligible = 5_000_000L + source.utxoCount = null + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) + assertNull(service.estimateFee(SendBalance.CORE, balanceKindOf(platform))) + // Too small to cover the reserve and the margin (or Platform's minimum output): no Max. + source.utxoCount = 2 + source.coreEligible = fee.duffs + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) + source.coreEligible = fee.duffs + 499L + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) + source.coreEligible = fee.duffs + 500L + assertEquals(Dash(500L), service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) + } + + @Test + fun resume_usesExactlyThePersistedRecipients_andClearsOnSuccess() = runBlocking { + val source = source() + val pending = pendingRecord() + val store = FakeStore().apply { record = pending } + val service = service(source, store) + assertEquals(1, service.resumePendingPlatformFunding()) + assertEquals(listOf("resumePlatformFundingExternal"), source.calls) + assertTrue(source.resumed.single().sameAs(pending)) + assertEquals(pending.recipients, source.resumed.single().recipients) + assertNull(store.record) + // Nothing left: the next sweep does nothing. + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals(1, source.resumed.size) + } + + @Test + fun resume_consumedLock_clearsTheRecord() = runBlocking { + val source = source().apply { lockStatus = { ASSET_LOCK_STATUS_CONSUMED } } + val store = FakeStore().apply { record = pendingRecord() } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertTrue(source.calls.isEmpty()) + assertNull(store.record) + } + + @Test + fun resume_alreadyConsumedAnswer_keepsTheRecordAsCompletionUnconfirmed_neverResumedAgain_andStopsBlocking() = runBlocking { + val source = source().apply { + resume = { throw DashSdkError.PlatformWallet.AssetLockAlreadyConsumed("already consumed") } + } + val store = FakeStore().apply { record = pendingRecord() } + val service = service(source, store) + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals(1, source.resumed.size) + // Kept, marked, out of the pending slot: never deleted for an unauthenticated answer. + assertNull(store.record) + val kept = store.readCompletionUnconfirmed().single() + assertTrue(kept.completionUnconfirmed) + assertTrue(kept.sameAs(pendingRecord().asCompletionUnconfirmed())) + + // A later process (new service instance, same store) does not resume it either. + val restarted = service(source, store) + assertEquals(0, restarted.resumePendingPlatformFunding()) + assertEquals(1, source.resumed.size) + + // The next Core → Platform send is not refused; its own record is the pending one. + assertEquals(ExternalSendResult.Sent(LOCK_TXID), restarted.send(SendBalance.CORE, platform, amount, false)) + assertEquals(1, source.funded.size) + assertEquals(1, store.readCompletionUnconfirmed().size) + } + + @Test + fun resume_alreadyConsumedAnswer_thatCannotBeMarked_staysPendingAndBlocking() = runBlocking { + val source = source().apply { + resume = { throw DashSdkError.PlatformWallet.AssetLockAlreadyConsumed("already consumed") } + } + val store = FakeStore().apply { + record = pendingRecord() + failMark = true + } + val service = service(source, store) + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals(1, source.resumed.size) + assertEquals("earlier", store.record?.id) + assertEquals( + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), + service.send(SendBalance.CORE, platform, amount, false) + ) + assertTrue(source.funded.isEmpty()) + } + + @Test + fun resume_withoutAnOutPoint_ignoresOnlyTheCompletionUnconfirmedLocks_ofThisWallet() = runBlocking { + val otherOutPoint = "fe".repeat(32) + ":0" + val store = FakeStore().apply { + record = pendingRecord(outPointHex = null) + unconfirmed += pendingRecord().asCompletionUnconfirmed().encode() + unconfirmed += PendingPlatformFunding( + "other-wallet", walletB, 162_000L, PlatformAddressBytes(0, hash20), amountCredits, + PlatformAddressBytes(0, remainderHash), otherOutPoint, completionUnconfirmed = true + ).encode() + } + // Another (genuinely open) funding lock still keeps the record. + var source = source().apply { unconsumedLocks = { true } } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertEquals(setOf(OUT_POINT), source.lastExcludedOutPoints) + assertEquals("earlier", store.record?.id) + + source = source().apply { unconsumedLocks = { false } } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertNull(store.record) + + // Their set unreadable: fail closed, the record is kept and the SDK is not asked. + store.record = pendingRecord(outPointHex = null) + store.failReadUnconfirmed = true + source = source().apply { unconsumedLocks = { false } } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertNull(source.lastExcludedOutPoints) + assertEquals("earlier", store.record?.id) + } + + @Test + fun resume_unconfirmedOutcome_keepsTheRecord_untilALaterResumeProvesIt() = runBlocking { + // dashpay/platform#5556: Tenderdash's "tx already exists in cache" for the identical + // transition no longer surfaces as "Object already exists"; the SDK waits for the + // proved result and, when that fails, reports the outcome as unconfirmed. + val unconfirmed = listOf( + DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed( + "state transition outcome is unconfirmed; reconcile the original operation " + + "before submitting a replacement: Object already exists: tx already exists in cache" + ), + DashSdkError.StateTransitionResultUnconfirmed("wait timeout"), + RuntimeException("wrapped", DashSdkError.StateTransitionResultUnconfirmed("wait timeout")) + ) + for (error in unconfirmed) { + var fail = true + val source = source().apply { + resume = { if (fail) throw error } + } + val store = FakeStore().apply { record = pendingRecord() } + val service = service(source, store) + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals("earlier", store.record?.id) + // Kept, so a new Core → Platform send is still refused, with nothing built. + assertEquals( + ExternalSendResult.NotSent(NotSentReason.PAYMENT_STILL_CONFIRMING), + service.send(SendBalance.CORE, platform, amount, false) + ) + assertTrue(source.funded.isEmpty()) + + // The next sweep resubmits the same transition; its proved success clears it. + fail = false + assertEquals(1, service.resumePendingPlatformFunding()) + assertEquals(2, source.resumed.size) + assertTrue(source.resumed.all { it.sameAs(pendingRecord()) }) + assertNull(store.record) + assertEquals(ExternalSendResult.Sent(LOCK_TXID), service.send(SendBalance.CORE, platform, amount, false)) + } + } + + @Test + fun coreToPlatform_unconfirmedOutcome_isMayHaveGoneThrough_neverNotSent_andKeepsTheRecord() = runBlocking { + // The typed error carries an arbitrary SDK diagnostic; a pre-broadcast-looking one must + // not turn it into NotSent, whether or not the lock callback has fired. + val diagnostics = listOf("no private key stored", "Insufficient funds", "Invalid identity data") + for (built in listOf(false, true)) { + for (diagnostic in diagnostics) { + val source = source().apply { + fund = { _, onBuilt -> + if (built) onBuilt(OUT_POINT) + throw DashSdkError.StateTransitionResultUnconfirmed(diagnostic) + } + } + val store = FakeStore() + assertEquals( + ExternalSendResult.MayHaveGoneThrough, + service(source, store).send(SendBalance.CORE, platform, amount, false) + ) + val kept = requireNotNull(store.record) + assertEquals(if (built) OUT_POINT else null, kept.outPointHex) + } + } + } + + @Test + fun resume_failure_keepsTheRecord_andAttemptsAreCappedPerProcess() = runBlocking { + val source = source().apply { resume = { throw RuntimeException("platform timeout") } } + val store = FakeStore().apply { record = pendingRecord() } + val service = service(source, store) + repeat(ExternalSendServiceImpl.MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS + 2) { + assertEquals(0, service.resumePendingPlatformFunding()) + } + assertEquals(ExternalSendServiceImpl.MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS, source.resumed.size) + assertEquals("earlier", store.record?.id) + } + + @Test + fun resume_withoutAnOutPoint_clearsOnlyWhenNoFundingLockIsOpen() = runBlocking { + var source = source().apply { unconsumedLocks = { true } } + val store = FakeStore().apply { record = pendingRecord(outPointHex = null) } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertTrue(source.calls.isEmpty()) + assertEquals("earlier", store.record?.id) + + source = source().apply { unconsumedLocks = { false } } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertTrue(source.calls.isEmpty()) + assertNull(store.record) + } + + @Test + fun resume_keepsTheRecord_forAnotherWallet_anUntrackedLock_orAnUnreadableStatus() = runBlocking { + for (setup in listOf<(FakeSource) -> Unit>( + { it.bound = mutableListOf(walletB) }, + { it.lockStatus = { null } }, + { it.lockStatus = { throw java.io.IOException("room") } }, + { it.cutover = { false } } + )) { + val source = source().also(setup) + val store = FakeStore().apply { record = pendingRecord() } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertTrue(source.calls.isEmpty()) + assertEquals("earlier", store.record?.id) + } + } + + @Test + fun resume_doesNotRunAlongsideASend() = runBlocking { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val source = source().apply { + fund = { _, built -> + built(OUT_POINT) + runBlocking { + entered.complete(Unit) + release.await() + } + } + } + val store = FakeStore() + val service = service(source, store) + try { + val send = async(Dispatchers.Default) { service.send(SendBalance.CORE, platform, amount, false) } + entered.await() + // The send owns its record (outpoint recorded, lock not done): the sweep keeps off it. + assertEquals(0, service.resumePendingPlatformFunding()) + assertTrue(source.resumed.isEmpty()) + release.complete(Unit) + assertEquals(ExternalSendResult.Sent(LOCK_TXID), send.await()) + } finally { + release.complete(Unit) + } + assertNull(store.record) + } + + // ── Reset Wallet: the wipe barrier ─────────────────────────────── + + /** Every SDK write route except Core → Core (its funnel holds the barrier itself). */ + private val barrierRoutes: List> + get() = listOf( + SendBalance.CORE to shielded, + SendBalance.CORE to ownIdentity, + SendBalance.CORE to platform, + SendBalance.SHIELDED to core, + SendBalance.SHIELDED to shielded, + SendBalance.SHIELDED to platform, + SendBalance.SHIELDED to otherIdentity, + SendBalance.PLATFORM to platform, + SendBalance.PLATFORM to ownIdentity, + SendBalance.PLATFORM to core, + SendBalance.PLATFORM to shielded, + SendBalance.IDENTITY to core, + SendBalance.IDENTITY to platform, + SendBalance.IDENTITY to otherIdentity, + SendBalance.IDENTITY to shielded + ) + + private fun barrierSource() = source().apply { + platformBalances = { listOf(address(1, 900_000_000L), address(2, 900_000_000L)) } + } + + @Test + fun aWipeUnderWay_refusesEveryWrite_withNothingCalled_andNothingRecorded() = runBlocking { + for ((from, to) in barrierRoutes) { + val lock = FundingSelectionLock().apply { raiseWipeBarrier() } + val source = barrierSource() + val store = FakeStore() + val result = service(source, store, lock).send(from, to, amount, false) + assertEquals("$from → $to", ExternalSendResult.NotSent(NotSentReason.GENERIC), result) + assertTrue("$from → $to: ${source.calls}", source.calls.isEmpty()) + assertNull("$from → $to", store.record) + + // The next wallet's sends go through once the wipe is done. + lock.lowerWipeBarrier() + val next = service(barrierSource(), FakeStore(), lock).send(from, to, amount, false) + assertTrue("$from → $to", next is ExternalSendResult.Sent) + } + } + + @Test + fun theFinalWalletCheck_runsInsideTheHold_soARefusalComesBeforeIt() = runBlocking { + // One bound read before the hold (sendInner) and none inside it: the wipe refuses first. + val lock = FundingSelectionLock().apply { raiseWipeBarrier() } + var reads = 0 + val source = object : ExternalSendSource by barrierSource() { + override suspend fun boundWalletIdOrNull(): String? { + reads++ + return walletA + } + } + val service = ExternalSendServiceImpl( + source, + AddressNetwork.DASH_TESTNET, + FakeStore(), + ioDispatcher = Dispatchers.Unconfined, + fundingSelection = lock + ) + assertEquals( + ExternalSendResult.NotSent(NotSentReason.GENERIC), + service.send(SendBalance.PLATFORM, platform, amount, false) + ) + assertEquals(1, reads) + lock.lowerWipeBarrier() + assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.PLATFORM, platform, amount, false)) + assertEquals(3, reads) + } + + @Test + fun aWipeThatCancelsACreditsWrite_afterItsSubmission_isMayHaveGoneThrough_neverACancellation() = runBlocking { + val lock = FundingSelectionLock() + val source = source().apply { + nativeWrite = { + // Reset Wallet starts while the SDK call runs; the call then notices the cancel. + lock.raiseWipeBarrier() + yield() + } + } + assertEquals( + ExternalSendResult.MayHaveGoneThrough, + service(source, fundingSelection = lock).send(SendBalance.PLATFORM, platform, amount, false) + ) + assertEquals(listOf("platformTransfer"), source.calls) + } + + @Test + fun aWipeThatCancelsACoreToPlatformFunding_keepsItsBuiltLock_andIsMayHaveGoneThrough() = runBlocking { + val lock = FundingSelectionLock() + val store = FakeStore() + val source = source().apply { + fund = { _, built -> built(OUT_POINT) } + } + val gated = object : ExternalSendSource by source { + override suspend fun fundPlatformExternal( + record: PendingPlatformFunding, + onAssetLockBuilt: (String) -> Unit + ) { + source.fundPlatformExternal(record, onAssetLockBuilt) + lock.raiseWipeBarrier() + yield() + } + } + val service = ExternalSendServiceImpl( + gated, + AddressNetwork.DASH_TESTNET, + store, + ioDispatcher = Dispatchers.Unconfined, + fundingSelection = lock + ) + assertEquals(ExternalSendResult.MayHaveGoneThrough, service.send(SendBalance.CORE, platform, amount, false)) + // The lock was built: its record (with the outpoint) stays for the wipe to clear. + assertEquals(OUT_POINT, store.record?.outPointHex) + } + + @Test + fun resume_refusedByAWipeUnderWay_callsNothing_andKeepsTheRecord() = runBlocking { + val lock = FundingSelectionLock().apply { raiseWipeBarrier() } + val source = source() + val pending = pendingRecord() + val store = FakeStore().apply { record = pending } + assertEquals(0, service(source, store, lock).resumePendingPlatformFunding()) + assertTrue(source.resumed.isEmpty()) + assertTrue(requireNotNull(store.record).sameAs(pending)) + + lock.lowerWipeBarrier() + assertEquals(1, service(source, store, lock).resumePendingPlatformFunding()) + assertNull(store.record) + } + + @Test + fun theAddressFundingLockType_isNotOneTheShieldedOrIdentitySweepsRead() { + assertTrue(ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP != ASSET_LOCK_FUNDING_TYPE_SHIELDED_TOPUP) + assertTrue( + org.dashfoundation.dashsdk.wallet.TrackedAssetLock.FundingType.values() + .none { it.raw == ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP } + ) + } + + private companion object { + const val OUT_POINT = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef:1" + const val LOCK_TXID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + const val SHIELD_LOCK_TXID = "aa23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + const val TOP_UP_LOCK_TXID = "bb23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + val remainderHash = ByteArray(20) { 7 } + } +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncServiceTest.kt new file mode 100644 index 0000000000..bdf977bff4 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncServiceTest.kt @@ -0,0 +1,157 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package de.schildbach.wallet.service.platform.sdk + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Start/stop fencing of [PlatformAddressSyncService] over a fake SDK seam. */ +class PlatformAddressSyncServiceTest { + + private class FakeSource : PlatformAddressSyncSource { + var ready: () -> Boolean = { true } + var running = false + var starts = 0 + var stops = 0 + var startGate: CompletableDeferred? = null + val startEntered = CompletableDeferred() + var startFailure: Exception? = null + var stopFailure: Exception? = null + + override suspend fun ready() = ready.invoke() + override suspend fun isRunning() = running + override suspend fun start() { + startEntered.complete(Unit) + startGate?.await() + startFailure?.let { throw it } + starts++ + running = true + } + override suspend fun stop() { + stopFailure?.let { throw it } + stops++ + running = false + } + } + + private val source = FakeSource() + + @Test + fun startsWhenReady() = runBlocking { + val service = PlatformAddressSyncService(source) + + assertTrue(service.startIfReady(service.stopGeneration())) + assertEquals(1, source.starts) + } + + @Test + fun doesNotStartBeforeTheWalletIsBound() = runBlocking { + source.ready = { false } + val service = PlatformAddressSyncService(source) + + assertFalse(service.startIfReady(service.stopGeneration())) + assertEquals(0, source.starts) + } + + @Test + fun anUnreadableReadinessDoesNotStart() = runBlocking { + source.ready = { throw IllegalStateException("cutover state unreadable") } + val service = PlatformAddressSyncService(source) + + assertFalse(service.startIfReady(service.stopGeneration())) + assertEquals(0, source.starts) + } + + @Test + fun isIdempotentWhileRunning() = runBlocking { + source.running = true + val service = PlatformAddressSyncService(source) + + assertTrue(service.startIfReady(service.stopGeneration())) + assertEquals(0, source.starts) + } + + @Test + fun aStopAfterTheStartWasDecided_refusesIt() = runBlocking { + val service = PlatformAddressSyncService(source) + val decidedUnder = service.stopGeneration() + + service.stop() + + assertFalse(service.startIfReady(decidedUnder)) + assertEquals(0, source.starts) + assertFalse(source.running) + } + + @Test + fun aStopThatWaitsForAnInFlightStart_stopsTheLoopItStarted() = runBlocking { + source.startGate = CompletableDeferred() + val service = PlatformAddressSyncService(source) + + val start = async(Dispatchers.Default) { service.startIfReady(service.stopGeneration()) } + withTimeout(5_000) { source.startEntered.await() } + val stop = async(Dispatchers.Default) { service.stop() } + source.startGate?.complete(Unit) + start.await() + stop.await() + + assertFalse(source.running) + } + + @Test + fun aStopThatTimedOutOnTheLock_isPaidByTheStartWhenItReturns() = runBlocking { + source.startGate = CompletableDeferred() + val service = PlatformAddressSyncService(source, stopLockTimeoutMs = 50) + + val start = async(Dispatchers.Default) { service.startIfReady(service.stopGeneration()) } + withTimeout(5_000) { source.startEntered.await() } + service.stop() // times out on the lock held by the start + assertEquals(0, source.stops) + source.startGate?.complete(Unit) + + assertFalse(start.await()) + assertEquals(1, source.starts) + assertEquals(1, source.stops) + assertFalse(source.running) + } + + @Test + fun startAndStopFailuresAreContained() = runBlocking { + source.startFailure = IllegalStateException("native start failed") + source.stopFailure = IllegalStateException("native stop failed") + val service = PlatformAddressSyncService(source) + + assertFalse(service.startIfReady(service.stopGeneration())) + service.stop() + } + + @Test + fun aStartAfterAStopIsAllowedUnderTheNewGeneration() = runBlocking { + val service = PlatformAddressSyncService(source) + service.stop() + + assertTrue(service.startIfReady(service.stopGeneration())) + assertEquals(1, source.starts) + } +} diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkDashPayWritesTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkDashPayWritesTest.kt index bd403d81ef..2fab40cfb4 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkDashPayWritesTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkDashPayWritesTest.kt @@ -517,7 +517,15 @@ class SdkDashPayWritesTest { // note-value arithmetic guards in select_notes DashSdkError.PlatformWallet.WalletOperation( "shielded transfer failed: Shielded build error: amount + fee overflows u64" - ) + ), + // a third-party shield (Type 15 / 21) to this wallet's own Orchard address, + // refused by resolve_shield_recipient before anything is built + DashSdkError.PlatformWallet.WalletOperation( + "shielded shield failed: Shielded build error: recipient belongs to this shielded " + + "account; use the self-shield entry point (no recipient) instead" + ), + // an earlier identity shield is unresolved: this one was never built + DashSdkError.PlatformWallet.ShieldedIdentityDebitPending("earlier identity debit unresolved") ) for (error in liveShapes) { val result = classifyBroadcastFailure(error) @@ -575,6 +583,39 @@ class SdkDashPayWritesTest { } } + @Test + fun classify_typedUnconfirmed_isAmbiguous_whateverItsDiagnosticSays() { + // dashpay/platform#5556: the typed unconfirmed outcome embeds the SDK's unproven + // diagnostic, which may read exactly like a pre-broadcast refusal. + val preBroadcastLooking = listOf( + "no private key stored for key 1", + "Invalid identity data: no encryption key", + "Insufficient funds: available 1, required 2", + "asset lock coin selection is short", + "SPV client not started", + "invalid platform address", + "User not authenticated" + ) + for (diagnostic in preBroadcastLooking) { + val errors = listOf( + DashSdkError.StateTransitionResultUnconfirmed(diagnostic), + DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed(diagnostic), + DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed(diagnostic), + DashSdkError.PlatformWallet.MasternodeWithdrawalUnconfirmed(diagnostic), + RuntimeException(diagnostic, DashSdkError.StateTransitionResultUnconfirmed(diagnostic)) + ) + for (error in errors) { + assertTrue("$diagnostic must stay unconfirmed", isSubmissionOutcomeUnconfirmed(error)) + val result = classifyBroadcastFailure(error) + assertTrue("${error.javaClass.simpleName}($diagnostic) must be Ambiguous", result is SdkWriteResult.Ambiguous) + assertSame(error, (result as SdkWriteResult.Ambiguous).cause) + } + } + assertFalse(isSubmissionOutcomeUnconfirmed(DashSdkError.Timeout("dapi timeout"))) + assertFalse(isSubmissionOutcomeUnconfirmed(DashSdkError.PlatformWallet.PublicContactRequestUnconfirmed("held"))) + assertFalse(isSubmissionOutcomeUnconfirmed(RuntimeException("state transition outcome is unconfirmed"))) + } + // ── Preflight: everything before the broadcast is NotBroadcast ─────── @Test diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreationTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreationTest.kt index 3ee4535e0c..8f2cb08f48 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreationTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkShieldedUsernameCreationTest.kt @@ -1260,6 +1260,14 @@ class SdkShieldedUsernameCreationTest { DashSdkError.PlatformWallet.ShieldedInviteAlreadyClaimed("") ) ) + // A typed unconfirmed outcome is never terminal, whatever its diagnostic quotes. + for (unconfirmed in listOf( + DashSdkError.StateTransitionResultUnconfirmed("Object already exists: tx already exists in cache"), + DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed("nullifier already spent"), + DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed("outpoint already used") + )) { + assertFalse(SdkShieldedUsernameCreation.isInviteAlreadyUsedFailure(unconfirmed)) + } // The fail-closed denomination refusal is NOT already-used — it is the // only refusal the ladder may descend on. assertFalse( diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryServiceTest.kt index ef9c7cff40..770c2cb2b2 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTopUpRecoveryServiceTest.kt @@ -184,6 +184,22 @@ class SdkTopUpRecoveryServiceTest { assertFalse(report.retryNeeded) } + @Test + fun drain_unconfirmedOutcome_quotingAlreadyUsed_isRetried_notTerminal() { + // dashpay/platform#5556: an unconfirmed submission embeds its unproven diagnostic. + val unconfirmed = DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed( + "state transition outcome is unconfirmed: output 0 already completely used" + ) + val source = FakeSource( + boundWalletId = { walletId }, + recoveryLocks = { listOf(lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP)) }, + onResume = { throw unconfirmed } + ) + val report = runBlocking { service(source).drainPendingTopUps() } + assertEquals(TopUpDrainReport(pending = 1, resumed = 0, alreadyConsumed = 0, failed = 1), report) + assertTrue(report.retryNeeded) + } + @Test fun drain_oneFailure_doesNotStopTheRest_andRequestsRetry() { val failing = lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP, firstByte = 2) diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt index 065983ca4f..4b8f5f88d9 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt @@ -49,6 +49,7 @@ class SdkTransparentTopUpTest { var unresolvedLock: () -> TrackedAssetLock? = { null }, var onResume: (TrackedAssetLock) -> Long? = { null }, var onTopUpFromCore: () -> Long? = { null }, + var builtLockTxid: () -> String? = { null }, private val identityId: ByteArray, private val registrationIndex: Int, private val walletId: String @@ -75,7 +76,7 @@ class SdkTransparentTopUpTest { override suspend fun topUpAssetLockTxidDisplayHex( walletIdHex: String, registrationIndex: Int - ): String? = null + ): String? = builtLockTxid() override suspend fun topUpFromCore( walletIdHex: String, @@ -259,4 +260,142 @@ class SdkTransparentTopUpTest { assertTrue(result is SdkWriteResult.Broadcast) assertEquals(1, source.resumeCalls) } + + // ── the lock txid reported to External Send ─────────────────────────── + + private fun topUpOf(source: FakeSource, freshFundingBlocked: Boolean = false) = SdkTransparentTopUp( + source = source, + cutoverCommitted = { true }, + freshFundingBlocked = { freshFundingBlocked }, + fundingSelection = de.schildbach.wallet.payments.FundingSelectionLock() + ) + + @Test + fun reportingLockTxId_freshBuild_carriesTheBuiltLocksDisplayTxid() { + val source = fakeSource() + source.onTopUpFromCore = { 55_000L } + source.builtLockTxid = { "cd".repeat(32) } + + val result = runBlocking { + topUpOf(source).topUpReportingLockTxId(identityBase58, amountDuffs, newUserIntent = true) + } + + assertEquals(SdkWriteResult.Broadcast(TopUpOutcome(55_000L, "cd".repeat(32))), result) + } + + @Test + fun reportingLockTxId_resume_carriesTheResumedLocksDisplayTxid() { + val source = fakeSource() + val lock = trackedLock(firstByte = 9) + source.unresolvedLock = { lock } + source.onResume = { 42_000L } + + val result = runBlocking { + topUpOf(source).topUpReportingLockTxId(identityBase58, amountDuffs, newUserIntent = false) + } + + assertEquals(SdkWriteResult.Broadcast(TopUpOutcome(42_000L, displayHexOf(lock.outpointTxid))), result) + } + + @Test + fun reportingLockTxId_newIntentResumingAnEarlierLock_isFlaggedResumedEarlier_plainTopUpUnchanged() { + val lock = trackedLock(firstByte = 9) + val source = fakeSource().apply { + unresolvedLock = { lock } + onResume = { 42_000L } + } + + val result = runBlocking { + topUpOf(source).topUpReportingLockTxId(identityBase58, amountDuffs, newUserIntent = true) + } + + // The earlier request's lock was completed; nothing of this request's amount was built. + assertEquals( + SdkWriteResult.Broadcast(TopUpOutcome(42_000L, displayHexOf(lock.outpointTxid), resumedEarlier = true)), + result + ) + assertEquals(0, source.topUpFromCoreCalls) + + // topUp's own result (Buy Credits, PerformTopUpWorker) is unchanged. + val plain = fakeSource().apply { + unresolvedLock = { lock } + onResume = { 42_000L } + } + assertEquals( + SdkWriteResult.Broadcast(42_000L), + runBlocking { topUpOf(plain).topUp(identityBase58, amountDuffs, newUserIntent = true) } + ) + } + + @Test + fun reportingLockTxId_newIntentSkippingAStaleConsumedLock_buildsFresh_notResumedEarlier() { + val source = fakeSource().apply { + unresolvedLock = { trackedLock() } + onResume = { throw alreadyConsumedFailure() } + onTopUpFromCore = { 77_000L } + builtLockTxid = { "cd".repeat(32) } + } + + val result = runBlocking { + topUpOf(source).topUpReportingLockTxId(identityBase58, amountDuffs, newUserIntent = true) + } + + assertEquals(SdkWriteResult.Broadcast(TopUpOutcome(77_000L, "cd".repeat(32))), result) + assertEquals(1, source.topUpFromCoreCalls) + } + + @Test + fun reportingLockTxId_rerunOnItsOwnConsumedLock_carriesThatLocksTxid() { + val source = fakeSource() + val lock = trackedLock(firstByte = 5) + source.unresolvedLock = { lock } + source.onResume = { throw alreadyConsumedFailure() } + + val result = runBlocking { + topUpOf(source).topUpReportingLockTxId(identityBase58, amountDuffs, newUserIntent = false) + } + + assertEquals( + SdkWriteResult.Broadcast( + TopUpOutcome(SdkTransparentTopUp.BALANCE_ALREADY_CREDITED, displayHexOf(lock.outpointTxid)) + ), + result + ) + assertEquals(0, source.topUpFromCoreCalls) + } + + @Test + fun reportingLockTxId_unrecoverableTxid_isStillBroadcast_withoutIt() { + val source = fakeSource() + source.onTopUpFromCore = { 55_000L } + source.builtLockTxid = { throw IllegalStateException("asset_locks unreadable") } + + val result = runBlocking { + topUpOf(source).topUpReportingLockTxId(identityBase58, amountDuffs, newUserIntent = true) + } + + assertEquals(SdkWriteResult.Broadcast(TopUpOutcome(55_000L, null)), result) + } + + @Test + fun reportingLockTxId_failuresKeepTheirClass_andPlainTopUpIsUnchanged() { + val blocked = fakeSource().apply { onTopUpFromCore = { 55_000L } } + val refused = runBlocking { + topUpOf(blocked, freshFundingBlocked = true).topUpReportingLockTxId(identityBase58, amountDuffs, true) + } + assertTrue(refused is SdkWriteResult.NotBroadcast) + + val unknown = fakeSource().apply { onTopUpFromCore = { null } } + val ambiguous = runBlocking { topUpOf(unknown).topUpReportingLockTxId(identityBase58, amountDuffs, true) } + assertTrue(ambiguous is SdkWriteResult.Ambiguous) + + val plain = fakeSource().apply { + onTopUpFromCore = { 55_000L } + builtLockTxid = { "cd".repeat(32) } + } + assertEquals( + SdkWriteResult.Broadcast(55_000L), + runBlocking { topUpOf(plain).topUp(identityBase58, amountDuffs, newUserIntent = true) } + ) + } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt index 2423e4efc5..39800691e1 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -282,6 +282,31 @@ class ShieldedBalanceServiceTest { onShield() } + var lastIdentityId: ByteArray? = null + val shieldToCalls = mutableListOf() + + override suspend fun shieldToRecipient(walletId: ByteArray, recipientRaw43: ByteArray, amountCredits: Long) { + broadcastCalls++ + shieldToCalls += "platform" + lastRecipientRaw43 = recipientRaw43 + lastAmountCredits = amountCredits + onShield() + } + + override suspend fun shieldFromIdentityToRecipient( + walletId: ByteArray, + identityId: ByteArray, + recipientRaw43: ByteArray, + amountCredits: Long + ) { + broadcastCalls++ + shieldToCalls += "identity" + lastIdentityId = identityId + lastRecipientRaw43 = recipientRaw43 + lastAmountCredits = amountCredits + onShield() + } + override suspend fun transfer( walletId: ByteArray, recipientRaw43: ByteArray, @@ -458,7 +483,8 @@ class ShieldedBalanceServiceTest { stopLockTimeoutMs: Long = ShieldedBalanceServiceImpl.STOP_LOCK_TIMEOUT_MS, afterReadyCommitted: suspend () -> Unit = {}, afterStopFallbackBump: suspend () -> Unit = {}, - freshFundingBlocked: suspend () -> Boolean = { false } + freshFundingBlocked: suspend () -> Boolean = { false }, + seedAssetLockKind: (String, AssetLockKind) -> Unit = { _, _ -> } ) = ShieldedBalanceServiceImpl( source = source, dashPayConfig = config(enabled, l1ShadowEnabled, lastBalanceDuffs, consumed), @@ -474,6 +500,7 @@ class ShieldedBalanceServiceTest { afterReadyCommitted = afterReadyCommitted, afterStopFallbackBump = afterStopFallbackBump, freshFundingBlocked = freshFundingBlocked, + seedAssetLockKind = seedAssetLockKind, fundingSelection = de.schildbach.wallet.payments.FundingSelectionLock() ) @@ -1767,6 +1794,84 @@ class ShieldedBalanceServiceTest { } } + // ── Third-party shields: Platform (Type 15) / identity (Type 21) → recipient ── + + private val identity32 = ByteArray(32) { 4 } + + private suspend fun ShieldedBalanceServiceImpl.shieldTo( + fromIdentity: Boolean, + address: String = recipientAddress, + amount: Dash = Dash(250), + expectedWallet: String = walletIdHex, + identityId: ByteArray = identity32 + ): SdkWriteResult = if (fromIdentity) { + shieldFromIdentityToAddress(identityId, address, amount, expectedWallet) + } else { + shieldFromCreditsToAddress(address, amount, expectedWallet) + } + + @Test + fun shieldToRecipient_mapsRecipientAmountAndIdentity() = runBlocking { + for (fromIdentity in listOf(false, true)) { + val source = readySource() + val result = service(source).shieldTo(fromIdentity) + + assertTrue(result is SdkWriteResult.Broadcast) + assertEquals(listOf(if (fromIdentity) "identity" else "platform"), source.shieldToCalls) + assertArrayEquals(recipientRaw43, source.lastRecipientRaw43) + assertEquals(250_000L, source.lastAmountCredits) + if (fromIdentity) assertArrayEquals(identity32, source.lastIdentityId) + } + } + + @Test + fun shieldToRecipient_preflightRefusals_areNotBroadcast_withNoBroadcastAttempt() = runBlocking { + val mainnetAddress = encodeOrchardAddress(recipientRaw43, "dash")!! + for (fromIdentity in listOf(false, true)) { + val source = readySource() + val service = service(source) + for (bad in listOf("not-an-address", mainnetAddress)) { + assertTrue(service.shieldTo(fromIdentity, address = bad) is SdkWriteResult.NotBroadcast) + } + assertTrue(service.shieldTo(fromIdentity, amount = Dash.ZERO) is SdkWriteResult.NotBroadcast) + // The runtime is bound to another wallet than the one the user confirmed with. + assertTrue(service.shieldTo(fromIdentity, expectedWallet = "cd".repeat(32)) is SdkWriteResult.NotBroadcast) + assertEquals(0, source.broadcastCalls) + } + val source = readySource() + assertTrue(service(source).shieldTo(true, identityId = ByteArray(31)) is SdkWriteResult.NotBroadcast) + assertEquals(0, source.broadcastCalls) + } + + @Test + fun shieldToRecipient_sdkOutcomes_ownRecipientAndDebitPendingAreNotBroadcast_unconfirmedIsAmbiguous() = runBlocking { + val cases = listOf Unit, Boolean>>( + // rs-platform-wallet resolve_shield_recipient, before anything is built. + { + throw DashSdkError.PlatformWallet.WalletOperation( + "shielded shield failed: Shielded build error: recipient belongs to this shielded " + + "account; use the self-shield entry point (no recipient) instead" + ) + } to true, + { throw DashSdkError.PlatformWallet.ShieldedIdentityDebitPending("earlier debit unresolved") } to true, + { throw DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed("broadcast accepted") } to false, + { throw DashSdkError.NetworkError("conn dropped mid-submit") } to false + ) + for (fromIdentity in listOf(false, true)) { + for ((outcome, notBroadcast) in cases) { + val source = readySource().apply { onShield = outcome } + val result = service(source).shieldTo(fromIdentity) + if (notBroadcast) { + assertTrue(result is SdkWriteResult.NotBroadcast) + } else { + assertTrue(result is SdkWriteResult.Ambiguous) + } + // One attempt, never retried. + assertEquals(1, source.broadcastCalls) + } + } + } + // ── Pure mapping: sync status ───────────────────────────────────────── @Test @@ -3581,6 +3686,139 @@ class ShieldedBalanceServiceTest { ) } + // ── shieldFromWalletToAddress (External Send, Core → Shielded) ───────── + + @Test + fun shieldFromWalletToAddress_paysTheExternalRecipient_notTheOwnAddress() = runBlocking { + val source = readySource() + val service = service(source, progress = { caughtUpProgress() }) + + val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) + + // No tracked lock to identify: still COMPLETED, without a txid. + assertEquals(SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.COMPLETED, null)), result) + assertArrayEquals(recipientRaw43, source.lastFundRecipient) + assertEquals(Dash.COIN.duffs, source.lastFundAmountDuffs) + } + + @Test + fun shieldFromWalletToAddress_completed_reportsTheNewLocksDisplayTxId_notAnEarlierLock() = runBlocking { + val source = readySource() + val service = service(source, progress = { caughtUpProgress() }) + val earlier = PendingWalletShieldLock("aa".repeat(32) + ":0", 1, 100_000) + val built = PendingWalletShieldLock("bb".repeat(32) + ":1", 1, 100_000) + var funded = false + source.shieldLocks = { if (funded) listOf(earlier, built) else listOf(earlier) } + source.onFund = { funded = true } + + val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) + + assertEquals( + SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.COMPLETED, "bb".repeat(32))), + result + ) + } + + /** + * Pre-review finding 6: a shield to ANOTHER wallet's Orchard address is a payment, + * so its funding lock is seeded [AssetLockKind.SHIELD_EXTERNAL] (sent arrow), not + * SHIELD (the own-pool self-transfer look). + */ + @Test + fun shieldFromWalletToAddress_completed_seedsTheLockAsAnExternalShield() = runBlocking { + val source = readySource() + val seeds = mutableListOf>() + val service = service(source, progress = { caughtUpProgress() }, seedAssetLockKind = { h, k -> seeds += h to k }) + var funded = false + source.shieldLocks = { + if (funded) listOf(PendingWalletShieldLock("bb".repeat(32) + ":1", 1, 100_000)) else emptyList() + } + source.onFund = { funded = true } + + service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) + + assertEquals(listOf("bb".repeat(32) to AssetLockKind.SHIELD_EXTERNAL), seeds) + } + + /** The own-pool shield keeps SHIELD and its self-transfer look. */ + @Test + fun shieldFromWallet_completed_seedsTheLockAsAnOwnShield() = runBlocking { + val source = readySource() + val seeds = mutableListOf>() + val service = service(source, progress = { caughtUpProgress() }, seedAssetLockKind = { h, k -> seeds += h to k }) + var funded = false + source.shieldLocks = { + if (funded) listOf(PendingWalletShieldLock("cc".repeat(32) + ":0", 1, 100_000)) else emptyList() + } + source.onFund = { funded = true } + + service.shieldFromWallet(Dash.COIN) + + assertEquals(listOf("cc".repeat(32) to AssetLockKind.SHIELD), seeds) + } + + @Test + fun shieldFromWalletToAddress_otherWallet_isNotBroadcast_beforeFunding() = runBlocking { + val source = readySource() + val service = service(source, progress = { caughtUpProgress() }) + + val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, "cd".repeat(32)) + + assertTrue(result is SdkWriteResult.NotBroadcast) + assertEquals(0, source.fundCalls) + } + + @Test + fun shieldFromWalletToAddress_lockOut_stageBMayHaveSubmitted_isAmbiguous() = runBlocking { + val source = readySource() + val service = service(source, progress = { caughtUpProgress() }) + var funded = false + source.shieldLocks = { + if (funded) listOf(PendingWalletShieldLock("aa".repeat(32) + ":0", 1, 100_000)) else emptyList() + } + source.onFund = { funded = true; throw RuntimeException("transition timed out") } + + // The self-shield calls this SHIELD_PENDING_RETRY; to an external recipient the + // timed-out Type 18 may have paid them, so "it comes back to you" is not known. + val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) + + assertTrue(result is SdkWriteResult.Ambiguous) + } + + @Test + fun shieldFromWalletToAddress_lockOut_stageBDefinitivelyRejected_isPendingRetry_resumedToOwnAddress() = + runBlocking { + val source = readySource() + val service = service(source, progress = { caughtUpProgress() }) + var funded = false + source.shieldLocks = { + if (funded) listOf(PendingWalletShieldLock("aa".repeat(32) + ":0", 1, 100_000)) else emptyList() + } + source.onFund = { funded = true; throw DashSdkError.InvalidParameter("shield transition rejected") } + + val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) + // A lock that did not pay the recipient carries no txid. + assertEquals( + SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY, null)), + result + ) + + // The sweep finishes the externally-addressed lock to the SENDER's own address. + assertEquals(1, service.resumePendingWalletShields()) + assertArrayEquals(source.defaultAddress, source.lastResumeRecipient) + assertFalse(recipientRaw43.contentEquals(source.lastResumeRecipient)) + } + + @Test + fun shieldFromWalletToAddress_malformedAddress_isNotBroadcast() = runBlocking { + val source = readySource() + val service = service(source, progress = { caughtUpProgress() }) + + val result = service.shieldFromWalletToAddress("tdash1notanaddress", Dash.COIN, walletIdHex) + assertTrue(result is SdkWriteResult.NotBroadcast) + assertEquals(0, source.fundCalls) + } + @Test fun shieldFromWallet_definitiveRejection_noNewLock_isNotBroadcast() = runBlocking { val source = readySource() diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt new file mode 100644 index 0000000000..1144d7510e --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -0,0 +1,1482 @@ +/* + * Copyright 2026 Dash Core Group. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.schildbach.wallet.ui.payments.send + +import androidx.lifecycle.SavedStateHandle +import de.schildbach.wallet.service.platform.sdk.Bech32m +import de.schildbach.wallet.service.platform.sdk.DestinationParse +import de.schildbach.wallet.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.ExternalSendService +import de.schildbach.wallet.service.platform.sdk.ExternalSendServiceImpl +import de.schildbach.wallet.service.platform.sdk.FeeEstimate +import de.schildbach.wallet.service.platform.sdk.IdentityResolution +import de.schildbach.wallet.service.platform.sdk.NotSentReason +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.SendDestination +import de.schildbach.wallet.service.platform.sdk.SendSupport +import de.schildbach.wallet.service.platform.sdk.WITHDRAWAL_CORE_FEE_DUFFS +import de.schildbach.wallet.ui.more.connections.protocol.DashConnectUri +import de.schildbach.wallet.ui.shielded.toKeypadString +import de.schildbach.wallet_test.R +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.dash.wallet.common.data.WalletUIConfig +import org.dash.wallet.common.data.entity.ExchangeRate +import org.dash.wallet.common.money.Dash +import org.dash.wallet.common.payments.parsers.AddressNetwork +import org.dash.wallet.common.payments.parsers.Base58 +import org.dash.wallet.common.services.ExchangeRatesProvider +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ExternalSendViewModelTest { + + private val network = AddressNetwork.DASH_TESTNET + private val hash20 = ByteArray(20) { (it + 1).toByte() } + private val coreAddress = Base58.encodeChecked(network.addressHeader, hash20) + private val mainnetCoreAddress = Base58.encodeChecked(AddressNetwork.DASH_MAINNET.addressHeader, hash20) + private val platformAddress = requireNotNull(Bech32m.encode("tdash", byteArrayOf(0xb0.toByte()) + hash20)) + + /** A P2SH Platform address: the one destination Core cannot pay (P2PKH-only funding). */ + private val platformP2shAddress = requireNotNull(Bech32m.encode("tdash", byteArrayOf(0x80.toByte()) + hash20)) + private val shieldedAddress = + requireNotNull(Bech32m.encode("tdash", byteArrayOf(0x10) + ByteArray(43) { (it * 3 + 7).toByte() })) + private val identityId = Base58.encode(ByteArray(32) { (255 - it).toByte() }) + + private val oneDash = Dash.COIN + private val twoDash = Dash.COIN * 2L + + /** A fake service: every answer is a field the test sets; every send is recorded. */ + private class FakeService : ExternalSendService { + val balances = SendBalance.entries.associateWith { MutableStateFlow(null) } + val hasIdentity = MutableStateFlow(false) + var ownIdentity: Boolean? = false + var resolution: IdentityResolution = IdentityResolution.Found("alice") + var fee: FeeEstimate? = null + val max = mutableMapOf() + + /** When set for a source, its [maxSendable] suspends on it (a slow Max read). */ + val maxGates = mutableMapOf>() + var sendGate: CompletableDeferred? = null + var sendResult: ExternalSendResult = ExternalSendResult.Sent(null) + val sends = mutableListOf() + var walletId: String? = WALLET_A + + override fun currentWalletIdOrNull(): String? = walletId + override fun observeBalance(source: SendBalance): Flow = balances.getValue(source) + override fun observeHasIdentity(): Flow = hasIdentity + override suspend fun isOwnIdentity(identityIdBase58: String): Boolean? = ownIdentity + override suspend fun resolveIdentity(identityIdBase58: String): IdentityResolution = resolution + override suspend fun estimateFee(source: SendBalance, destinationKind: SendBalance) = fee + override suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? { + maxGates[source]?.await() + return max[source] + } + override suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + expectedWalletIdHex: String? + ): ExternalSendResult { + sends += ExternalSendRequest(source, destination, amount, isMax, expectedWalletIdHex) + return sendGate?.await() ?: sendResult + } + + var platformResumes = 0 + override suspend fun resumePendingPlatformFunding(): Int { + platformResumes++ + return 0 + } + } + + /** The persisted in-flight flag; [failReads]/[failWrites] make the store throw. */ + private class FakeMarker : ExternalSendInFlightMarker { + var value = false + var failReads = false + var failWrites = false + val log = mutableListOf() + + /** When set, [clear] suspends on it (after counting the call in [clearCalls]). */ + var clearGate: CompletableDeferred? = null + var clearCalls = 0 + + override suspend fun isSet(): Boolean { + if (failReads) throw java.io.IOException("datastore") + return value + } + + /** When set, [set] suspends on it before writing (a slow marker write). */ + var setGate: CompletableDeferred? = null + + override suspend fun set() { + setGate?.await() + if (failWrites) throw java.io.IOException("datastore") + log += "set" + value = true + } + + override suspend fun clear() { + clearCalls++ + clearGate?.await() + if (failWrites) throw java.io.IOException("datastore") + log += "clear" + value = false + } + } + + private companion object { + const val WALLET_A = "wallet-a" + } + + private val service = FakeService() + private val marker = FakeMarker() + private lateinit var executor: ExternalSendExecutor + + private val mainDispatcher = UnconfinedTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(mainDispatcher) + executor = newExecutor() + } + + private fun newExecutor() = ExternalSendExecutor(service, marker, CoroutineScope(UnconfinedTestDispatcher())) + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun buildViewModel( + savedState: SavedStateHandle = SavedStateHandle(), + rate: ExchangeRate? = null + ): ExternalSendViewModel { + val walletUIConfig = mockk { + every { observe(WalletUIConfig.SELECTED_CURRENCY) } returns flowOf("USD") + } + val rates = mockk { + every { observeExchangeRate(any()) } returns flowOf(rate) + } + return ExternalSendViewModel(service, executor, walletUIConfig, rates, savedState, network) + } + + private fun ExternalSendViewModel.goToAmount(address: String) { + onAddressChanged(address) + onAddressContinue() + } + + private fun ExternalSendViewModel.type(amount: String) { + amount.forEach { onKeyInput(it.toString()) } + } + + // ── address step ───────────────────────────────────────────────────────── + + @Test + fun address_states_gateContinue_andShowAnErrorOnlyForBadInput() { + val viewModel = buildViewModel() + with(viewModel.uiState.value) { + assertEquals(DestinationParse.Empty, addressParse) + assertFalse(addressError) + assertFalse(canContinueAddress) + } + + viewModel.onAddressChanged("not an address") + assertTrue(viewModel.uiState.value.addressError) + assertFalse(viewModel.uiState.value.canContinueAddress) + + viewModel.onAddressChanged(mainnetCoreAddress) + assertEquals(DestinationParse.WrongNetwork, viewModel.uiState.value.addressParse) + assertTrue(viewModel.uiState.value.addressError) + assertFalse(viewModel.uiState.value.canContinueAddress) + + viewModel.onAddressContinue() + assertEquals(ExternalSendStep.ADDRESS, viewModel.uiState.value.step) + + viewModel.onAddressChanged(coreAddress) + assertFalse(viewModel.uiState.value.addressError) + assertTrue(viewModel.uiState.value.canContinueAddress) + viewModel.onAddressContinue() + assertEquals(ExternalSendStep.AMOUNT, viewModel.uiState.value.step) + assertEquals(SendDestination.Core(coreAddress), viewModel.uiState.value.destination) + } + + @Test + fun clipboard_offersOnlyDestinationsOfThisNetwork_andPastesTheTappedOne() { + val viewModel = buildViewModel() + viewModel.onClipboardRead("pay $shieldedAddress or $mainnetCoreAddress please") + assertTrue(viewModel.uiState.value.clipboardShown) + assertEquals(listOf(shieldedAddress), viewModel.uiState.value.clipboardEntries) + + viewModel.onClipboardEntrySelected(shieldedAddress) + assertEquals(shieldedAddress, viewModel.uiState.value.addressInput) + assertFalse(viewModel.uiState.value.clipboardShown) + assertTrue(viewModel.uiState.value.canContinueAddress) + } + + @Test + fun clipboard_withNoAddress_showsNoEntries() { + val viewModel = buildViewModel() + viewModel.onClipboardRead(null) + assertTrue(viewModel.uiState.value.clipboardShown) + assertTrue(viewModel.uiState.value.clipboardEntries.isEmpty()) + } + + // ── source choice ──────────────────────────────────────────────────────── + + @Test + fun initialSource_isTheFirstSupported_inCoreShieldedPlatformIdentityOrder() { + val core = buildViewModel().apply { goToAmount(coreAddress) } + assertEquals(SendBalance.CORE, core.uiState.value.source) + + // Core pays a P2PKH Platform address (fundFromAssetLockExternal) ... + val platform = buildViewModel().apply { goToAmount(platformAddress) } + assertEquals(SendBalance.CORE, platform.uiState.value.source) + + // ... but not a P2SH one; Shielded can. + val p2sh = buildViewModel().apply { goToAmount(platformP2shAddress) } + assertEquals(SendBalance.SHIELDED, p2sh.uiState.value.source) + } + + @Test + fun initialSource_forAnIdentity_isCoreOnlyWhenTheIdentityIsOurOwn() { + service.hasIdentity.value = true + service.ownIdentity = false + val other = buildViewModel().apply { goToAmount(identityId) } + assertEquals(SendBalance.SHIELDED, other.uiState.value.source) + // Core tops up only a managed identity; Platform tops up anyone's (platform#5860). + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, other.uiState.value.supportOf(SendBalance.CORE)) + assertEquals(SendSupport.SUPPORTED, other.uiState.value.supportOf(SendBalance.PLATFORM)) + other.onSourceSelected(SendBalance.CORE) + assertEquals(SendBalance.SHIELDED, other.uiState.value.source) + other.onSourceSelected(SendBalance.PLATFORM) + assertEquals(SendBalance.PLATFORM, other.uiState.value.source) + + service.ownIdentity = true + val own = buildViewModel().apply { goToAmount(identityId) } + assertEquals(SendBalance.CORE, own.uiState.value.source) + assertEquals(SendSupport.SUPPORTED, own.uiState.value.supportOf(SendBalance.PLATFORM)) + + // Could not tell: Core fails closed; Platform does not depend on it (the send + // refuses when the managed set is unreadable). + service.ownIdentity = null + val unknown = buildViewModel().apply { goToAmount(identityId) } + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, unknown.uiState.value.supportOf(SendBalance.CORE)) + assertEquals(SendSupport.SUPPORTED, unknown.uiState.value.supportOf(SendBalance.PLATFORM)) + } + + @Test + fun sourceSelection_ignoresUnsupportedAndUnlistedSources() { + val viewModel = buildViewModel() + viewModel.goToAmount(platformP2shAddress) + + viewModel.onSourceSelected(SendBalance.CORE) + assertEquals(SendBalance.SHIELDED, viewModel.uiState.value.source) + + // No identity: the Identity row is not listed and cannot be picked. + assertFalse(SendBalance.IDENTITY in viewModel.uiState.value.sources) + viewModel.onSourceSelected(SendBalance.IDENTITY) + assertEquals(SendBalance.SHIELDED, viewModel.uiState.value.source) + + viewModel.onSourceSelected(SendBalance.PLATFORM) + assertEquals(SendBalance.PLATFORM, viewModel.uiState.value.source) + assertTrue(viewModel.uiState.value.sourceChosenByUser) + + service.hasIdentity.value = true + assertTrue(SendBalance.IDENTITY in viewModel.uiState.value.sources) + viewModel.onSourceSelected(SendBalance.IDENTITY) + assertEquals(SendBalance.IDENTITY, viewModel.uiState.value.source) + } + + @Test + fun switchingSource_dropsTheOldBalanceAndMax() { + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + service.max[SendBalance.SHIELDED] = oneDash + val viewModel = buildViewModel() + viewModel.goToAmount(platformP2shAddress) + assertEquals(twoDash, viewModel.uiState.value.balance) + assertEquals(oneDash, viewModel.uiState.value.maxSendable) + + viewModel.onSourceSelected(SendBalance.PLATFORM) + assertNull(viewModel.uiState.value.balance) + assertNull(viewModel.uiState.value.maxSendable) + } + + // ── Max ────────────────────────────────────────────────────────────────── + + @Test + fun max_isUnavailableWhileUnknown_andSetsTheExactMaxWhenKnown() { + service.balances.getValue(SendBalance.CORE).value = twoDash + service.max[SendBalance.CORE] = null + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + assertNull(viewModel.uiState.value.maxSendable) + viewModel.onMaxClick() + assertFalse(viewModel.uiState.value.isMax) + assertEquals(Dash.ZERO, viewModel.uiState.value.amount) + + service.max[SendBalance.CORE] = Dash(199_990_000) + service.balances.getValue(SendBalance.CORE).value = Dash(200_000_001) + viewModel.onMaxClick() + assertTrue(viewModel.uiState.value.isMax) + assertEquals(Dash(199_990_000), viewModel.uiState.value.amount) + + viewModel.onKeyInput("back") + assertFalse(viewModel.uiState.value.isMax) + } + + // ── Continue gating ────────────────────────────────────────────────────── + + @Test + fun continue_needsAKnownBalance_andAnAmountWithinIt() { + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + assertFalse("unknown balance", viewModel.uiState.value.canContinueAmount) + + service.balances.getValue(SendBalance.CORE).value = twoDash + assertTrue(viewModel.uiState.value.canContinueAmount) + + viewModel.type("0") + assertEquals(Dash.COIN * 10L, viewModel.uiState.value.amount) + assertFalse("over the balance", viewModel.uiState.value.canContinueAmount) + } + + @Test + fun continue_isBoundedByTheMaxSendable_whenKnown() { + service.balances.getValue(SendBalance.CORE).value = twoDash + service.max[SendBalance.CORE] = oneDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1.5") + assertFalse(viewModel.uiState.value.canContinueAmount) + } + + @Test + fun platformToCore_isBoundedByItsMaxOnly_neverByTheBalance() { + // MO-1121 QA: 0.02039398 on Platform; the withdrawal fee reserve leaves 0.01638708. + val cap = Dash(1_638_708L) + service.balances.getValue(SendBalance.PLATFORM).value = Dash(2_039_398L) + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.onSourceSelected(SendBalance.PLATFORM) + assertEquals(SendBalance.PLATFORM, viewModel.uiState.value.source) + + // Max unknown (unreadable or none): Continue is blocked, not bounded by the balance. + assertNull(viewModel.uiState.value.maxSendable) + viewModel.type("0.01") + assertNull(viewModel.uiState.value.limit) + assertFalse("unknown max", viewModel.uiState.value.canContinueAmount) + + // Known: the cap bounds the amount, and Max fills exactly the cap. + service.max[SendBalance.PLATFORM] = cap + service.balances.getValue(SendBalance.PLATFORM).value = Dash(2_039_399L) + assertEquals(cap, viewModel.uiState.value.limit) + assertTrue(viewModel.uiState.value.canContinueAmount) + viewModel.onMaxClick() + assertTrue(viewModel.uiState.value.isMax) + assertEquals(cap, viewModel.uiState.value.amount) + assertTrue(viewModel.uiState.value.canContinueAmount) + + // The QA amount: under the balance, over the cap. + val over = ExternalSendUIState( + step = ExternalSendStep.AMOUNT, + destination = SendDestination.Core(coreAddress), + source = SendBalance.PLATFORM, + amountText = "0.01739398", + balance = Dash(2_039_398L), + maxSendable = cap + ) + assertTrue(over.exceedsBalance) + assertFalse(over.canContinueAmount) + assertTrue(over.copy(amountText = "0.01638708").canContinueAmount) + assertFalse(over.copy(amountText = "0.01638709").canContinueAmount) + // Other pairs keep the balance as the bound while their Max is unknown. + assertTrue(over.copy(source = SendBalance.SHIELDED, maxSendable = null).canContinueAmount) + } + + @Test + fun continue_isBlockedForAnUnsupportedPair() { + val state = ExternalSendUIState( + step = ExternalSendStep.AMOUNT, + destination = SendDestination.Platform(platformP2shAddress), + source = SendBalance.CORE, + amountText = "1", + balance = twoDash + ) + assertFalse(state.canContinueAmount) + // A P2PKH Platform address is payable from Core. + assertTrue(state.copy(destination = SendDestination.Platform(platformAddress)).canContinueAmount) + assertTrue(state.copy(source = SendBalance.SHIELDED).canContinueAmount) + } + + @Test + fun continue_isAllowedForThePairsTheInt37SdkAdded() { + val state = ExternalSendUIState( + step = ExternalSendStep.AMOUNT, + destination = SendDestination.Core(coreAddress), + source = SendBalance.PLATFORM, + amountText = "1", + balance = twoDash, + maxSendable = twoDash, + hasIdentity = true + ) + // Platform → Core (partial withdrawal, bounded by its known Max), Platform / Identity → + // Shielded (third-party shields). + assertTrue(state.canContinueAmount) + assertFalse(state.copy(maxSendable = null).canContinueAmount) + assertTrue(state.copy(destination = SendDestination.Shielded(shieldedAddress)).canContinueAmount) + assertTrue( + state.copy(source = SendBalance.IDENTITY, destination = SendDestination.Shielded(shieldedAddress)) + .canContinueAmount + ) + } + + @Test + fun continue_toAnIdentity_needsItToBeFound_andUnknownCanBeRetried() { + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + service.resolution = IdentityResolution.NotFound + val viewModel = buildViewModel() + viewModel.goToAmount(identityId) + viewModel.type("1") + assertEquals(IdentityResolution.NotFound, viewModel.uiState.value.identityResolution) + assertFalse(viewModel.uiState.value.canContinueAmount) + + service.resolution = IdentityResolution.Unknown + viewModel.onRetryIdentity() + assertEquals(IdentityResolution.Unknown, viewModel.uiState.value.identityResolution) + assertFalse(viewModel.uiState.value.canContinueAmount) + + service.resolution = IdentityResolution.Found(null) + viewModel.onRetryIdentity() + assertTrue(viewModel.uiState.value.canContinueAmount) + } + + // ── confirm and send ───────────────────────────────────────────────────── + + @Test + fun confirm_carriesTheExactRequest_andTheFee() { + service.balances.getValue(SendBalance.CORE).value = twoDash + service.max[SendBalance.CORE] = twoDash + service.fee = FeeEstimate(Dash(1_000), exact = false) + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.onMaxClick() + viewModel.onAmountContinue() + + val confirm = requireNotNull(viewModel.uiState.value.confirm) + assertEquals( + ExternalSendRequest(SendBalance.CORE, SendDestination.Core(coreAddress), twoDash, isMax = true, WALLET_A), + confirm.request + ) + assertEquals(service.fee, confirm.fee) + assertFalse(confirm.feeLoading) + // A Core Max is the drain: the fee comes out of the amount (Basic's sendAllBalance). + assertTrue(confirm.feeIncluded) + assertEquals(twoDash - Dash(1_000), confirm.recipientAmount) + assertEquals(twoDash, confirm.total) + assertEquals(confirm.request, viewModel.confirmedRequest()) + } + + @Test + fun aCoreMaxDrain_withTheFeeUnknown_hasNoRecipientAmount() { + val drain = ExternalSendConfirm( + ExternalSendRequest(SendBalance.CORE, SendDestination.Core(coreAddress), twoDash, isMax = true, WALLET_A), + fee = null, + feeLoading = true + ) + assertTrue(drain.feeIncluded) + // Not the gross amount: that would overstate what the recipient receives. + assertNull(drain.recipientAmount) + assertNull(drain.copy(feeLoading = false).recipientAmount) + // The total of a drain is the confirmed amount itself, fee or not. + assertEquals(twoDash, drain.total) + assertEquals(twoDash - Dash(1_000), drain.copy(fee = FeeEstimate(Dash(1_000), exact = true), feeLoading = false).recipientAmount) + } + + @Test + fun platformToCore_aFailedMaxRead_isRetried_whileTheBalanceIsUnchanged() { + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + service.max[SendBalance.PLATFORM] = null + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.onSourceSelected(SendBalance.PLATFORM) + viewModel.type("1") + assertNull(viewModel.uiState.value.maxSendable) + // Max is the bound for Platform → Core: unknown blocks Continue. + assertFalse(viewModel.uiState.value.canContinueAmount) + + // The balance does not change (the feed is distinct); only the retry can recover. + service.max[SendBalance.PLATFORM] = oneDash + mainDispatcher.scheduler.advanceTimeBy(ExternalSendServiceImpl.BALANCE_POLL_MS + 1) + mainDispatcher.scheduler.runCurrent() + + assertEquals(oneDash, viewModel.uiState.value.maxSendable) + assertTrue(viewModel.uiState.value.canContinueAmount) + } + + @Test + fun anUnknownFee_hasNoTotal() { + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + service.fee = null + val viewModel = buildViewModel() + viewModel.goToAmount(platformAddress) + viewModel.onSourceSelected(SendBalance.PLATFORM) + viewModel.type("1") + viewModel.onAmountContinue() + val confirm = requireNotNull(viewModel.uiState.value.confirm) + assertNull(confirm.fee) + assertFalse(confirm.feeLoading) + assertNull(confirm.total) + } + + @Test + fun submit_sendsTheCapturedRequest_andRefusesAnyOther() { + service.balances.getValue(SendBalance.CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + val captured = requireNotNull(viewModel.confirmedRequest()) + + assertFalse(viewModel.submit(captured.copy(amount = twoDash))) + assertTrue(service.sends.isEmpty()) + + assertTrue(viewModel.submit(captured)) + assertEquals(listOf(captured), service.sends) + assertNull(viewModel.uiState.value.confirm) + } + + @Test + fun aRunningSend_showsSending_andTheResultWhenItLands_evenOnALaterVisit() { + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + val gate = CompletableDeferred() + service.sendGate = gate + val viewModel = buildViewModel() + viewModel.goToAmount(shieldedAddress) + viewModel.onSourceSelected(SendBalance.SHIELDED) + viewModel.type("1") + viewModel.onAmountContinue() + assertTrue(viewModel.submit(requireNotNull(viewModel.confirmedRequest()))) + assertEquals(ExternalSendStatus.Sending(shieldedLeg = true), viewModel.uiState.value.status) + assertFalse(viewModel.uiState.value.canContinueAmount) + // Leaving while sending is allowed; it does not cancel the send. + assertFalse(viewModel.onBack()) + + // A later visit (new ViewModel) picks the same send up. + val later = buildViewModel() + assertEquals(ExternalSendStatus.Sending(shieldedLeg = true), later.uiState.value.status) + gate.complete(ExternalSendResult.Sent("txid")) + assertEquals(ExternalSendStatus.Done(ExternalSendResult.Sent("txid")), later.uiState.value.status) + } + + @Test + fun eachResult_mapsToItsOwnOutcome() { + val results = listOf( + ExternalSendResult.Sent(null), + ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), + ExternalSendResult.MayHaveGoneThrough, + ExternalSendResult.InterruptedFundsReturnToShielded + ) + results.forEach { result -> + service.sendResult = result + service.balances.getValue(SendBalance.CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + assertTrue(viewModel.submit(requireNotNull(viewModel.confirmedRequest()))) + assertEquals(ExternalSendStatus.Done(result), viewModel.uiState.value.status) + viewModel.onResultAcknowledged() + assertEquals(ExternalSendStatus.Idle, viewModel.uiState.value.status) + } + + assertEquals(R.string.external_send_sent_title, resultContentFor(results[0]).title) + assertEquals(R.string.external_send_not_sent_insufficient_funds, resultContentFor(results[1]).message) + assertEquals(R.string.external_send_interrupted_message, resultContentFor(results[3]).message) + } + + @Test + fun mayHaveGoneThrough_isTerminal_withNoRetry() { + service.sendResult = ExternalSendResult.MayHaveGoneThrough + service.balances.getValue(SendBalance.CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + assertTrue(viewModel.submit(request)) + + val content = resultContentFor(ExternalSendResult.MayHaveGoneThrough) + assertEquals(R.string.external_send_ambiguous_message, content.message) + assertEquals(R.string.external_send_close, content.button) + assertNotEquals(R.string.button_retry, content.button) + // Unacknowledged: nothing can be confirmed or sent again. + assertFalse(viewModel.uiState.value.canContinueAmount) + assertNull(viewModel.confirmedRequest()) + assertFalse(executor.submit(request)) + assertEquals(1, service.sends.size) + } + + @Test + fun notSent_returnsToEditing() { + service.sendResult = ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED) + service.balances.getValue(SendBalance.CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + viewModel.submit(requireNotNull(viewModel.confirmedRequest())) + assertEquals(R.string.external_send_edit, resultContentFor(ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED)).button) + + viewModel.onResultAcknowledged() + assertEquals(ExternalSendStep.AMOUNT, viewModel.uiState.value.step) + assertFalse(viewModel.uiState.value.finished) + assertTrue(viewModel.uiState.value.formEditable) + assertTrue(viewModel.uiState.value.canContinueAmount) + } + + @Test + fun anAcknowledgedOutcome_endsTheFlow_andTheFormStaysInert_onceTheExecutorIsIdle() { + for (result in listOf( + ExternalSendResult.Sent("txid"), + ExternalSendResult.MayHaveGoneThrough, + ExternalSendResult.InterruptedFundsReturnToShielded + )) { + executor = newExecutor() + service.sendResult = result + service.max[SendBalance.CORE] = oneDash + val saved = SavedStateHandle() + val clearGate = CompletableDeferred() + marker.clearGate = clearGate + val viewModel = sendOnce(buildViewModel(saved)) + assertEquals(ExternalSendStatus.Done(result), viewModel.uiState.value.status) + + viewModel.onResultAcknowledged() + // Acknowledging (the marker still clearing): inert. + assertTrue(viewModel.uiState.value.finished) + assertFalse(viewModel.uiState.value.canContinueAmount) + + clearGate.complete(Unit) + marker.clearGate = null + assertEquals(ExternalSendExecution.Idle, executor.state.value) + with(viewModel.uiState.value) { + assertEquals(ExternalSendStatus.Idle, status) + assertFalse(formEditable) + assertFalse(canContinueAmount) + assertFalse(canContinueAddress) + } + // Nothing in the form reacts, and back leaves instead of reopening the address page. + val amountText = viewModel.uiState.value.amountText + viewModel.onKeyInput("5") + viewModel.onMaxClick() + viewModel.onShowSourceSheet() + viewModel.onAmountContinue() + with(viewModel.uiState.value) { + assertEquals(amountText, this.amountText) + assertFalse(isMax) + assertFalse(showSourceSheet) + assertNull(confirm) + } + assertNull(viewModel.confirmedRequest()) + assertFalse(viewModel.onBack()) + + // A process restore after acknowledging cannot re-enable the form. + val restored = buildViewModel(saved) + assertTrue(restored.uiState.value.finished) + assertFalse(restored.uiState.value.canContinueAmount) + service.sends.clear() + marker.value = false + } + } + + // ── prefill and restore ────────────────────────────────────────────────── + + @Test + fun aScannedDashUri_opensTheAmountStep_withItsAmount() { + val viewModel = buildViewModel( + SavedStateHandle(mapOf(ExternalSendViewModel.ARG_PREFILL to "dash:$coreAddress?amount=0.5")) + ) + with(viewModel.uiState.value) { + assertEquals(ExternalSendStep.AMOUNT, step) + assertEquals(SendDestination.Core(coreAddress), destination) + assertEquals(Dash(50_000_000), amount) + } + } + + @Test + fun savedState_restoresAddressAmountAndSource() { + val saved = SavedStateHandle() + val first = buildViewModel(saved) + first.goToAmount(platformAddress) + first.onSourceSelected(SendBalance.PLATFORM) + first.type("1.25") + + val restored = buildViewModel(saved) + with(restored.uiState.value) { + assertEquals(ExternalSendStep.AMOUNT, step) + assertEquals(platformAddress, addressInput) + assertEquals(SendDestination.Platform(platformAddress), destination) + assertEquals("1.25", amountText) + assertEquals(SendBalance.PLATFORM, source) + assertTrue(sourceChosenByUser) + } + } + + @Test + fun savedState_restoresAMaxAmountOnAUserChosenSource() { + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + service.max[SendBalance.PLATFORM] = oneDash + val saved = SavedStateHandle() + val first = buildViewModel(saved) + first.goToAmount(platformAddress) + first.onSourceSelected(SendBalance.PLATFORM) + first.onMaxClick() + + val restored = buildViewModel(saved) + assertEquals(SendBalance.PLATFORM, restored.uiState.value.source) + assertTrue(restored.uiState.value.isMax) + assertEquals(oneDash, restored.uiState.value.amount) + } + + @Test + fun back_closesSheets_thenReturnsToTheAddress_thenLeaves() { + service.balances.getValue(SendBalance.CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.onShowSourceSheet() + assertTrue(viewModel.onBack()) + assertFalse(viewModel.uiState.value.showSourceSheet) + assertTrue(viewModel.onBack()) + assertEquals(ExternalSendStep.ADDRESS, viewModel.uiState.value.step) + assertFalse(viewModel.onBack()) + } + + // ── helpers ────────────────────────────────────────────────────────────── + + @Test + fun shorten_keepsTheFirst7AndLast8() { + assertEquals("tdash1z...lrs27eg4", ExternalSendViewModel.shorten("tdash1zqumn3c48sdenak7qr0f8jplrs27eg4")) + assertEquals("short", ExternalSendViewModel.shorten("short")) + } + + @Test + fun scanAction_routesEachKindOfCode() { + val connect = { input: String -> input.startsWith("dash-key:") } + assertEquals( + AdvancedScanAction.DashConnect("dash-key:abc"), + AdvancedSendViewModel.scanActionFor("dash-key:abc", network, supportsConnect = true, isDashConnect = connect) + ) + assertEquals( + AdvancedScanAction.Error(wrongNetwork = false), + AdvancedSendViewModel.scanActionFor("dash-key:abc", network, supportsConnect = false, isDashConnect = connect) + ) + val bip70 = "dash:$coreAddress?r=https://example.com/invoice" + assertEquals( + AdvancedScanAction.PaymentRequest(bip70), + AdvancedSendViewModel.scanActionFor(bip70, network, true, connect) + ) + val uri = "dash:$coreAddress?amount=1" + assertEquals(AdvancedScanAction.ExternalSend(uri), AdvancedSendViewModel.scanActionFor(uri, network, true, connect)) + assertEquals( + AdvancedScanAction.ExternalSend(identityId), + AdvancedSendViewModel.scanActionFor(identityId, network, true, connect) + ) + assertEquals( + AdvancedScanAction.Error(wrongNetwork = true), + AdvancedSendViewModel.scanActionFor(mainnetCoreAddress, network, true, connect) + ) + } + + @Test + fun scanAction_withTheSharedPredicate_routesEveryDashConnectCarrier() { + // The fragment passes DashConnectUri::isConnectUri, as the Basic Send tab does. + for (input in listOf("dash-key:abc", "dash-st:abc", "dashpay://connect?x=1")) { + assertEquals( + AdvancedScanAction.DashConnect(input), + AdvancedSendViewModel.scanActionFor(input, network, true, DashConnectUri::isConnectUri) + ) + } + assertEquals( + AdvancedScanAction.ExternalSend(identityId), + AdvancedSendViewModel.scanActionFor(identityId, network, true, DashConnectUri::isConnectUri) + ) + } + + // ── review round 1 regressions ─────────────────────────────────────────── + + @Test + fun confirm_aNonMaxSend_paysTheFeeOnTop_andOnlyACoreMaxIsFeeInclusive() { + service.balances.getValue(SendBalance.CORE).value = twoDash + service.fee = FeeEstimate(Dash(1_000), exact = false) + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + val confirm = requireNotNull(viewModel.uiState.value.confirm) + assertFalse(confirm.feeIncluded) + assertEquals(oneDash, confirm.recipientAmount) + assertEquals(oneDash + Dash(1_000), confirm.total) + + // A Max to a Shielded address is not a drain: the pool fee is paid on top. + val shieldMax = ExternalSendConfirm( + ExternalSendRequest(SendBalance.CORE, SendDestination.Shielded(shieldedAddress), oneDash, true, WALLET_A), + FeeEstimate(Dash(52_001), exact = false), + feeLoading = false + ) + assertFalse(shieldMax.feeIncluded) + assertEquals(oneDash, shieldMax.recipientAmount) + assertEquals(oneDash + Dash(52_001), shieldMax.total) + } + + @Test + fun confirm_withdrawalsToCore_payTheRecipientTheAmount_exceptAShieldedMax_whichCarriesTheCoreFee() { + val toCore = SendDestination.Core(coreAddress) + // Shielded → Core, not Max: the Core fee is withdrawn on top (and is part of the fee). + val shieldedSend = ExternalSendConfirm( + ExternalSendRequest(SendBalance.SHIELDED, toCore, oneDash, false, WALLET_A), + FeeEstimate(Dash(2_191), exact = false), + feeLoading = false + ) + assertFalse(shieldedSend.coreFeeIncluded) + assertEquals(oneDash, shieldedSend.recipientAmount) + assertEquals(oneDash + Dash(2_191), shieldedSend.total) + + // Shielded → Core Max: the Max itself is withdrawn, the recipient gets it minus the Core fee. + val shieldedMax = shieldedSend.copy(request = shieldedSend.request.copy(isMax = true)) + assertTrue(shieldedMax.coreFeeIncluded) + assertFalse(shieldedMax.feeIncluded) + assertEquals(oneDash - Dash(WITHDRAWAL_CORE_FEE_DUFFS), shieldedMax.recipientAmount) + // What leaves the balance: the Max plus the pool fee (2 191 − 190). + assertEquals(oneDash + Dash(2_001), shieldedMax.total) + + // Platform / Identity → Core: the recipient gets the confirmed amount; the fee is unknown. + for (source in listOf(SendBalance.PLATFORM, SendBalance.IDENTITY)) { + val confirm = ExternalSendConfirm( + ExternalSendRequest(source, toCore, oneDash, false, WALLET_A), + null, + feeLoading = false + ) + assertFalse(confirm.coreFeeIncluded) + assertEquals(oneDash, confirm.recipientAmount) + assertNull(confirm.total) + } + } + + @Test + fun confirm_capturesTheBoundWallet_andTheSendCarriesIt_evenIfAnotherIsBoundLater() { + service.balances.getValue(SendBalance.CORE).value = twoDash + val viewModel = buildViewModel() + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + val request = requireNotNull(viewModel.confirmedRequest()) + assertEquals(WALLET_A, request.expectedWalletIdHex) + + service.walletId = "wallet-b" + assertTrue(viewModel.submit(request)) + assertEquals(WALLET_A, service.sends.single().expectedWalletIdHex) + } + + private fun sendOnce(viewModel: ExternalSendViewModel = buildViewModel()): ExternalSendViewModel { + service.balances.getValue(SendBalance.CORE).value = twoDash + viewModel.goToAmount(coreAddress) + viewModel.type("1") + viewModel.onAmountContinue() + assertTrue(viewModel.submit(requireNotNull(viewModel.confirmedRequest()))) + return viewModel + } + + @Test + fun inFlightMarker_isWrittenBeforeTheSend_keptOnSentUntilAcknowledged_clearedOnNotSent() { + val gate = CompletableDeferred() + service.sendGate = gate + val viewModel = sendOnce() + assertEquals(1, service.sends.size) + assertTrue("set before the service runs", marker.value) + gate.complete(ExternalSendResult.Sent("txid")) + // Sent keeps the restart protection until the user has seen it. + assertTrue(marker.value) + assertEquals(listOf("set"), marker.log) + // A process death now restarts into the conservative warning, never the editable form. + assertEquals(ExternalSendExecution.InterruptedByRestart, newExecutor().state.value) + + viewModel.onResultAcknowledged() + assertFalse(marker.value) + assertEquals(listOf("set", "clear"), marker.log) + assertEquals(ExternalSendExecution.Idle, executor.state.value) + service.sendGate = null + service.sendResult = ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED) + marker.log.clear() + sendOnce() + assertFalse(marker.value) + assertEquals(listOf("set", "clear"), marker.log) + } + + @Test + fun inFlightMarker_survivesAnUnknownOutcome_untilAcknowledged() { + for (result in listOf(ExternalSendResult.MayHaveGoneThrough, ExternalSendResult.InterruptedFundsReturnToShielded)) { + marker.value = false + executor = newExecutor() + service.sendResult = result + val viewModel = sendOnce() + assertTrue(marker.value) + viewModel.onResultAcknowledged() + assertFalse(marker.value) + assertEquals(ExternalSendExecution.Idle, executor.state.value) + } + } + + @Test + fun aDoubleAcknowledgement_clearsOnce_andCannotClearALaterSendsMarker() { + service.sendResult = ExternalSendResult.Sent("txid") + val viewModel = sendOnce() + val clearGate = CompletableDeferred() + marker.clearGate = clearGate + + executor.acknowledge() + // Claimed: not Idle (no new send yet), no result dialog, the form inert. + assertEquals(ExternalSendExecution.Acknowledging, executor.state.value) + assertEquals(ExternalSendStatus.Restoring, viewModel.uiState.value.status) + executor.acknowledge() + viewModel.onResultAcknowledged() + assertEquals(1, marker.clearCalls) + assertFalse(executor.submit(service.sends.single())) + + clearGate.complete(Unit) + marker.clearGate = null + assertEquals(ExternalSendExecution.Idle, executor.state.value) + assertEquals(1, marker.clearCalls) + + // A later send's marker survives a stale acknowledgement. + val gate = CompletableDeferred() + service.sendGate = gate + assertTrue(executor.submit(service.sends.single())) + executor.acknowledge() + assertTrue(marker.value) + assertEquals(1, marker.clearCalls) + gate.complete(ExternalSendResult.MayHaveGoneThrough) + assertTrue(marker.value) + } + + // ── Reset Wallet ───────────────────────────────────────────────────────── + + @Test + fun aWalletWipe_forgetsAnUnacknowledgedOutcome_soTheNextWalletNeitherShowsNorOpensIt() { + val txId = "0123456789abcdef".repeat(4) + service.sendResult = ExternalSendResult.Sent(txId) + sendOnce() + assertTrue(executor.state.value is ExternalSendExecution.Finished) + assertTrue(marker.value) + + runBlocking { executor.forgetWalletState() } + + assertEquals(ExternalSendExecution.Idle, executor.state.value) + assertFalse(marker.value) + val next = buildViewModel() + assertEquals(ExternalSendStatus.Idle, next.uiState.value.status) + assertNull(next.openTransactionResult.value) + // The executor is free for the next wallet. + service.sendResult = ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED) + assertTrue(executor.submit(service.sends.single())) + } + + @Test + fun aMarkerWrite_resumingAfterAWipe_sendsNothing_andLeavesTheMarkerAlone() { + val setGate = CompletableDeferred() + marker.setGate = setGate + sendOnce() + assertTrue(executor.state.value is ExternalSendExecution.Sending) + + runBlocking { executor.forgetWalletState() } + val clearsAfterWipe = marker.clearCalls + // The marker write lands after the wipe; it may now be the next wallet's send's. + setGate.complete(Unit) + marker.setGate = null + + assertTrue(service.sends.isEmpty()) + assertTrue(marker.value) + assertEquals(clearsAfterWipe, marker.clearCalls) + assertEquals(ExternalSendExecution.Idle, executor.state.value) + } + + @Test + fun aSendOfTheWipedWallet_completingLate_neverPublishes_norTouchesTheNextWalletsMarker() { + val lateResults = listOf( + ExternalSendResult.Sent("ab".repeat(32)), + ExternalSendResult.NotSent(NotSentReason.GENERIC) + ) + for (late in lateResults) { + marker.value = false + executor = newExecutor() + val gate = CompletableDeferred() + service.sendGate = gate + sendOnce() + assertTrue(executor.state.value is ExternalSendExecution.Sending) + + runBlocking { executor.forgetWalletState() } + assertEquals(ExternalSendExecution.Idle, executor.state.value) + assertFalse(marker.value) + // The next wallet's send has written its own marker by the time the old one returns. + marker.value = true + val clearsBefore = marker.clearCalls + + gate.complete(late) + assertEquals("$late", ExternalSendExecution.Idle, executor.state.value) + assertTrue("$late", marker.value) + assertEquals("$late", clearsBefore, marker.clearCalls) + service.sendGate = null + } + } + + // ── the transaction result screen (a Sent with its txid) ───────────────── + + private val lockTxId = "0123456789abcdef".repeat(4) + + @Test + fun sentWithItsTxId_opensTheTransactionResult_onceUntilAcknowledged() { + val gate = CompletableDeferred() + service.sendGate = gate + val viewModel = sendOnce() + assertNull("nothing while sending", viewModel.openTransactionResult.value) + + gate.complete(ExternalSendResult.Sent(lockTxId)) + assertEquals(lockTxId, viewModel.uiState.value.openTransactionResult) + assertEquals(lockTxId, viewModel.openTransactionResult.value) + assertTrue(viewModel.takeTransactionResult(lockTxId)) + assertFalse("another txid is not the outcome", viewModel.takeTransactionResult("ab".repeat(32))) + + viewModel.onResultAcknowledged() + // Cleared at once, before the executor settles: never opened twice. + assertNull(viewModel.uiState.value.openTransactionResult) + assertNull(viewModel.openTransactionResult.value) + assertFalse(viewModel.takeTransactionResult(lockTxId)) + assertTrue(viewModel.uiState.value.finished) + assertEquals(ExternalSendExecution.Idle, executor.state.value) + assertFalse(marker.value) + } + + @Test + fun sentWithItsTxId_isOfferedAgain_toAScreenCreatedBeforeItWasAcknowledged_butNotAfter() { + service.sendResult = ExternalSendResult.Sent(lockTxId) + val saved = SavedStateHandle() + sendOnce(buildViewModel(saved)) + // The user left while it was sending (the executor is app-scoped): a new screen opens it. + val returned = buildViewModel() + assertEquals(lockTxId, returned.openTransactionResult.value) + + returned.onResultAcknowledged() + // A recreation (config change) of the acknowledged screen restores finished: nothing to open. + val recreated = buildViewModel(SavedStateHandle(mapOf(ExternalSendViewModel.KEY_FINISHED to true))) + assertNull(recreated.openTransactionResult.value) + assertNull(buildViewModel().openTransactionResult.value) + } + + @Test + fun everyOtherOutcome_keepsTheInScreenResult() { + val others = listOf( + ExternalSendResult.Sent(null), + ExternalSendResult.Sent("txid"), + ExternalSendResult.Sent(lockTxId.dropLast(1) + "z"), + ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED), + ExternalSendResult.MayHaveGoneThrough, + ExternalSendResult.InterruptedFundsReturnToShielded + ) + for (result in others) { + executor = newExecutor() + service.sendResult = result + val viewModel = sendOnce() + assertEquals(ExternalSendStatus.Done(result), viewModel.uiState.value.status) + assertNull("$result", viewModel.uiState.value.openTransactionResult) + assertNull("$result", viewModel.openTransactionResult.value) + viewModel.onResultAcknowledged() + marker.value = false + } + // The restart warning has no txid either. + marker.value = true + executor = newExecutor() + assertNull(buildViewModel().uiState.value.openTransactionResult) + } + + @Test + fun inFlightMarker_unwritable_sendsNothing() { + marker.failWrites = true + sendOnce() + assertTrue(service.sends.isEmpty()) + assertEquals( + ExternalSendExecution.Finished( + ExternalSendRequest(SendBalance.CORE, SendDestination.Core(coreAddress), oneDash, false, WALLET_A), + ExternalSendResult.NotSent(NotSentReason.GENERIC) + ), + executor.state.value + ) + } + + @Test + fun aFreshProcess_withTheMarkerSet_showsMayHaveGoneThrough_insteadOfTheEditableForm() { + // The previous process restored the form; the send it ran left the marker behind. + val saved = SavedStateHandle() + service.balances.getValue(SendBalance.CORE).value = twoDash + buildViewModel(saved).apply { + goToAmount(coreAddress) + type("1") + } + marker.value = true + executor = newExecutor() + + val restored = buildViewModel(saved) + assertEquals( + ExternalSendStatus.Done(ExternalSendResult.MayHaveGoneThrough, afterRestart = true), + restored.uiState.value.status + ) + assertFalse(restored.uiState.value.canContinueAmount) + restored.onAmountContinue() + assertNull(restored.confirmedRequest()) + assertEquals( + R.string.external_send_ambiguous_after_restart_message, + resultContentFor(ExternalSendResult.MayHaveGoneThrough, afterRestart = true).message + ) + + restored.onResultAcknowledged() + assertFalse(marker.value) + assertEquals(ExternalSendStatus.Idle, restored.uiState.value.status) + } + + @Test + fun aFreshProcess_withAnUnreadableMarker_failsClosed() { + marker.failReads = true + executor = newExecutor() + assertEquals(ExternalSendExecution.InterruptedByRestart, executor.state.value) + } + + private val usd100 = ExchangeRate("USD", "100") + + @Test + fun switchingCurrency_neverChangesTheAmount_untilTheUserEditsIt() { + val viewModel = buildViewModel(rate = usd100) + viewModel.goToAmount(coreAddress) + viewModel.type("0.12345678") + val exact = Dash(12_345_678) + assertEquals(exact, viewModel.uiState.value.amount) + + viewModel.onCurrencySelected(dashMode = false) + assertEquals("12.35", viewModel.uiState.value.amountText) + assertEquals(exact, viewModel.uiState.value.amount) + viewModel.onCurrencySelected(dashMode = true) + assertEquals(exact, viewModel.uiState.value.amount) + assertEquals("0.12345678", viewModel.uiState.value.amountText) + + // An edit re-parses what is on show. + viewModel.onCurrencySelected(dashMode = false) + viewModel.onKeyInput("back") + assertNull(viewModel.uiState.value.pinnedAmount) + assertEquals(Dash(12_300_000), viewModel.uiState.value.amount) + } + + @Test + fun aUriAmount_staysExactAcrossACurrencySwitch() { + val viewModel = buildViewModel( + SavedStateHandle(mapOf(ExternalSendViewModel.ARG_PREFILL to "dash:$coreAddress?amount=0.12345678")), + rate = usd100 + ) + viewModel.onCurrencySelected(dashMode = false) + assertEquals(Dash(12_345_678), viewModel.uiState.value.amount) + } + + @Test + fun max_followsTheSource_acrossACurrencySwitch() { + val shieldedMax = Dash(123_456_789) + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + service.max[SendBalance.SHIELDED] = shieldedMax + service.max[SendBalance.PLATFORM] = oneDash + val viewModel = buildViewModel(rate = usd100) + viewModel.goToAmount(platformP2shAddress) + viewModel.onMaxClick() + viewModel.onCurrencySelected(dashMode = false) + assertEquals(shieldedMax, viewModel.uiState.value.amount) + + viewModel.onSourceSelected(SendBalance.PLATFORM) + with(viewModel.uiState.value) { + assertTrue(isMax) + assertFalse(dashMode) + assertEquals(oneDash, amount) + } + } + + // ── Max follows a source change ────────────────────────────────────────── + + private val coreMax = Dash(3_064_752) + private val shieldedMax = Dash(1_500_000) + + /** Core and Shielded funded, each with its own Max; [platformAddress] opens on Core. */ + private fun maxOnCore(saved: SavedStateHandle = SavedStateHandle()): ExternalSendViewModel { + service.balances.getValue(SendBalance.CORE).value = twoDash + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + service.max[SendBalance.CORE] = coreMax + service.max[SendBalance.SHIELDED] = shieldedMax + val viewModel = buildViewModel(saved) + viewModel.goToAmount(platformAddress) + assertEquals(SendBalance.CORE, viewModel.uiState.value.source) + viewModel.onMaxClick() + assertEquals(coreMax, viewModel.uiState.value.amount) + return viewModel + } + + @Test + fun maxThenSwitchingSource_becomesTheNewSourcesMax() { + val gate = CompletableDeferred() + service.maxGates[SendBalance.SHIELDED] = gate + val viewModel = maxOnCore() + + viewModel.onSourceSelected(SendBalance.SHIELDED) + // While the new source's Max is read, nothing is sendable: never the old source's Max. + with(viewModel.uiState.value) { + assertTrue(maxPending) + assertFalse(isMax) + assertEquals(Dash.ZERO, amount) + assertEquals("0", amountText) + assertFalse(canContinueAmount) + } + + gate.complete(Unit) + with(viewModel.uiState.value) { + assertFalse(maxPending) + assertTrue(isMax) + assertEquals(shieldedMax, amount) + assertEquals(shieldedMax.toKeypadString(), amountText) + assertTrue(canContinueAmount) + } + viewModel.onAmountContinue() + val request = viewModel.uiState.value.confirm?.request + assertEquals(SendBalance.SHIELDED, request?.source) + assertEquals(shieldedMax, request?.amount) + assertEquals(true, request?.isMax) + } + + @Test + fun maxThenSwitchingToASourceWithNoMax_clearsTheAmount() { + val viewModel = maxOnCore() + service.max[SendBalance.PLATFORM] = null + + // Balance not known yet: Max is still pending. + viewModel.onSourceSelected(SendBalance.PLATFORM) + assertTrue(viewModel.uiState.value.maxPending) + assertEquals(Dash.ZERO, viewModel.uiState.value.amount) + + // Known balance, no Max (fee unknown): the pending Max is dropped, the amount stays zero. + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + with(viewModel.uiState.value) { + assertFalse(maxPending) + assertFalse(isMax) + assertEquals(Dash.ZERO, amount) + assertEquals("0", amountText) + assertNull(pinnedAmount) + assertFalse(canContinueAmount) + } + } + + @Test + fun typingWhileMaxIsPending_cancelsIt() { + val gate = CompletableDeferred() + service.maxGates[SendBalance.SHIELDED] = gate + val viewModel = maxOnCore() + viewModel.onSourceSelected(SendBalance.SHIELDED) + assertTrue(viewModel.uiState.value.maxPending) + + viewModel.type("1") + assertFalse(viewModel.uiState.value.maxPending) + assertEquals(oneDash, viewModel.uiState.value.amount) + + gate.complete(Unit) + with(viewModel.uiState.value) { + assertFalse(isMax) + assertEquals(shieldedMax, maxSendable) + assertEquals(oneDash, amount) + } + } + + @Test + fun aKeyTheKeypadRejects_stillCancelsAPendingMax() { + service.maxGates[SendBalance.SHIELDED] = CompletableDeferred() + val viewModel = maxOnCore() + viewModel.onSourceSelected(SendBalance.SHIELDED) + viewModel.onKeyInput("back") + assertFalse(viewModel.uiState.value.maxPending) + assertEquals(Dash.ZERO, viewModel.uiState.value.amount) + } + + @Test + fun aStaleSourcesMax_isIgnored() { + val shieldedGate = CompletableDeferred() + val platformGate = CompletableDeferred() + service.maxGates[SendBalance.SHIELDED] = shieldedGate + service.maxGates[SendBalance.PLATFORM] = platformGate + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + service.max[SendBalance.PLATFORM] = oneDash + val viewModel = maxOnCore() + + viewModel.onSourceSelected(SendBalance.SHIELDED) + viewModel.onSourceSelected(SendBalance.PLATFORM) + shieldedGate.complete(Unit) + with(viewModel.uiState.value) { + assertEquals(SendBalance.PLATFORM, source) + assertTrue(maxPending) + assertNull(maxSendable) + assertEquals(Dash.ZERO, amount) + } + + platformGate.complete(Unit) + with(viewModel.uiState.value) { + assertFalse(maxPending) + assertTrue(isMax) + assertEquals(oneDash, amount) + } + } + + @Test + fun switchingSourceWithoutMax_keepsTheTypedAmount() { + service.balances.getValue(SendBalance.CORE).value = twoDash + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + service.max[SendBalance.SHIELDED] = shieldedMax + val viewModel = buildViewModel() + viewModel.goToAmount(platformAddress) + viewModel.type("0.5") + + viewModel.onSourceSelected(SendBalance.SHIELDED) + with(viewModel.uiState.value) { + assertFalse(maxPending) + assertFalse(isMax) + assertEquals("0.5", amountText) + assertEquals(Dash(50_000_000), amount) + } + } + + @Test + fun aPendingMax_survivesProcessDeath_andResolvesOnRestore() { + val saved = SavedStateHandle() + service.maxGates[SendBalance.SHIELDED] = CompletableDeferred() + val first = maxOnCore(saved) + first.onSourceSelected(SendBalance.SHIELDED) + assertTrue(first.uiState.value.maxPending) + assertEquals(true, saved.get(ExternalSendViewModel.KEY_MAX_PENDING)) + assertNull(saved.get(ExternalSendViewModel.KEY_MAX_DUFFS)) + + // The new process reads the Shielded Max at once, before the pending Max is restored. + service.maxGates.remove(SendBalance.SHIELDED) + val restored = buildViewModel(saved) + with(restored.uiState.value) { + assertEquals(SendBalance.SHIELDED, source) + assertFalse(maxPending) + assertTrue(isMax) + assertEquals(shieldedMax, amount) + } + assertEquals(false, saved.get(ExternalSendViewModel.KEY_MAX_PENDING)) + assertEquals(shieldedMax.duffs, saved.get(ExternalSendViewModel.KEY_MAX_DUFFS)) + } + + @Test + fun maxFollowsTheSource_whenAnAutomaticPickReplacesTheUsersSource() { + service.hasIdentity.value = true + service.balances.getValue(SendBalance.CORE).value = twoDash + service.balances.getValue(SendBalance.IDENTITY).value = twoDash + service.max[SendBalance.CORE] = coreMax + service.max[SendBalance.IDENTITY] = oneDash + val viewModel = buildViewModel() + viewModel.goToAmount(platformAddress) + viewModel.onSourceSelected(SendBalance.IDENTITY) + assertEquals(SendBalance.IDENTITY, viewModel.uiState.value.source) + viewModel.onMaxClick() + assertEquals(oneDash, viewModel.uiState.value.amount) + + // The identity goes away: the source falls back to Core, and so does Max. + service.hasIdentity.value = false + with(viewModel.uiState.value) { + assertEquals(SendBalance.CORE, source) + assertTrue(isMax) + assertEquals(coreMax, amount) + } + } + + @Test + fun aNonCoreAmountRequest_opensTheAmountStep_withItsAmount() { + val viewModel = buildViewModel( + SavedStateHandle(mapOf(ExternalSendViewModel.ARG_PREFILL to "dash:$platformAddress?amount=0.5")) + ) + with(viewModel.uiState.value) { + assertEquals(ExternalSendStep.AMOUNT, step) + assertEquals(SendDestination.Platform(platformAddress), destination) + assertEquals(Dash(50_000_000), amount) + } + } + + @Test + fun scanAction_keepsEveryInvoiceFormatOnTheBasicPath() { + val connect = { _: String -> false } + for (invoice in listOf( + "pay:?r=https://example.com/invoice", + "DASH:-ABCDEF", + "dash:?r=https://example.com/invoice", + "dash:$shieldedAddress?r=https://example.com/invoice" + )) { + assertEquals(invoice, AdvancedScanAction.PaymentRequest(invoice), AdvancedSendViewModel.scanActionFor(invoice, network, true, connect)) + } + val request = "dash:$shieldedAddress?amount=1" + assertEquals(AdvancedScanAction.ExternalSend(request), AdvancedSendViewModel.scanActionFor(request, network, true, connect)) + assertEquals( + AdvancedScanAction.Error(wrongNetwork = true), + AdvancedSendViewModel.scanActionFor("dash:$mainnetCoreAddress", network, true, connect) + ) + assertEquals( + AdvancedScanAction.Error(wrongNetwork = false), + AdvancedSendViewModel.scanActionFor("bitcoin:abc", network, true, connect) + ) + assertEquals( + AdvancedScanAction.Error(wrongNetwork = false), + AdvancedSendViewModel.scanActionFor("3QJmnh", network, true, connect) + ) + } + + @Test + fun anInterruptedCoreToPlatformSend_isResumed_whenTheExecutorStarts_andEachTimeTheScreenOpens() { + // setUp's executor ran one sweep. + assertEquals(1, service.platformResumes) + buildViewModel() + assertEquals(2, service.platformResumes) + buildViewModel() + assertEquals(3, service.platformResumes) + } +}