From d2cd61ffb5c3b22ceef16cd723a4ab321a8cf50e Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 3 Nov 2026 22:12:52 -0800 Subject: [PATCH 01/30] refactor(compose): extract a shared AmountEntryPage and move the DEX enter-amount screen onto it AmountEntryPage (common) combines the EnterAmount bar, NumericKeyboardCompose and the locale display boundary, with header/belowAmount/primaryButton slots and optional Max/balance buttons, Dash/fiat picker or tap-to-toggle secondary amount. State stays hoisted: keys go to the owner, which applies processAmountKeyInput. DEXEnterAmountScreen now uses it with no change in layout or behaviour. PurchaseGiftCardScreenV2 is left as is: only one of its three modes shows the keypad, inside a scrolling column, with different button spacing. Adds unit tests for processAmountKeyInput and the display-separator helpers, and moves the processAmountKeyInput KDoc back above its function. Co-Authored-By: Claude Opus 5.5 --- .../common/ui/enter_amount/AmountEntryPage.kt | 250 ++++++++++++++++++ .../ui/enter_amount/EnterAmountCompose.kt | 6 +- .../ui/enter_amount/AmountEntryInputTest.kt | 75 ++++++ .../maya/ui/DEXEnterAmountScreen.kt | 110 +++----- 4 files changed, 369 insertions(+), 72 deletions(-) create mode 100644 common/src/main/java/org/dash/wallet/common/ui/enter_amount/AmountEntryPage.kt create mode 100644 common/src/test/java/org/dash/wallet/common/ui/enter_amount/AmountEntryInputTest.kt diff --git a/common/src/main/java/org/dash/wallet/common/ui/enter_amount/AmountEntryPage.kt b/common/src/main/java/org/dash/wallet/common/ui/enter_amount/AmountEntryPage.kt new file mode 100644 index 0000000000..1799119312 --- /dev/null +++ b/common/src/main/java/org/dash/wallet/common/ui/enter_amount/AmountEntryPage.kt @@ -0,0 +1,250 @@ +/* + * 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 org.dash.wallet.common.ui.enter_amount + +import android.content.res.Configuration +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import org.dash.wallet.common.R +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.LocalDashColors +import org.dash.wallet.common.ui.components.Size +import org.dash.wallet.common.ui.components.Style +import org.dash.wallet.common.ui.components.TopIntro +import java.text.DecimalFormatSymbols +import java.util.Locale + +/** The decimal separator [locale] displays, e.g. `,` for `de-DE`. */ +fun decimalSeparatorFor(locale: Locale): Char = DecimalFormatSymbols.getInstance(locale).decimalSeparator + +/** + * Renders an amount kept as a plain `.`-separated string (the form [processAmountKeyInput] produces + * and `BigDecimal` parses) with [decimalSeparator], for display only. A trailing separator is kept, + * so "12." shows as "12," while the user is typing. + */ +fun localizeAmountForDisplay(amount: String, decimalSeparator: Char): String = + amount.replace('.', decimalSeparator) + +/** + * Full-height amount entry page: an optional [header], the design-system [EnterAmount] bar, optional + * content under it, and the [NumericKeyboardCompose] keypad flush with the bottom edge, with an + * optional [primaryButton] inside the keypad panel. + * + * State is hoisted. [amount] is the plain `.`-separated amount string for the currency at + * [selectedCurrencyIndex]; the page localizes its decimal separator (and the keypad's separator + * key label) from [locale] for display only. Keys go to [onKeyInput] unprocessed ("0"–"9", ".", + * "back", "back_long"); the owner applies them with [processAmountKeyInput], usually in its + * ViewModel, so it can choose the decimal places per currency. + * + * Switching between Dash and fiat works in one of two ways: + * - pass [onCurrencySelected] to show [EnterAmount]'s vertical currency picker, or + * - pass [secondaryAmount] and tap handlers ([onPrimaryAmountClick] / [onSecondaryAmountClick]) to + * toggle by tapping the amounts. + * + * The Max and show-balance buttons are shown only when [onMaxClick] / [onBalanceClick] are set. + * + * The page fills the space its [modifier] gives it; the flexible gap between the amount and the + * keypad needs a bounded height (e.g. `Modifier.fillMaxSize()` or `Modifier.weight(1f)`). + * + * @param keypadEnabled false dims the keypad and ignores taps (e.g. offline, or while the amount is + * being validated). It does not affect [primaryButton], which manages its own enabled state. + * @param header content above the amount bar, e.g. a [TopIntro] heading. + * @param belowAmount content directly under the amount bar, e.g. a validation message. + * @param primaryButton content at the bottom of the keypad panel, usually [AmountEntryPrimaryButton]. + */ +@Composable +fun AmountEntryPage( + amount: String, + currencyCodes: List, + selectedCurrencyIndex: Int, + onKeyInput: (String) -> Unit, + modifier: Modifier = Modifier, + locale: Locale = Locale.getDefault(), + secondaryAmount: String? = null, + showPrimaryChevron: Boolean = true, + helpTextTop: String? = null, + helpTextBottom: String? = null, + keypadEnabled: Boolean = true, + onCurrencySelected: ((Int) -> Unit)? = null, + onPrimaryAmountClick: () -> Unit = {}, + onSecondaryAmountClick: () -> Unit = {}, + onMaxClick: (() -> Unit)? = null, + onBalanceClick: (() -> Unit)? = null, + header: @Composable ColumnScope.() -> Unit = {}, + belowAmount: @Composable ColumnScope.() -> Unit = {}, + primaryButton: (@Composable ColumnScope.() -> Unit)? = null +) { + val decimalSeparator = remember(locale) { decimalSeparatorFor(locale) } + + Column(modifier = modifier) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + header() + EnterAmount( + primaryAmount = localizeAmountForDisplay(amount, decimalSeparator), + secondaryAmount = secondaryAmount?.let { localizeAmountForDisplay(it, decimalSeparator) } ?: "0", + currencyCodes = currencyCodes, + selectedCurrencyIndex = selectedCurrencyIndex, + locale = locale, + helpTextTop = helpTextTop, + helpTextBottom = helpTextBottom, + showMaxButton = onMaxClick != null, + showBalanceButton = onBalanceClick != null, + showPrimaryChevron = showPrimaryChevron, + showSecondary = secondaryAmount != null, + showCurrencyPicker = onCurrencySelected != null, + onMaxClick = { onMaxClick?.invoke() }, + onBalanceClick = { onBalanceClick?.invoke() }, + onPrimaryAmountClick = onPrimaryAmountClick, + onSecondaryAmountClick = onSecondaryAmountClick, + onCurrencyPickerSelect = { _, index -> onCurrencySelected?.invoke(index) } + ) + belowAmount() + } + + // Empty flexible space between the amount bar and the keypad. + Spacer(modifier = Modifier.weight(1f)) + + NumericKeyboardCompose( + modifier = Modifier.fillMaxWidth(), + enabled = keypadEnabled, + decimalSeparator = decimalSeparator, + onKeyInput = onKeyInput, + bottomSlot = primaryButton + ) + } +} + +/** + * The standard primary action for [AmountEntryPage]'s `primaryButton` slot: a full-width large + * filled button, inset to line up with the keypad keys. + */ +@Composable +fun ColumnScope.AmountEntryPrimaryButton( + text: String, + enabled: Boolean, + onClick: () -> Unit +) { + DashButton( + text = text, + style = Style.FilledBlue, + size = Size.Large, + isEnabled = enabled, + onClick = onClick, + modifier = Modifier + .fillMaxWidth() + .padding(top = 20.dp, start = 20.dp, end = 20.dp) + ) +} + +/** Receive-style page: no Max or balance buttons, Dash/fiat picker, Continue action. */ +@Preview(name = "Picker Light", showBackground = true, widthDp = 393, heightDp = 700, uiMode = Configuration.UI_MODE_NIGHT_NO) +@Preview(name = "Picker Dark", showBackground = true, widthDp = 393, heightDp = 700, uiMode = Configuration.UI_MODE_NIGHT_YES) +@Composable +private fun AmountEntryPagePickerPreview() { + DashWalletTheme { + AmountEntryPage( + amount = "12.5", + currencyCodes = listOf("USD", DASH_CURRENCY_CODE), + selectedCurrencyIndex = 0, + locale = Locale.US, + onKeyInput = {}, + onCurrencySelected = {}, + modifier = Modifier + .fillMaxSize() + .background(LocalDashColors.current.backgroundPrimary), + header = { TopIntro(heading = "Enter amount") }, + primaryButton = { + AmountEntryPrimaryButton( + text = stringResource(R.string.button_continue), + enabled = true, + onClick = {} + ) + } + ) + } +} + +/** Every option on: Max and balance buttons, tap-to-toggle secondary amount, help text. */ +@Preview(name = "Full Light", showBackground = true, widthDp = 393, heightDp = 700, uiMode = Configuration.UI_MODE_NIGHT_NO) +@Preview(name = "Full Dark", showBackground = true, widthDp = 393, heightDp = 700, uiMode = Configuration.UI_MODE_NIGHT_YES) +@Composable +private fun AmountEntryPageFullPreview() { + DashWalletTheme { + AmountEntryPage( + amount = "0.5", + secondaryAmount = "14.20", + currencyCodes = listOf(DASH_CURRENCY_CODE, "USD"), + selectedCurrencyIndex = 0, + locale = Locale.US, + helpTextTop = "Available: 1.2345 DASH", + onKeyInput = {}, + onMaxClick = {}, + onBalanceClick = {}, + modifier = Modifier + .fillMaxSize() + .background(LocalDashColors.current.backgroundPrimary), + primaryButton = { + AmountEntryPrimaryButton( + text = stringResource(R.string.button_continue), + enabled = false, + onClick = {} + ) + } + ) + } +} + +/** German locale with the keypad disabled: decimal comma, € after the amount, dimmed keys. */ +@Preview(name = "German Disabled", showBackground = true, widthDp = 393, heightDp = 700) +@Composable +private fun AmountEntryPageGermanDisabledPreview() { + DashWalletTheme { + AmountEntryPage( + amount = "125.50", + currencyCodes = listOf("EUR", DASH_CURRENCY_CODE), + selectedCurrencyIndex = 0, + locale = Locale.GERMANY, + keypadEnabled = false, + onKeyInput = {}, + onCurrencySelected = {}, + modifier = Modifier + .fillMaxSize() + .background(LocalDashColors.current.backgroundPrimary) + ) + } +} diff --git a/common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountCompose.kt b/common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountCompose.kt index e6aa127e69..4463ed0cb8 100644 --- a/common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountCompose.kt +++ b/common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountCompose.kt @@ -47,6 +47,9 @@ import org.dash.wallet.common.ui.components.DashWalletTheme import org.dash.wallet.common.ui.components.LocalDashColors import org.dash.wallet.common.ui.components.MyTheme +// Opacity applied to the keys when the keyboard is disabled, so it reads as inactive. +private const val DISABLED_KEY_ALPHA = 0.4f + /** * Updates an amount string based on a keyboard key press. * @@ -54,9 +57,6 @@ import org.dash.wallet.common.ui.components.MyTheme * and exceeding [maxDecimalPlaces]); "back" removes the last character (floor to "0"); "back_long" * resets to "0". */ -// Opacity applied to the keys when the keyboard is disabled, so it reads as inactive. -private const val DISABLED_KEY_ALPHA = 0.4f - fun processAmountKeyInput(current: String, key: String, maxDecimalPlaces: Int = 2): String { return when (key) { "back" -> if (current.length > 1) current.dropLast(1) else "0" diff --git a/common/src/test/java/org/dash/wallet/common/ui/enter_amount/AmountEntryInputTest.kt b/common/src/test/java/org/dash/wallet/common/ui/enter_amount/AmountEntryInputTest.kt new file mode 100644 index 0000000000..4949d48705 --- /dev/null +++ b/common/src/test/java/org/dash/wallet/common/ui/enter_amount/AmountEntryInputTest.kt @@ -0,0 +1,75 @@ +/* + * 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 org.dash.wallet.common.ui.enter_amount + +import org.junit.Assert.assertEquals +import org.junit.Test +import java.util.Locale + +class AmountEntryInputTest { + + private fun type(keys: List, maxDecimalPlaces: Int = 2, start: String = "0"): String = + keys.fold(start) { current, key -> processAmountKeyInput(current, key, maxDecimalPlaces) } + + @Test + fun `first digit replaces the leading zero`() { + assertEquals("7", type(listOf("7"))) + assertEquals("70", type(listOf("7", "0"))) + } + + @Test + fun `zero stays a single zero`() { + assertEquals("0", type(listOf("0", "0"))) + } + + @Test + fun `decimal point is added once`() { + assertEquals("0.", type(listOf("."))) + assertEquals("1.5", type(listOf("1", ".", ".", "5"))) + } + + @Test + fun `digits beyond maxDecimalPlaces are rejected`() { + assertEquals("1.23", type(listOf("1", ".", "2", "3", "4"))) + assertEquals("1.23456789", type(listOf("1", ".", "2", "3", "4", "5", "6", "7", "8", "9", "1"), 8)) + } + + @Test + fun `back removes the last character and floors to zero`() { + assertEquals("1.", type(listOf("back"), start = "1.5")) + assertEquals("0", type(listOf("back"), start = "5")) + assertEquals("0", type(listOf("back"), start = "0")) + } + + @Test + fun `back_long resets to zero`() { + assertEquals("0", type(listOf("back_long"), start = "123.45")) + } + + @Test + fun `display uses the locale decimal separator and keeps a trailing one`() { + val german = decimalSeparatorFor(Locale.GERMANY) + assertEquals(',', german) + assertEquals("125,50", localizeAmountForDisplay("125.50", german)) + assertEquals("12,", localizeAmountForDisplay("12.", german)) + + val us = decimalSeparatorFor(Locale.US) + assertEquals('.', us) + assertEquals("125.50", localizeAmountForDisplay("125.50", us)) + } +} diff --git a/integrations/maya/src/main/java/org/dash/wallet/integrations/maya/ui/DEXEnterAmountScreen.kt b/integrations/maya/src/main/java/org/dash/wallet/integrations/maya/ui/DEXEnterAmountScreen.kt index 6d1492fee2..97b362d473 100644 --- a/integrations/maya/src/main/java/org/dash/wallet/integrations/maya/ui/DEXEnterAmountScreen.kt +++ b/integrations/maya/src/main/java/org/dash/wallet/integrations/maya/ui/DEXEnterAmountScreen.kt @@ -21,14 +21,12 @@ import androidx.annotation.StringRes import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource @@ -36,19 +34,15 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle 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.EnterAmount import org.dash.wallet.common.ui.components.LocalDashColors import org.dash.wallet.common.ui.components.MyTheme import org.dash.wallet.common.ui.components.NavBarBack -import org.dash.wallet.common.ui.components.Size -import org.dash.wallet.common.ui.components.Style import org.dash.wallet.common.ui.components.Toast import org.dash.wallet.common.ui.components.ToastImageResource import org.dash.wallet.common.ui.components.TopIntro -import org.dash.wallet.common.ui.enter_amount.NumericKeyboardCompose +import org.dash.wallet.common.ui.enter_amount.AmountEntryPage +import org.dash.wallet.common.ui.enter_amount.AmountEntryPrimaryButton import org.dash.wallet.integrations.maya.R -import java.text.DecimalFormatSymbols import java.util.Locale @Composable @@ -99,11 +93,6 @@ private fun DEXEnterAmountScreenContent( // Overridable so previews can force a specific locale (symbol position, separators). locale: Locale = Locale.getDefault() ) { - // The ViewModel keeps the amount as a plain '.'-separated string (it round-trips through - // BigDecimal parsing and persistence); the locale's decimal separator is applied here, - // at the display boundary, and on the keypad's separator key label. - val decimalSeparator = remember(locale) { DecimalFormatSymbols.getInstance(locale).decimalSeparator } - Box( modifier = Modifier .fillMaxSize() @@ -114,67 +103,50 @@ private fun DEXEnterAmountScreenContent( onBackClick = onBackClick ) - // Amount input bar (design-system EnterAmount). Fiat is the primary input; DASH and - // the asset being bought are offered as alternate display currencies in the picker. - // No Max / balance / help text in this frame — only the amount + currency selector. - Column( - modifier = Modifier - .fillMaxWidth() - // .height(110.dp) - .padding(horizontal = 20.dp), - horizontalAlignment = Alignment.CenterHorizontally - ) { - TopIntro(heading = stringResource(R.string.dex_enter_amount_title, assetDisplayCode)) - EnterAmount( - primaryAmount = amount.replace('.', decimalSeparator), - currencyCodes = currencyCodes, - selectedCurrencyIndex = selectedCurrencyIndex, - locale = locale, - showMaxButton = false, - showBalanceButton = false, - showSecondary = false, - showCurrencyPicker = true, - onCurrencyPickerSelect = { _, index -> onCurrencySelected(index) } - ) - - validationErrorRes?.let { errorRes -> - // The message is chosen in the ViewModel: a below-minimum rejection names itself, - // anything else falls back to the neutral catch-all (SwapKit's noRoutesFound - // can't tell too-low from temporarily-unroutable, and the entered value is in the - // selected display currency — so any min/max guess would be misleading). Messages - // without a %1$s placeholder simply ignore the coin code. - Text( - text = stringResource(errorRes, assetCurrencyCode), - style = MyTheme.Body2Regular, - color = LocalDashColors.current.red, - modifier = Modifier.padding(top = 8.dp) - ) - } - } - - // Empty flexible space between the amount bar and the keypad. - Spacer(modifier = Modifier.weight(1f)) - - // Numeric keypad with the Continue button in its bottom slot, flush to the bottom edge. - NumericKeyboardCompose( - modifier = Modifier.fillMaxWidth(), + // Amount input bar (design-system EnterAmount) over the keypad. The ViewModel keeps the + // amount as a plain '.'-separated string; the page applies the locale's decimal + // separator at the display boundary. Fiat is the primary input; DASH and the asset + // being bought are offered as alternate display currencies in the picker. No Max / + // balance / help text in this frame — only the amount + currency selector. + AmountEntryPage( + amount = amount, + currencyCodes = currencyCodes, + selectedCurrencyIndex = selectedCurrencyIndex, + locale = locale, + onKeyInput = onKeyInput, + onCurrencySelected = onCurrencySelected, // Fully disabled (dimmed, not tappable) while offline — a swap can't be quoted // without a connection — and while the entered amount is being validated, so the // validated amount can't change mid-flight. - enabled = isOnline && !isValidating, - decimalSeparator = decimalSeparator, - onKeyInput = onKeyInput, - bottomSlot = { - DashButton( + keypadEnabled = isOnline && !isValidating, + modifier = Modifier + .fillMaxWidth() + .weight(1f), + header = { + TopIntro(heading = stringResource(R.string.dex_enter_amount_title, assetDisplayCode)) + }, + belowAmount = { + validationErrorRes?.let { errorRes -> + // The message is chosen in the ViewModel: a below-minimum rejection names + // itself, anything else falls back to the neutral catch-all (SwapKit's + // noRoutesFound can't tell too-low from temporarily-unroutable, and the + // entered value is in the selected display currency — so any min/max guess + // would be misleading). Messages without a %1$s placeholder simply ignore + // the coin code. + Text( + text = stringResource(errorRes, assetCurrencyCode), + style = MyTheme.Body2Regular, + color = LocalDashColors.current.red, + modifier = Modifier.padding(top = 8.dp) + ) + } + }, + primaryButton = { + AmountEntryPrimaryButton( text = stringResource(R.string.button_continue), - style = Style.FilledBlue, - size = Size.Large, // Disabled while offline: a swap can't be quoted without a connection. - isEnabled = continueEnabled && isOnline, - onClick = onContinueClick, - modifier = Modifier - .fillMaxWidth() - .padding(top = 20.dp, start = 20.dp, end = 20.dp) + enabled = continueEnabled && isOnline, + onClick = onContinueClick ) } ) From fb335a0ddb0f6b6f59197e400b5e7233f5fbd273 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 16:50:00 -0800 Subject: [PATCH 02/30] feat(payments): External Send from any balance in Advanced mode (MO-1121) The Advanced payments Send tab gets its own Compose page: send to a username (Core, as today), to a typed/pasted/scanned destination, or by scanning a Dash QR. The external send flow detects the destination type from the whole address (Core, Platform dash1k/dash1s, Shielded dash1z, identity ID) and rejects wrong-network or malformed input, then reuses AmountEntryPage with From/To cards, a source picker, a confirm sheet and PIN before every send. ExternalSendService routes each source/destination pair to the SDK with the SdkWriteResult rules (only provably pre-broadcast failures are retryable, the bound wallet is captured and re-checked before submit). Supported: Core->Core/Shielded/own Identity, Shielded->all, Platform->Platform/Identity, Identity->Core/Platform/Identity. The rest need SDK changes and are shown as not available yet. Basic mode is unchanged. Co-Authored-By: Claude Opus 5.5 --- wallet/res/navigation/nav_home.xml | 24 + wallet/res/values/strings.xml | 64 ++ .../schildbach/wallet/di/PlatformSdkModule.kt | 7 + .../platform/sdk/ExternalSendModels.kt | 300 ++++++ .../platform/sdk/ExternalSendService.kt | 135 +++ .../platform/sdk/ExternalSendServiceImpl.kt | 969 ++++++++++++++++++ .../platform/sdk/ShieldedBalanceService.kt | 91 ++ .../sdk/ShieldedBalanceServiceImpl.kt | 162 ++- .../ui/payments/AdvancedPaymentsFragment.kt | 7 +- .../ui/payments/send/AdvancedSendFragment.kt | 235 +++++ .../ui/payments/send/AdvancedSendViewModel.kt | 106 ++ .../ui/payments/send/ExternalSendExecutor.kt | 132 +++ .../ui/payments/send/ExternalSendFragment.kt | 153 +++ .../ui/payments/send/ExternalSendScreen.kt | 903 ++++++++++++++++ .../ui/payments/send/ExternalSendViewModel.kt | 600 +++++++++++ .../platform/sdk/ExternalSendModelsTest.kt | 280 +++++ .../sdk/ExternalSendServiceImplTest.kt | 544 ++++++++++ .../sdk/ShieldedBalanceServiceTest.kt | 72 ++ .../send/ExternalSendViewModelTest.kt | 569 ++++++++++ 19 files changed, 5342 insertions(+), 11 deletions(-) create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt create mode 100644 wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt create mode 100644 wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt create mode 100644 wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt create mode 100644 wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt diff --git a/wallet/res/navigation/nav_home.xml b/wallet/res/navigation/nav_home.xml index 131d82cad5..41d3a71692 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" /> + + + + + + + + + + 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 + The funds go to this identity\'s balance on Dash Platform, not to its owner\'s Dash wallet. + 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 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 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/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt new file mode 100644 index 0000000000..1f6ba01da1 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -0,0 +1,300 @@ +/* + * 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 result of [detectSendDestination]. */ +sealed class DestinationParse { + /** + * A destination of the wallet's network. [amount] is set only for a `dash:` payment + * URI that carried one (always a [SendDestination.Core]). + */ + 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)) +} + +/** 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 with an address resolves to [SendDestination.Core] plus its + * optional amount, through the shared [PaymentURI] parser. 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. + */ +fun detectSendDestination(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) + } + + detectCoreAddress(trimmed, network)?.let { return it } + detectBech32mAddress(trimmed, network)?.let { return it } + decodeIdentityId(trimmed)?.let { + return DestinationParse.Valid(SendDestination.Identity(trimmed)) + } + 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 { + // 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 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 | no (1) | own identity only (2) | + * | Shielded | yes | yes | yes | yes | + * | Platform | no (3) | no (4) | yes | yes | + * | Identity | yes | no (5) | yes | yes, not to itself | + * + * 1. The pinned Kotlin SDK's `fundFromAssetLock` only funds the wallet's OWN Platform + * addresses (Rust `RecipientOwnership::AllOwned`); the external variant exists in + * the Rust FFI but is not bound in JNI. + * 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 SDK's Platform-address withdrawal only withdraws the full balance. + * 4. `shieldedShield` (Type 15) only pays the wallet's own Orchard address. + * 5. `shieldedShieldFromIdentity` (Type 21) is self-only too. + */ +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 -> SendSupport.NOT_SUPPORTED_YET + is SendDestination.Identity -> + if (destinationIsOwnIdentity == true) SendSupport.SUPPORTED else SendSupport.NEEDS_OWN_IDENTITY + } + SendBalance.SHIELDED -> SendSupport.SUPPORTED + SendBalance.PLATFORM -> when (destination) { + is SendDestination.Platform, is SendDestination.Identity -> SendSupport.SUPPORTED + is SendDestination.Core, is SendDestination.Shielded -> SendSupport.NOT_SUPPORTED_YET + } + SendBalance.IDENTITY -> when (destination) { + is SendDestination.Core, is SendDestination.Platform -> SendSupport.SUPPORTED + is SendDestination.Shielded -> SendSupport.NOT_SUPPORTED_YET + // 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..e24a10f64f --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -0,0 +1,135 @@ +/* + * 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, + + /** 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 + + /** 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 this exact send, or null when it cannot be known before the send (never fabricated). */ + suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? + + /** Balance minus fee for Max, or null when unknown. */ + suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? + + /** + * Send [amount] from [source] to [destination]. The caller has ALREADY + * authenticated (PIN/biometric) for this send and passes exactly what the user + * confirmed. The implementation captures the wallet before its first suspension + * and re-checks it right before the native call (a change → 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). + * + * Shielded legs block for a ~30s proof: run this on an application-scoped owner so + * leaving the screen does not cancel it. + */ + suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean + ): ExternalSendResult +} 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..b30940d603 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -0,0 +1,969 @@ +/* + * 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.SendEngineNotSyncedException +import de.schildbach.wallet.payments.SendNotSdkRoutableException +import de.schildbach.wallet.payments.SendSignerLockedException +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.isAssetLockSelectionShort +import de.schildbach.wallet.ui.shielded.shieldedMaxFeeAdjustment +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.catch +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.dashfoundation.dashsdk.credits.FundingInput +import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicBoolean +import javax.inject.Inject +import javax.inject.Singleton + +// ── Pure helpers ────────────────────────────────────────────────────── + +/** + * 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) -> 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 + } +} + +/** + * Pick Platform-address inputs that spend EXACTLY [targetCredits] (largest balances + * first), or null when the addresses cannot cover it — never a partial spend. + */ +internal fun selectPlatformInputs(candidates: List, targetCredits: Long): List? { + if (targetCredits <= 0) return null + val picked = packOverageInputs(candidates, targetCredits) + val covered = picked.fold(0L) { acc, input -> Math.addExact(acc, input.credits) } + return picked.takeIf { covered == targetCredits } +} + +// ── 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? + + /** [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 null-wrapped [Result.failure] on read errors. */ + 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 + 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) + suspend fun platformTopUpIdentity(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) +} + +/** 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 +) : 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 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)) } + .catch { e -> + if (e is CancellationException) throw e + log.warn("identity record unreadable; identity unknown", e) + emit(Result.failure(e)) + } + + /** 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 fun observeShieldedBalance(): Flow = + flow { emitAll(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) } + .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 + } + } + } + .catch { e -> + if (e is CancellationException) throw e + log.warn("shielded balance unreadable", e) + emit(null) + } + + 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.topUp(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 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 + ) + } + + 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; + * 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 id is captured, 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). + */ +@Singleton +class ExternalSendServiceImpl internal constructor( + private val source: ExternalSendSource, + private val network: AddressNetwork, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val balancePollMs: Long = BALANCE_POLL_MS +) : ExternalSendService { + + @Inject + constructor( + sdkService: DashSdkService, + sendPaymentService: SendPaymentService, + sdkL1SendService: SdkL1SendService, + cutoverUiDataService: CutoverUiDataService, + shieldedBalanceService: ShieldedBalanceService, + transparentTopUp: SdkTransparentTopUp, + usernameQueries: SdkUsernameQueries, + dashPayConfig: DashPayConfig, + identityConfig: BlockchainIdentityConfig, + walletData: WalletData + ) : this( + source = DashSdkExternalSendSource( + sdkService, sendPaymentService, sdkL1SendService, cutoverUiDataService, shieldedBalanceService, + transparentTopUp, usernameQueries, dashPayConfig, identityConfig, walletData + ), + network = AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id) + ) + + private val inFlight = AtomicBoolean(false) + + // ── 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) + } + SendBalance.IDENTITY -> this.source.observeOwnIdentityId().flatMapLatest { own -> + val id = own.getOrNull() + if (own.isFailure || id == null) { + flowOf(null) + } else { + polled { _ -> this.source.identityBalanceCredits(id)?.takeIf { it >= 0 }?.let(::creditsToDash) } + } + } + }.catch { e -> + if (e is CancellationException) throw e + log.warn("external send: {} balance unreadable", source, e) + emit(null) + }.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", e) + null + } + emit(value) + delay(balancePollMs) + } + } + + override fun observeHasIdentity(): Flow = + source.observeOwnIdentityId() + .map { result -> if (result.isFailure) null else result.getOrNull() != null } + .distinctUntilChanged() + + 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", 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", 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", e) + null + } + return IdentityResolution.Found(username) + } + + override suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? = + try { + withContext(ioDispatcher) { estimateFeeInner(source, destination) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: fee estimate failed; unknown", e) + null + } + + /** + * - Core → Core: the SDK send's fee reserve ([SEND_ALL_FEE_RESERVE_DUFFS]), an upper + * bound the real (smaller) fee never exceeds — the same figure the Basic send shows. + * - Core → Shielded: the shield pool fee (flat shielded fee + asset-lock base cost), + * carved out of the locked amount; the L1 fee is extra and unknown, so not exact. + * - Shielded → *: the flat single-note pool fee of the transition; more notes cost more. + * - Core → Identity, Platform → *, Identity → *: Rust meters these at execution; no + * pre-send figure exists, so null. + */ + private suspend fun estimateFeeInner(source: SendBalance, destination: SendDestination): FeeEstimate? = + when (source) { + SendBalance.CORE -> when (destination) { + is SendDestination.Core -> FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false) + is SendDestination.Shielded -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { + FeeEstimate( + Dash(Math.addExact(ceilCreditsToDuffs(it), ShieldedBalanceServiceImpl.ASSET_LOCK_BASE_COST_DUFFS)), + exact = false + ) + } + else -> null + } + SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destination))?.let { + FeeEstimate(Dash(ceilCreditsToDuffs(it)), exact = false) + } + SendBalance.PLATFORM, SendBalance.IDENTITY -> null + } + + /** + * - Core → Core / Shielded: the SDK's max-sendable L1 figure (already net of the + * send-all fee headroom); a Max Core→Shielded send retries once with an L1 reserve + * if the lock selection comes up short. + * - Shielded → *: the READY balance minus the single-note pool fee; a Max send also + * retries once with the exact deficit the note selection reports. + * - Everything else: null (no pre-send fee figure). + */ + override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = try { + when (source) { + SendBalance.CORE -> when (destination) { + is SendDestination.Core, is SendDestination.Shielded -> + this.source.observeCoreMaxSendableDuffs().first()?.takeIf { it > 0 }?.let(::Dash) + else -> null + } + SendBalance.SHIELDED -> { + val balance = this.source.observeShieldedBalance().first() + val feeCredits = withContext(ioDispatcher) { + this@ExternalSendServiceImpl.source.shieldedFeeCredits(shieldedKindFor(destination)) + } + if (balance == null || feeCredits == null) { + null + } else { + (balance - Dash(ceilCreditsToDuffs(feeCredits))).takeIf { it.isPositive } + } + } + SendBalance.PLATFORM, SendBalance.IDENTITY -> null + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send: max sendable unreadable", e) + null + } + + // ── Send ────────────────────────────────────────────────────────── + + override suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean + ): 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) } + } 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), e) + ExternalSendResult.MayHaveGoneThrough + } finally { + inFlight.set(false) + } + } + + private suspend fun sendInner( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + coreSession: WalletSession? + ): 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) Wallet captured, support gate enforced here. + val walletIdHex = readOrNull("bound wallet") { this.source.boundWalletIdOrNull() } + ?: return notSent(pair, NotSentReason.GENERIC, "no bound SDK wallet") + 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) { + is SendDestination.Identity -> if (source == SendBalance.CORE) { + 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)") + } + + // 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, isMax, coreSession) + SendBalance.SHIELDED -> sendFromShielded(pair, walletIdHex, destination, amount, isMax) + SendBalance.PLATFORM -> sendFromPlatform(pair, walletIdHex, destination, amountCredits) + SendBalance.IDENTITY -> sendFromIdentity( + pair, + walletIdHex, + checkNotNull(ownIdentityBytes) { "identity source without its id" }, + destination, + amountCredits + ) + } + } + + private suspend fun sendFromCore( + pair: String, + walletIdHex: String, + destination: SendDestination, + amount: Dash, + isMax: Boolean, + coreSession: WalletSession? + ): ExternalSendResult = when (destination) { + is SendDestination.Core -> { + if (!stillBound(pair, walletIdHex)) { + ExternalSendResult.NotSent(NotSentReason.GENERIC) + } else { + 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, e) } + } + } + } + is SendDestination.Shielded -> { + var result = shieldFromCoreChecked(pair, walletIdHex, destination.address, amount) + val first = result + if (isMax && first is SdkWriteResult.NotBroadcast && isAssetLockSelectionShort(first)) { + val reserve = this.source.spendableUtxoCount()?.let(::assetLockMaxFeeReserve) + val adjusted = reserve?.let { amount - it } + if (adjusted != null && adjusted.isPositive) { + log.info("external send {}: max shield short; retrying once with an L1 fee reserve", pair) + result = shieldFromCoreChecked(pair, walletIdHex, destination.address, adjusted) + } + } + when (result) { + is SdkWriteResult.Broadcast -> when (result.value) { + ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) + ShieldFromWalletOutcome.SHIELD_PENDING_RETRY -> { + log.warn("external send {}: lock out, shield not submitted — returns to own shielded", pair) + ExternalSendResult.InterruptedFundsReturnToShielded + } + } + else -> mapWrite(pair, result) + } + } + is SendDestination.Identity -> { + if (!stillBound(pair, walletIdHex)) { + ExternalSendResult.NotSent(NotSentReason.GENERIC) + } else { + mapWrite(pair, this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) + } + } + is SendDestination.Platform -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") + } + + private suspend fun shieldFromCoreChecked( + pair: String, + walletIdHex: String, + address: String, + amount: Dash + ): SdkWriteResult = + if (!stillBound(pair, walletIdHex)) { + SdkWriteResult.NotBroadcast("the bound wallet changed") + } else { + 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 { + if (!stillBound(pair, walletIdHex)) return SdkWriteResult.NotBroadcast("the bound wallet changed") + return 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 + ) + } + } + var result = attempt(amount) + val first = result + if (isMax && first is SdkWriteResult.NotBroadcast) { + val adjustment = shieldedMaxFeeAdjustment(amount, first) + if (adjustment != null) { + log.info("external send {}: max spend short by the pool fee; retrying once", pair) + result = attempt(adjustment.adjustedAmount) + } + } + return when (result) { + is SdkWriteResult.Broadcast -> ExternalSendResult.Sent(null) + else -> mapWrite(pair, result) + } + } + + private suspend fun sendFromPlatform( + pair: String, + walletIdHex: String, + destination: SendDestination, + amountCredits: Long + ): ExternalSendResult = when (destination) { + 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") + val inputs = selectPlatformInputs(candidates, amountCredits) + ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount") + nativeWrite(pair, walletIdHex) { this.source.platformTopUpIdentity(walletIdHex, identityId, inputs) } + } + else -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") + } + + private suspend fun sendFromIdentity( + pair: String, + walletIdHex: String, + fromId: ByteArray, + destination: SendDestination, + amountCredits: Long + ): ExternalSendResult = when (destination) { + is SendDestination.Core -> + nativeWrite(pair, walletIdHex) { + this.source.identityWithdraw(walletIdHex, fromId, amountCredits, 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 -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") + } + + /** One raw SDK credits call, after the wallet re-check, classified by [classifyBroadcastFailure]. */ + private suspend fun nativeWrite(pair: String, walletIdHex: String, call: suspend () -> Unit): ExternalSendResult { + if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) + val result: SdkWriteResult = try { + 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) + } + return if (result is SdkWriteResult.Broadcast) { + log.info("external send {}: sent", pair) + ExternalSendResult.Sent(null) + } else { + mapWrite(pair, result) + } + } + + 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, result.cause) + ExternalSendResult.NotSent(reason) + } + is SdkWriteResult.Ambiguous -> { + log.error("external send {}: outcome unconfirmed — may have gone through; do NOT retry", pair, 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, 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 + + 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(destination: SendDestination): ShieldedFeeKind = when (destination) { + is SendDestination.Core -> ShieldedFeeKind.WITHDRAWAL + is SendDestination.Shielded -> ShieldedFeeKind.TRANSFER + is SendDestination.Platform -> ShieldedFeeKind.UNSHIELD + is SendDestination.Identity -> ShieldedFeeKind.IDENTITY_TOP_UP + } + } +} 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 b0a653152a..91f12ba7e9 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceService.kt @@ -97,6 +97,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, @@ -514,4 +533,76 @@ 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 + + /** + * [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). + */ + 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 df57cadf56..709b4ca548 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -746,6 +746,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. */ @@ -959,6 +973,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 + ) } /** @@ -2179,7 +2211,13 @@ 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 ): SdkWriteResult { val operation = if (fundingPath == null) "shieldFromWallet" else "shieldMixedFundsFromWallet" if (!isEnabled()) return SdkWriteResult.NotBroadcast("flag off") @@ -2236,7 +2274,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,7 +2431,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 + ) } } ) @@ -2418,7 +2459,14 @@ 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 } @@ -2427,6 +2475,17 @@ class ShieldedBalanceServiceImpl internal constructor( log.error("shielded {} failed and the tracked-lock evidence is unreadable", operation, 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, failure + ) + return SdkWriteResult.Ambiguous(failure) + } if (newLocks.isNotEmpty()) { log.error( "shielded {}: the L1 asset lock is out ({} tracked outpoint(s)) but the shield " + @@ -2593,6 +2652,79 @@ 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 shieldFromWalletToAddress( + toShieldedAddress: String, + amount: Dash, + expectedWalletIdHex: String + ): SdkWriteResult { + val recipientRaw43 = decodeOrchardAddress(toShieldedAddress, displayHrpSafe()) + ?: return notBroadcast("shieldFromWallet", "malformed or wrong-network shielded address", null) + return shieldFromWalletInternal( + amount, + fundingPath = null, + expectedWalletIdHex = expectedWalletIdHex, + externalRecipientRaw43 = recipientRaw43 + ) + } + + 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", 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()) @@ -2601,7 +2733,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) } } @@ -2617,12 +2749,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) } } @@ -2649,6 +2788,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") @@ -2665,7 +2806,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 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..ca4a91d184 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt @@ -0,0 +1,235 @@ +/* + * 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.isKeyUri(it) || DashConnectUri.isStUri(it) } + 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..6fb6ab99ef --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt @@ -0,0 +1,106 @@ +/* + * 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.PaymentURI +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 `dash:` URI with a BIP70 payment request (`r=`): the Basic invoice flow, as today. */ + 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]. [isDashConnect] is only consulted when [supportsConnect]; a + * BIP70 `dash:` link keeps the merchant invoice flow, everything else goes through + * [detectSendDestination]. + */ + fun scanActionFor( + input: String, + network: AddressNetwork, + supportsConnect: Boolean, + isDashConnect: (String) -> Boolean + ): AdvancedScanAction { + if (supportsConnect && isDashConnect(input)) return AdvancedScanAction.DashConnect(input) + if (isPaymentRequestUri(input)) return AdvancedScanAction.PaymentRequest(input) + return when (detectSendDestination(input, network)) { + is DestinationParse.Valid -> AdvancedScanAction.ExternalSend(input) + DestinationParse.WrongNetwork -> AdvancedScanAction.Error(wrongNetwork = true) + DestinationParse.Empty, DestinationParse.Invalid -> AdvancedScanAction.Error(wrongNetwork = false) + } + } + + private fun isPaymentRequestUri(input: String): Boolean { + val trimmed = input.trim() + if (!trimmed.startsWith("${AddressNetwork.DASH_SCHEME}:", ignoreCase = true)) return false + return try { + PaymentURI(null, trimmed).paymentRequestUrl != null + } catch (e: PaymentURI.ParseException) { + false + } + } + } + + 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..738ac73cf4 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -0,0 +1,132 @@ +/* + * 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.service.platform.sdk.ExternalSendResult +import de.schildbach.wallet.service.platform.sdk.ExternalSendService +import de.schildbach.wallet.service.platform.sdk.SendBalance +import de.schildbach.wallet.service.platform.sdk.SendDestination +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +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 org.dash.wallet.common.money.Dash +import org.slf4j.LoggerFactory +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. [toString] is redacted. + */ +data class ExternalSendRequest( + val source: SendBalance, + val destination: SendDestination, + val amount: Dash, + val isMax: Boolean +) { + 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 { + 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() +} + +/** + * 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. + * + * 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 @Inject constructor( + private val service: ExternalSendService, + private val applicationScope: CoroutineScope +) { + companion object { + private val log = LoggerFactory.getLogger(ExternalSendExecutor::class.java) + } + + private val _state = MutableStateFlow(ExternalSendExecution.Idle) + val state: StateFlow = _state.asStateFlow() + + /** + * Start sending [request]. Refused (false) while another send is running or an earlier + * outcome has not been acknowledged: one attempt per confirmation, and a terminal result + * is never silently replaced. + */ + fun submit(request: ExternalSendRequest): Boolean { + 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 + try { + result = service.send(request.source, request.destination, request.amount, request.isMax) + } 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", e) + } finally { + log.info("external send {} → {} finished: {}", request.source, kindOf(request.destination), kindOf(result)) + _state.value = ExternalSendExecution.Finished(request, result) + } + } + return true + } + + /** The screen showed [ExternalSendExecution.Finished]; the executor is free again. */ + fun acknowledge() { + _state.update { if (it is ExternalSendExecution.Finished) ExternalSendExecution.Idle else it } + } + + 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..6dde58472c --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt @@ -0,0 +1,153 @@ +/* + * 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.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_test.R +import kotlinx.coroutines.launch +import org.dash.wallet.common.services.AuthenticationManager +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 + + 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() } + ExternalSendScreen( + uiState = uiState, + actions = 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 + ) + ) + } + } + } + + private fun onBack() { + 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) + } + } + + private fun onResultClosed(result: ExternalSendResult) { + viewModel.onResultAcknowledged() + if (result !is ExternalSendResult.NotSent) { + leave() + } + } +} 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..9cf266efc2 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -0,0 +1,903 @@ +/* + * 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.padding +import androidx.compose.foundation.layout.size +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.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.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.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.ButtonData +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.ModalDialog +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 [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) + is ExternalSendStatus.Done -> ResultDialog(status.result) { actions.onResultClosed(status.result) } + ExternalSendStatus.Idle -> {} + } + } +} + +// ── 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 ───────────────────────────────────────────────────────────── + +@Composable +private fun AmountPage(uiState: ExternalSendUIState, actions: ExternalSendActions) { + val fiatCode = uiState.fiatCode + val codes = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE) + 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.status == ExternalSendStatus.Idle, + 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)) { + Card { + 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(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) + ) + } + } + ) + } + Card { + 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 Card(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. */ +@Composable +private fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color(0x800A0B0D)) + .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) {} + ) { + 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) + ) + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + ) { + ConfirmAmount(request.amount, uiState.rate, uiState.fiatCode) + 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), + value = confirm.total?.takeIf { fee != null }?.let { total -> + approximate(total.toDisplayString(), 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. */ +@Composable +private fun ConfirmAmount(amount: Dash, rate: Fiat?, fiatCode: String?) { + val separator = remember { decimalSeparatorFor(Locale.getDefault()) } + val fiat = amount.toFiatAt(rate) + EnterAmount( + primaryAmount = localizeAmountForDisplay(amount.toDisplayString(), separator), + secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", + currencyCodes = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE), + selectedCurrencyIndex = 0, + showMaxButton = false, + showBalanceButton = false, + showPrimaryChevron = false, + showSecondary = fiat != null, + showCurrencyPicker = false, + modifier = Modifier.padding(horizontal = 20.dp) + ) +} + +/** + * Figma 7107:48425: from the Shielded balance to anywhere but Shielded, the send is not instant + * and becomes public. An identity destination is paid into its Platform balance (AC8). + */ +@Composable +private fun ConfirmNotes(source: SendBalance, destination: SendDestination) { + val notes = buildList { + if (source == SendBalance.SHIELDED && destination !is SendDestination.Shielded) { + add(R.string.external_send_shielded_not_instant) + add( + 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 + } + ) + } + if (destination is SendDestination.Identity) { + add(R.string.external_send_identity_balance_note) + } + } + if (notes.isEmpty()) return + 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 -> + SystemMessage( + description = stringResource(note), + iconRes = org.dash.wallet.common.R.drawable.ic_info_blue + ) + } + } +} + +// ── 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. */ +@Composable +private fun ResultDialog(result: ExternalSendResult, onClose: () -> Unit) { + val content = resultContentFor(result) + ModalDialog( + showDialog = true, + onDismissRequest = onClose, + icon = ImageVector.vectorResource(content.icon), + heading = stringResource(content.title), + textBlocks = listOf(stringResource(content.message)), + buttons = listOf( + ButtonData( + label = stringResource(content.button), + onClick = onClose, + isPrimary = true, + 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): 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, + 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.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(balanceOf(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(balanceOf(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 +} + +/** The kind of balance a destination is paid into, for its icon and name. */ +private fun balanceOf(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 +} + +@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() + ) + } +} + +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..ad8c5e4fbf --- /dev/null +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -0,0 +1,600 @@ +/* + * 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.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.detectSendDestination +import de.schildbach.wallet.service.platform.sdk.externalSendSupport +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.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onEach +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 + +/** 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 { + object Idle : ExternalSendStatus() + + /** In flight; [shieldedLeg] = a ~30 s proof is involved. */ + data class Sending(val shieldedLeg: Boolean) : ExternalSendStatus() + + /** Terminal until acknowledged. */ + data class Done(val result: ExternalSendResult) : 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 +) { + /** Amount plus fee, or null while the fee is unknown. */ + val total: Dash? get() = fee?.let { request.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 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. + */ +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 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 +) { + /** 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 + + /** 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 ?: 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. */ + val limit: Dash? + get() = maxSendable ?: balance + + 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 && + balance != null && + !exceedsBalance && + (dashMode || rate != null) && + !identityBlocks && + status == ExternalSendStatus.Idle +} + +/** + * 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 +) : 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_SOURCE = "external_send_source" + internal const val KEY_SOURCE_CHOSEN = "external_send_source_chosen" + + 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() + + 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() + + 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) + + executor.state + .onEach { execution -> + val status = when (execution) { + ExternalSendExecution.Idle -> ExternalSendStatus.Idle + 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) + enterAmountStep(parse.destination, amount = null) + if (chosen && source != null) { + selectSource(source, byUser = true) + } + // After the source: a source change drops a Max amount. + _uiState.update { it.copy(amountText = amountText, dashMode = dashMode, maxAmount = maxAmount) } + saveAmount() + } + } + + // ── 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() { + 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, + maxAmount = if (sameDestination && amount == null) it.maxAmount 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.status != ExternalSendStatus.Idle) 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 + _uiState.update { it.copy(amountText = processAmountKeyInput(base, key, decimals), maxAmount = null) } + saveAmount() + } + + fun onCurrencySelected(dashMode: Boolean) { + val state = _uiState.value + if (state.dashMode == dashMode) return + if (!dashMode && state.rate == null) return + val text = if (state.amount.isZero) "0" else displayTextFor(state.amount, dashMode, state.rate) + _uiState.update { it.copy(dashMode = dashMode, amountText = text) } + saveAmount() + } + + fun onMaxClick() { + val state = _uiState.value + val max = state.maxSendable ?: return + if (state.status != ExternalSendStatus.Idle) return + _uiState.update { it.copy(maxAmount = max, amountText = displayTextFor(max, it.dashMode, it.rate)) } + saveAmount() + } + + fun onShowSourceSheet() { + _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 (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 { + it.copy( + source = source, + sourceChosenByUser = it.sourceChosenByUser || byUser, + maxAmount = if (changed) null else it.maxAmount, + balance = if (changed) null else it.balance, + maxSendable = if (changed) null else it.maxSendable + ) + } + 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 destination = 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) } + } + .mapLatest { balance -> if (balance == null) null else service.maxSendable(source, destination) } + .onEach { max -> + if (generation == balanceGeneration) _uiState.update { it.copy(maxSendable = max) } + } + .launchIn(viewModelScope) + } + + 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 + val request = ExternalSendRequest(state.source, destination, state.amount, state.isMax) + _uiState.update { it.copy(confirm = ExternalSendConfirm(request)) } + feeJob?.cancel() + feeJob = viewModelScope.launch { + val fee = service.estimateFee(request.source, request.destination, request.amount) + _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 + } + + /** + * 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 + executor.acknowledge() + if (status.result is ExternalSendResult.NotSent) { + _uiState.update { it.copy(maxAmount = null) } + } + } + + /** + * 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 + 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 + } +} 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..73ba79f112 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -0,0 +1,280 @@ +/* + * 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)) + assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.CORE, platform)) + 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() { + assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.PLATFORM, core)) + assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.PLATFORM, shielded)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, platform)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity)) + assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity, own = true)) + } + + @Test + fun matrix_identity() { + assertEquals(SendSupport.SUPPORTED, support(SendBalance.IDENTITY, core)) + assertEquals(SendSupport.NOT_SUPPORTED_YET, 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)) + } + } +} 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..dad3839158 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -0,0 +1,544 @@ +/* + * 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.SendEngineNotSyncedException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +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.dashfoundation.dashsdk.credits.FundingInput +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +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 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 shieldedBalance: Dash? = Dash(1_000_000L) + var platformBalances: () -> List = { emptyList() } + var shieldedResult: (Dash) -> SdkWriteResult = { SdkWriteResult.Broadcast(Unit) } + var shieldFromCoreResult: (Dash) -> SdkWriteResult = + { SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) } + var coreSend: () -> String = { "txid" } + var nativeWrite: () -> 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 suspend fun cutoverCommittedOrThrow(): Boolean = cutover() + override suspend fun shieldedEnabledOrThrow(): Boolean = shieldedOn() + override suspend fun ownIdentityIdOrThrow(): String? = ownIdentity + override fun observeOwnIdentityId(): Flow> = flowOf(Result.success(ownIdentity)) + override suspend fun managedIdentityIds(walletIdHex: String): List = managed + override fun observeCoreMaxSendableDuffs(): Flow = flowOf(coreMax) + override fun observeShieldedBalance(): Flow = flowOf(shieldedBalance) + override suspend fun platformAddressBalances(walletIdHex: String): List = platformBalances() + override suspend fun identityBalanceCredits(identityIdBase58: String): Long? = 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? = 2 + + 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 SdkWriteResult.Broadcast(1L) + } + + 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 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() + } + } + + private fun source( + bound: List = listOf(walletA), + ownIdentity: String? = ownIdBase58, + managed: List = listOf(ownId) + ) = FakeSource(bound.toMutableList(), ownIdentity, managed) + + private fun service(source: FakeSource) = + ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, ioDispatcher = Dispatchers.Unconfined) + + // ── Each supported pair: right seam, right units ────────────────── + + @Test + fun coreToCore_sendsThroughTheCoreFunnel_withTheCapturedSession_andMaxAsSendAll() = runBlocking { + val source = source() + val result = service(source).send(SendBalance.CORE, core, amount, 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(null), service(source).send(SendBalance.CORE, shielded, amount, false)) + assertEquals(listOf(amount), source.shieldedAmounts) + + source.shieldFromCoreResult = { SdkWriteResult.Broadcast(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY) } + assertEquals( + ExternalSendResult.InterruptedFundsReturnToShielded, + service(source).send(SendBalance.CORE, shielded, amount, false) + ) + } + + @Test + fun coreToOwnIdentity_topsUpInDuffs() = runBlocking { + val source = source() + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.CORE, ownIdentity, amount, false)) + assertEquals(listOf("coreTopUpIdentity"), source.calls) + assertEquals(100_000L, source.lastDuffs) + } + + @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) + assertEquals(listOf(amount), source.shieldedAmounts) + } + } + + @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 }, 60_000_000L), FundingInput(0, ByteArray(20) { 2 }, 70_000_000L)) + } + } + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, otherIdentity, amount, false)) + assertEquals(amountCredits, source.lastInputs?.sumOf { it.credits }) + assertArrayEquals(otherId, source.lastToId) + } + + @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, otherIdentity, 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) + assertEquals(amountCredits, source.lastCredits) + } + } + + // ── 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) + } + + // ── Gates: nothing is called ────────────────────────────────────── + + @Test + fun unsupportedPairs_areNotSupported_withNoSeamCall() = runBlocking { + val pairs = listOf( + SendBalance.CORE to platform, + SendBalance.PLATFORM to core, + SendBalance.PLATFORM to shielded, + SendBalance.IDENTITY to shielded, + 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.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, ioDispatcher = Dispatchers.Unconfined) + 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, 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, core)) + assertNull(service.maxSendable(SendBalance.PLATFORM, platform)) + } + + @Test + fun fees_areNullWhereNoPreSendFigureExists() = runBlocking { + val service = service(source()) + assertEquals(FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false), service.estimateFee(SendBalance.CORE, core, amount)) + assertEquals(FeeEstimate(Dash(2_001L), exact = false), service.estimateFee(SendBalance.SHIELDED, core, amount)) + assertNull(service.estimateFee(SendBalance.PLATFORM, platform, amount)) + assertNull(service.estimateFee(SendBalance.IDENTITY, core, amount)) + assertNull(service.estimateFee(SendBalance.CORE, ownIdentity, amount)) + } + + @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()) + } +} 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 632fe88987..4e29f6d19c 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -3554,6 +3554,78 @@ 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) + + assertEquals(SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED), result) + assertArrayEquals(recipientRaw43, source.lastFundRecipient) + assertEquals(Dash.COIN.duffs, source.lastFundAmountDuffs) + } + + @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) + assertEquals(SdkWriteResult.Broadcast(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY), 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..62af819ca5 --- /dev/null +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -0,0 +1,569 @@ +/* + * 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.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_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.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.dash.wallet.common.data.WalletUIConfig +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)) + 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() + var sendGate: CompletableDeferred? = null + var sendResult: ExternalSendResult = ExternalSendResult.Sent(null) + val sends = mutableListOf() + + 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, destination: SendDestination, amount: Dash) = fee + override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = max[source] + override suspend fun send( + source: SendBalance, + destination: SendDestination, + amount: Dash, + isMax: Boolean + ): ExternalSendResult { + sends += ExternalSendRequest(source, destination, amount, isMax) + return sendGate?.await() ?: sendResult + } + } + + private val service = FakeService() + private lateinit var executor: ExternalSendExecutor + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + executor = ExternalSendExecutor(service, CoroutineScope(UnconfinedTestDispatcher())) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun buildViewModel(savedState: SavedStateHandle = SavedStateHandle()): ExternalSendViewModel { + val walletUIConfig = mockk { + every { observe(WalletUIConfig.SELECTED_CURRENCY) } returns flowOf("USD") + } + val rates = mockk { + every { observeExchangeRate(any()) } returns flowOf(null) + } + 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 cannot pay a Platform address; Shielded can. + val platform = buildViewModel().apply { goToAmount(platformAddress) } + assertEquals(SendBalance.SHIELDED, platform.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) + + service.ownIdentity = true + val own = buildViewModel().apply { goToAmount(identityId) } + assertEquals(SendBalance.CORE, own.uiState.value.source) + } + + @Test + fun sourceSelection_ignoresUnsupportedAndUnlistedSources() { + val viewModel = buildViewModel() + viewModel.goToAmount(platformAddress) + + 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(platformAddress) + 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 continue_isBlockedForAnUnsupportedPair() { + val state = ExternalSendUIState( + step = ExternalSendStep.AMOUNT, + destination = SendDestination.Platform(platformAddress), + source = SendBalance.CORE, + amountText = "1", + balance = twoDash + ) + assertFalse(state.canContinueAmount) + assertTrue(state.copy(source = SendBalance.SHIELDED).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), + confirm.request + ) + assertEquals(service.fee, confirm.fee) + assertFalse(confirm.feeLoading) + assertEquals(twoDash + Dash(1_000), confirm.total) + assertEquals(confirm.request, viewModel.confirmedRequest()) + } + + @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) + assertTrue(viewModel.uiState.value.canContinueAmount) + } + + // ── 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) + ) + } +} From da452f796d0229c78ff847e7f136a41da27de672 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 17:16:47 -0800 Subject: [PATCH 03/30] fix(payments): address pre-review round 1 on External Send - Core->Shielded locks amount + pool fee so the recipient gets the confirmed amount; fee, Max and Total agree. - Core Max refuses when the balance changed since confirm; the confirm sheet shows a Max send as fee-inclusive, like Basic send-all. - The SDK wallet is captured at confirm and checked before every write. - An in-flight marker survives process death and restores the terminal "may have gone through" state instead of the editable form. - dash: URIs for Shielded/Platform/Identity amount requests parse. - The exact amount is pinned across a currency switch. - AddressUtils/WifKey reject an empty Base58Check payload instead of crashing; destination detection never throws. - Advanced scan keeps BIP70, AnyPay and serialized requests on the Basic invoice path. - Live identity/shielded reads recover after a transient error. Co-Authored-By: Claude Opus 5.5 --- .../common/payments/parsers/AddressNetwork.kt | 4 + .../wallet/common/payments/parsers/WifKey.kt | 15 +- .../payments/parsers/AddressParserTest.kt | 7 + .../common/payments/parsers/WifKeyTest.kt | 9 + wallet/res/values/strings.xml | 2 + .../platform/sdk/ExternalSendModels.kt | 89 ++++- .../platform/sdk/ExternalSendService.kt | 36 +- .../platform/sdk/ExternalSendServiceImpl.kt | 333 ++++++++++++------ .../wallet/ui/dashpay/utils/DashPayConfig.kt | 10 + .../ui/payments/send/AdvancedSendViewModel.kt | 48 ++- .../ui/payments/send/ExternalSendExecutor.kt | 144 +++++++- .../ui/payments/send/ExternalSendScreen.kt | 22 +- .../ui/payments/send/ExternalSendViewModel.kt | 84 ++++- .../platform/sdk/ExternalSendModelsTest.kt | 79 +++++ .../sdk/ExternalSendServiceImplTest.kt | 163 ++++++++- .../send/ExternalSendViewModelTest.kt | 281 ++++++++++++++- 16 files changed, 1137 insertions(+), 189 deletions(-) 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/values/strings.xml b/wallet/res/values/strings.xml index 890e11ebc8..d493e468f6 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -584,6 +584,8 @@ 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. + 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. diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 1f6ba01da1..fc72249b51 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -67,7 +67,7 @@ sealed class SendDestination { sealed class DestinationParse { /** * A destination of the wallet's network. [amount] is set only for a `dash:` payment - * URI that carried one (always a [SendDestination.Core]). + * 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 ""})" @@ -155,23 +155,41 @@ private val DASH_NETWORKS = listOf(AddressNetwork.DASH_MAINNET, AddressNetwork.D * whitespace is ignored; bech32m must be all-lowercase or all-uppercase (BIP-350) and * is returned lowercase. * - * A `dash:` payment URI with an address resolves to [SendDestination.Core] plus its - * optional amount, through the shared [PaymentURI] parser. 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. + * 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 { +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) +} - detectCoreAddress(trimmed, network)?.let { return it } - detectBech32mAddress(trimmed, network)?.let { return it } - decodeIdentityId(trimmed)?.let { - return DestinationParse.Valid(SendDestination.Identity(trimmed)) +/** 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 } @@ -216,6 +234,57 @@ private fun detectBech32mAddress(input: String, network: AddressNetwork): Destin } 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 { diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt index e24a10f64f..be370f54cc 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -56,6 +56,12 @@ enum class NotSentReason { /** 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, + /** Anything else refused before submission (including the wallet changing under the send). */ GENERIC } @@ -102,6 +108,13 @@ interface ExternalSendService { */ 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? @@ -111,17 +124,25 @@ interface ExternalSendService { /** Fee for this exact send, or null when it cannot be known before the send (never fabricated). */ suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? - /** Balance minus fee for Max, or null when unknown. */ + /** + * 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 every other pair the + * amount the recipient receives (balance minus the fee paid on top). + */ suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? /** * Send [amount] from [source] to [destination]. The caller has ALREADY * authenticated (PIN/biometric) for this send and passes exactly what the user - * confirmed. The implementation captures the wallet before its first suspension - * and re-checks it right before the native call (a change → 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). + * 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. @@ -130,6 +151,7 @@ interface ExternalSendService { source: SendBalance, destination: SendDestination, amount: Dash, - isMax: Boolean + isMax: Boolean, + expectedWalletIdHex: String? ): ExternalSendResult } diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index b30940d603..7be9b8a706 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -34,7 +34,6 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.emitAll @@ -43,6 +42,7 @@ import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.withContext import org.dash.wallet.common.money.Dash import org.dash.wallet.common.payments.parsers.AddressNetwork @@ -51,6 +51,7 @@ 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.dashfoundation.dashsdk.credits.FundingInput import org.slf4j.LoggerFactory import java.util.concurrent.atomic.AtomicBoolean @@ -136,6 +137,42 @@ internal fun selectPlatformInputs(candidates: List, targetCredits: return picked.takeIf { covered == targetCredits } } +/** + * 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) + +/** + * Keep a live observation alive across read failures: on a (non-cancellation) [Exception] + * emit [unknown] and re-subscribe after [retryDelayMs] (attempt counted from 0) — never + * complete on a transient error. A [Throwable] that is not an [Exception] is rethrown. + */ +internal fun Flow.retryReadErrors( + what: String, + unknown: T, + retryDelayMs: (Long) -> Long = ::readRetryDelayMs +): Flow = retryWhen { cause, attempt -> + if (cause is CancellationException || cause !is Exception) { + false + } else { + val delayMs = retryDelayMs(attempt) + retryLog.warn("external send: {} unreadable; unknown, retrying in {} ms", what, delayMs, cause) + emit(unknown) + delay(delayMs) + true + } +} + +private val retryLog = LoggerFactory.getLogger("de.schildbach.wallet.service.platform.sdk.ExternalSendRetry") + // ── Source seam ─────────────────────────────────────────────────────── /** @@ -152,6 +189,12 @@ internal interface ExternalSendSource { /** 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 @@ -161,7 +204,10 @@ internal interface ExternalSendSource { /** The user's registered identity (base58), null when there is none; throws when unreadable. */ suspend fun ownIdentityIdOrThrow(): String? - /** [ownIdentityIdOrThrow] as it changes; emits null-wrapped [Result.failure] on read errors. */ + /** + * [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). */ @@ -235,6 +281,8 @@ internal class DashSdkExternalSendSource( 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 = @@ -250,11 +298,7 @@ internal class DashSdkExternalSendSource( identityConfig.observePreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), identityConfig.observePreservingErrors(BlockchainIdentityConfig.CREATION_STATE) ) { id, state -> Result.success(ownIdentity(id, state)) } - .catch { e -> - if (e is CancellationException) throw e - log.warn("identity record unreadable; identity unknown", e) - emit(Result.failure(e)) - } + .retryReadErrors("identity record", Result.failure(IllegalStateException("identity record unreadable"))) /** A registered identity; an unknown creation state throws (unknown, not "none"). */ private fun ownIdentity(id: String?, state: String?): String? { @@ -290,11 +334,7 @@ internal class DashSdkExternalSendSource( } } } - .catch { e -> - if (e is CancellationException) throw e - log.warn("shielded balance unreadable", e) - emit(null) - } + .retryReadErrors("shielded balance", null) override suspend fun platformAddressBalances(walletIdHex: String): List = wallet(walletIdHex).addressesWithBalances() @@ -415,11 +455,15 @@ internal class DashSdkExternalSendSource( * [classifyBroadcastFailure]. * * Funds safety, in order, for every [send]: - * 1. the Core [WalletSession] is captured before anything suspends; + * 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 id is captured, then [externalSendSupport] is enforced here (not - * only in the UI) with the own-identity facts read from the SDK; + * 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; @@ -431,7 +475,8 @@ class ExternalSendServiceImpl internal constructor( private val source: ExternalSendSource, private val network: AddressNetwork, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, - private val balancePollMs: Long = BALANCE_POLL_MS + private val balancePollMs: Long = BALANCE_POLL_MS, + private val retryDelayMs: (Long) -> Long = ::readRetryDelayMs ) : ExternalSendService { @Inject @@ -475,11 +520,7 @@ class ExternalSendServiceImpl internal constructor( polled { _ -> this.source.identityBalanceCredits(id)?.takeIf { it >= 0 }?.let(::creditsToDash) } } } - }.catch { e -> - if (e is CancellationException) throw e - log.warn("external send: {} balance unreadable", source, e) - emit(null) - }.distinctUntilChanged() + }.retryReadErrors("$source balance", null, retryDelayMs).distinctUntilChanged() /** Poll [read] (null on failure) on IO every [balancePollMs] while collected. */ private fun polled(read: suspend (walletIdHex: String) -> Dash?): Flow = flow { @@ -499,9 +540,17 @@ class ExternalSendServiceImpl internal constructor( override fun observeHasIdentity(): Flow = source.observeOwnIdentityId() - .map { result -> if (result.isFailure) null else result.getOrNull() != null } + .map, Boolean?> { result -> if (result.isFailure) null else result.getOrNull() != null } + .retryReadErrors("identity record", null, retryDelayMs) .distinctUntilChanged() + override fun currentWalletIdOrNull(): String? = try { + source.currentBoundWalletIdOrNull() + } catch (e: Exception) { + log.warn("external send: bound wallet unreadable", e) + null + } + override suspend fun isOwnIdentity(identityIdBase58: String): Boolean? { val target = decodeIdentityId(identityIdBase58) ?: return false return try { @@ -554,8 +603,10 @@ class ExternalSendServiceImpl internal constructor( /** * - Core → Core: the SDK send's fee reserve ([SEND_ALL_FEE_RESERVE_DUFFS]), an upper * bound the real (smaller) fee never exceeds — the same figure the Basic send shows. - * - Core → Shielded: the shield pool fee (flat shielded fee + asset-lock base cost), - * carved out of the locked amount; the L1 fee is extra and unknown, so not exact. + * 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. * - Shielded → *: the flat single-note pool fee of the transition; more notes cost more. * - Core → Identity, Platform → *, Identity → *: Rust meters these at execution; no * pre-send figure exists, so null. @@ -565,10 +616,7 @@ class ExternalSendServiceImpl internal constructor( SendBalance.CORE -> when (destination) { is SendDestination.Core -> FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false) is SendDestination.Shielded -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { - FeeEstimate( - Dash(Math.addExact(ceilCreditsToDuffs(it), ShieldedBalanceServiceImpl.ASSET_LOCK_BASE_COST_DUFFS)), - exact = false - ) + FeeEstimate(Dash(shieldPoolFeeDuffs(it)), exact = false) } else -> null } @@ -579,9 +627,11 @@ class ExternalSendServiceImpl internal constructor( } /** - * - Core → Core / Shielded: the SDK's max-sendable L1 figure (already net of the - * send-all fee headroom); a Max Core→Shielded send retries once with an L1 reserve - * if the lock selection comes up short. + * - 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). + * - Core → Shielded: that figure minus the shield pool fee (what the recipient receives + * when the whole balance is locked); a Max send retries once with an L1 reserve if + * the lock selection comes up short. * - Shielded → *: the READY balance minus the single-note pool fee; a Max send also * retries once with the exact deficit the note selection reports. * - Everything else: null (no pre-send fee figure). @@ -589,8 +639,19 @@ class ExternalSendServiceImpl internal constructor( override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = try { when (source) { SendBalance.CORE -> when (destination) { - is SendDestination.Core, is SendDestination.Shielded -> + is SendDestination.Core -> this.source.observeCoreMaxSendableDuffs().first()?.takeIf { it > 0 }?.let(::Dash) + is SendDestination.Shielded -> { + val max = this.source.observeCoreMaxSendableDuffs().first() + val feeCredits = withContext(ioDispatcher) { + this@ExternalSendServiceImpl.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER) + } + if (max == null || feeCredits == null) { + null + } else { + (max - shieldPoolFeeDuffs(feeCredits)).takeIf { it > 0 }?.let(::Dash) + } + } else -> null } SendBalance.SHIELDED -> { @@ -619,7 +680,8 @@ class ExternalSendServiceImpl internal constructor( source: SendBalance, destination: SendDestination, amount: Dash, - isMax: Boolean + isMax: Boolean, + expectedWalletIdHex: String? ): ExternalSendResult { // (1) Captured before anything can suspend. val coreSession = if (source == SendBalance.CORE && destination is SendDestination.Core) { @@ -633,7 +695,9 @@ class ExternalSendServiceImpl internal constructor( return ExternalSendResult.NotSent(NotSentReason.IN_PROGRESS) } return try { - withContext(ioDispatcher) { sendInner(source, destination, amount, isMax, coreSession) } + withContext(ioDispatcher) { + sendInner(source, destination, amount, isMax, coreSession, expectedWalletIdHex) + } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -651,7 +715,8 @@ class ExternalSendServiceImpl internal constructor( destination: SendDestination, amount: Dash, isMax: Boolean, - coreSession: WalletSession? + coreSession: WalletSession?, + expectedWalletIdHex: String? ): ExternalSendResult { val pair = "$source → ${kindOf(destination)}" if (!amount.isPositive) return notSent(pair, NotSentReason.GENERIC, "non-positive amount") @@ -669,9 +734,11 @@ class ExternalSendServiceImpl internal constructor( if (!shielded) return notSent(pair, NotSentReason.NOT_SUPPORTED, "shielded flag off") } - // (4) Wallet captured, support gate enforced here. - val walletIdHex = readOrNull("bound wallet") { this.source.boundWalletIdOrNull() } - ?: return notSent(pair, NotSentReason.GENERIC, "no bound SDK wallet") + // (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() @@ -736,52 +803,100 @@ class ExternalSendServiceImpl internal constructor( amount: Dash, isMax: Boolean, coreSession: WalletSession? - ): ExternalSendResult = when (destination) { - is SendDestination.Core -> { - if (!stillBound(pair, walletIdHex)) { - ExternalSendResult.NotSent(NotSentReason.GENERIC) - } else { - 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, e) } + ): ExternalSendResult { + return when (destination) { + is SendDestination.Core -> sendCoreToCore(pair, walletIdHex, destination, amount, isMax, coreSession) + is SendDestination.Shielded -> sendCoreToShielded(pair, walletIdHex, destination, amount, isMax) + is SendDestination.Identity -> { + if (!stillBound(pair, walletIdHex)) { + ExternalSendResult.NotSent(NotSentReason.GENERIC) + } else { + mapWrite(pair, this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) } } + is SendDestination.Platform -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") } - is SendDestination.Shielded -> { - var result = shieldFromCoreChecked(pair, walletIdHex, destination.address, amount) - val first = result - if (isMax && first is SdkWriteResult.NotBroadcast && isAssetLockSelectionShort(first)) { - val reserve = this.source.spendableUtxoCount()?.let(::assetLockMaxFeeReserve) - val adjusted = reserve?.let { amount - it } - if (adjusted != null && adjusted.isPositive) { - log.info("external send {}: max shield short; retrying once with an L1 fee reserve", pair) - result = shieldFromCoreChecked(pair, walletIdHex, destination.address, adjusted) - } + } + + /** + * A Max is the SDK drain (`emptyWallet`), whose amount is display-only: it spends + * whatever is spendable when it runs. So the drain is only started while the SDK's + * max-sendable figure is still exactly the [amount] the user confirmed; anything else + * (funds arrived or left in between, or unreadable) is NotSent with nothing spent. + */ + 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, e) + return ExternalSendResult.NotSent(NotSentReason.GENERIC) } - when (result) { - is SdkWriteResult.Broadcast -> when (result.value) { - ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) - ShieldFromWalletOutcome.SHIELD_PENDING_RETRY -> { - log.warn("external send {}: lock out, shield not submitted — returns to own shielded", pair) - ExternalSendResult.InterruptedFundsReturnToShielded - } - } - else -> mapWrite(pair, result) + if (maxNow != amount.duffs) { + return notSent(pair, NotSentReason.BALANCE_CHANGED, "the balance changed since the Max was confirmed") } } - is SendDestination.Identity -> { - if (!stillBound(pair, walletIdHex)) { - ExternalSendResult.NotSent(NotSentReason.GENERIC) - } else { - mapWrite(pair, this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) + 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, e) } + } + } + + /** + * The recipient receives the confirmed [amount]: the lock is `amount + pool fee` + * ([shieldPoolFeeDuffs]), the fee Rust carves out of the lock. A Max whose lock + * selection comes up short (the L1 fee) retries once with an L1 reserve taken off the + * lock, so the recipient then receives that much less (never more than confirmed). + */ + private suspend fun sendCoreToShielded( + pair: String, + walletIdHex: String, + destination: SendDestination.Shielded, + amount: Dash, + isMax: Boolean + ): 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") + } + var result = shieldFromCoreChecked(pair, walletIdHex, destination.address, lock) + val first = result + if (isMax && first is SdkWriteResult.NotBroadcast && isAssetLockSelectionShort(first)) { + val reserve = this.source.spendableUtxoCount()?.let(::assetLockMaxFeeReserve) + val adjusted = reserve?.let { lock - it } + if (adjusted != null && adjusted.isPositive) { + log.info("external send {}: max shield short; retrying once with an L1 fee reserve", pair) + result = shieldFromCoreChecked(pair, walletIdHex, destination.address, adjusted) } } - is SendDestination.Platform -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") + return when (result) { + is SdkWriteResult.Broadcast -> when (result.value) { + ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) + 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( @@ -837,23 +952,25 @@ class ExternalSendServiceImpl internal constructor( walletIdHex: String, destination: SendDestination, amountCredits: Long - ): ExternalSendResult = when (destination) { - 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") - val inputs = selectPlatformInputs(candidates, amountCredits) - ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount") - nativeWrite(pair, walletIdHex) { this.source.platformTopUpIdentity(walletIdHex, identityId, inputs) } + ): ExternalSendResult { + return when (destination) { + 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") + val inputs = selectPlatformInputs(candidates, amountCredits) + ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount") + nativeWrite(pair, walletIdHex) { this.source.platformTopUpIdentity(walletIdHex, identityId, inputs) } + } + else -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") } - else -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") } private suspend fun sendFromIdentity( @@ -862,24 +979,26 @@ class ExternalSendServiceImpl internal constructor( fromId: ByteArray, destination: SendDestination, amountCredits: Long - ): ExternalSendResult = when (destination) { - is SendDestination.Core -> - nativeWrite(pair, walletIdHex) { - this.source.identityWithdraw(walletIdHex, fromId, amountCredits, destination.address) + ): ExternalSendResult { + return when (destination) { + is SendDestination.Core -> + nativeWrite(pair, walletIdHex) { + this.source.identityWithdraw(walletIdHex, fromId, amountCredits, 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.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 -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") } - 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 -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") } /** One raw SDK credits call, after the wallet re-check, classified by [classifyBroadcastFailure]. */ 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..8eec1b7448 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,16 @@ 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") + /** * `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/send/AdvancedSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt index 6fb6ab99ef..ddd474cd28 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendViewModel.kt @@ -30,7 +30,8 @@ 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.PaymentURI +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 @@ -42,7 +43,12 @@ sealed class AdvancedScanAction { /** A DashConnect `dash-key:` / `dash-st:` code, for the Connections screen. */ data class DashConnect(val input: String) : AdvancedScanAction() - /** A `dash:` URI with a BIP70 payment request (`r=`): the Basic invoice flow, as today. */ + /** + * 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]. */ @@ -61,9 +67,12 @@ class AdvancedSendViewModel @Inject constructor( companion object { /** - * Route a scanned [input]. [isDashConnect] is only consulted when [supportsConnect]; a - * BIP70 `dash:` link keeps the merchant invoice flow, everything else goes through - * [detectSendDestination]. + * 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, @@ -72,23 +81,24 @@ class AdvancedSendViewModel @Inject constructor( isDashConnect: (String) -> Boolean ): AdvancedScanAction { if (supportsConnect && isDashConnect(input)) return AdvancedScanAction.DashConnect(input) - if (isPaymentRequestUri(input)) return AdvancedScanAction.PaymentRequest(input) - return when (detectSendDestination(input, network)) { - is DestinationParse.Valid -> AdvancedScanAction.ExternalSend(input) - DestinationParse.WrongNetwork -> AdvancedScanAction.Error(wrongNetwork = true) - DestinationParse.Empty, DestinationParse.Invalid -> AdvancedScanAction.Error(wrongNetwork = false) + 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) } } - private fun isPaymentRequestUri(input: String): Boolean { - val trimmed = input.trim() - if (!trimmed.startsWith("${AddressNetwork.DASH_SCHEME}:", ignoreCase = true)) return false - return try { - PaymentURI(null, trimmed).paymentRequestUrl != null - } catch (e: PaymentURI.ParseException) { - 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()) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index 738ac73cf4..662c58c951 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -19,15 +19,19 @@ package de.schildbach.wallet.ui.payments.send 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.ui.dashpay.utils.DashPayConfig import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope +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 javax.inject.Inject @@ -35,25 +39,55 @@ import javax.inject.Singleton /** * Exactly what the user confirmed on the confirm sheet: captured BEFORE authentication and - * passed to [ExternalSendService.send] unchanged. [toString] is redacted. + * 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 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() +} + +/** + * 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) } /** @@ -63,25 +97,59 @@ sealed class ExternalSendExecution { * [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 only on a definitive Sent / Not sent, and on an + * unknown outcome only when the user acknowledges it. A fresh process that finds it set (or + * cannot read it) starts in [ExternalSendExecution.InterruptedByRestart]. + * * 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 @Inject constructor( +class ExternalSendExecutor internal constructor( private val service: ExternalSendService, + private val marker: ExternalSendInFlightMarker, private val applicationScope: CoroutineScope ) { + @Inject + constructor( + service: ExternalSendService, + dashPayConfig: DashPayConfig, + applicationScope: CoroutineScope + ) : this(service, DashPayConfigInFlightMarker(dashPayConfig), applicationScope) + companion object { private val log = LoggerFactory.getLogger(ExternalSendExecutor::class.java) } - private val _state = MutableStateFlow(ExternalSendExecution.Idle) + private val _state = MutableStateFlow(ExternalSendExecution.Restoring) val state: StateFlow = _state.asStateFlow() + 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", 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 + } + } + } + } + /** - * Start sending [request]. Refused (false) while another send is running or an earlier - * outcome has not been acknowledged: one attempt per confirmation, and a terminal result - * is never silently replaced. + * 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 { var accepted = false @@ -100,8 +168,27 @@ class ExternalSendExecutor @Inject constructor( } applicationScope.launch { var result: ExternalSendResult = ExternalSendResult.MayHaveGoneThrough + var marked = false try { - result = service.send(request.source, request.destination, request.amount, request.isMax) + 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", e) + 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". @@ -110,17 +197,54 @@ class ExternalSendExecutor @Inject constructor( log.error("external send threw; outcome unknown", e) } finally { log.info("external send {} → {} finished: {}", request.source, kindOf(request.destination), kindOf(result)) + // 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 && isDefinitive(result)) { + withContext(NonCancellable) { clearMarker() } + } _state.value = ExternalSendExecution.Finished(request, result) } } return true } - /** The screen showed [ExternalSendExecution.Finished]; the executor is free again. */ + /** + * The screen showed the outcome; the executor is free again. An unknown outcome (or a + * restart-interrupted one) clears the marker first, and only then becomes Idle, so the + * clear can never race a new send's marker. + */ fun acknowledge() { - _state.update { if (it is ExternalSendExecution.Finished) ExternalSendExecution.Idle else it } + val current = _state.value + val needsClear = when (current) { + is ExternalSendExecution.Finished -> !isDefinitive(current.result) + ExternalSendExecution.InterruptedByRestart -> true + else -> return + } + if (!needsClear) { + _state.update { if (it === current) ExternalSendExecution.Idle else it } + return + } + applicationScope.launch { + clearMarker() + _state.update { if (it === current) ExternalSendExecution.Idle else it } + } } + 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", e) + } + } + + /** Sent and Not sent are definitive; anything else may have moved money. */ + private fun isDefinitive(result: ExternalSendResult): Boolean = + result is ExternalSendResult.Sent || result is ExternalSendResult.NotSent + private fun kindOf(destination: SendDestination): String = destination::class.java.simpleName private fun kindOf(result: ExternalSendResult): String = when (result) { diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index 9cf266efc2..dfb8c4cb7b 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -149,8 +149,9 @@ fun ExternalSendScreen(uiState: ExternalSendUIState, actions: ExternalSendAction when (val status = uiState.status) { is ExternalSendStatus.Sending -> SendingOverlay(status.shieldedLeg, actions.onLeave) - is ExternalSendStatus.Done -> ResultDialog(status.result) { actions.onResultClosed(status.result) } - ExternalSendStatus.Idle -> {} + is ExternalSendStatus.Done -> + ResultDialog(status.result, status.afterRestart) { actions.onResultClosed(status.result) } + ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} } } } @@ -581,7 +582,8 @@ private fun ConfirmSheet(uiState: ExternalSendUIState, confirm: ExternalSendConf .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { - ConfirmAmount(request.amount, uiState.rate, uiState.fiatCode) + // What the recipient receives (a Core Max drain: the amount minus the fee). + ConfirmAmount(confirm.recipientAmount, uiState.rate, uiState.fiatCode) Spacer(modifier = Modifier.height(20.dp)) Menu { ListItem1( @@ -604,8 +606,9 @@ private fun ConfirmSheet(uiState: ExternalSendUIState, confirm: ExternalSendConf ) DashValueRow( label = stringResource(R.string.external_send_total), - value = confirm.total?.takeIf { fee != null }?.let { total -> - approximate(total.toDisplayString(), fee?.exact != true) + // 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 ) @@ -771,8 +774,8 @@ private fun SendingOverlay(shieldedLeg: Boolean, onLeave: () -> Unit) { /** The terminal outcome. Only Not sent offers to go back and edit; nothing offers a retry. */ @Composable -private fun ResultDialog(result: ExternalSendResult, onClose: () -> Unit) { - val content = resultContentFor(result) +private fun ResultDialog(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { + val content = resultContentFor(result, afterRestart) ModalDialog( showDialog = true, onDismissRequest = onClose, @@ -798,7 +801,7 @@ internal data class ResultContent( @StringRes val button: Int ) -internal fun resultContentFor(result: ExternalSendResult): ResultContent = when (result) { +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, @@ -814,7 +817,7 @@ internal fun resultContentFor(result: ExternalSendResult): ResultContent = when ExternalSendResult.MayHaveGoneThrough -> ResultContent( org.dash.wallet.common.R.drawable.ic_toast_info_warning, R.string.external_send_ambiguous_title, - R.string.external_send_ambiguous_message, + 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( @@ -833,6 +836,7 @@ internal fun notSentMessageFor(reason: NotSentReason): Int = when (reason) { 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.GENERIC -> R.string.external_send_not_sent_generic } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index ad8c5e4fbf..d85a1572dd 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -64,13 +64,19 @@ 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. */ - data class Done(val result: ExternalSendResult) : 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() } /** @@ -82,8 +88,19 @@ data class ExternalSendConfirm( val fee: FeeEstimate? = null, val feeLoading: Boolean = true ) { - /** Amount plus fee, or null while the fee is unknown. */ - val total: Dash? get() = fee?.let { request.amount + it.fee } + /** + * 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 + + /** What the recipient receives: the amount, or for a drain the amount minus the fee (when known). */ + val recipientAmount: Dash + get() = if (feeIncluded) fee?.let { request.amount - it.fee } ?: request.amount else request.amount + + /** What leaves the balance: amount plus fee (null while the fee is unknown), or for a drain the amount. */ + val total: Dash? get() = if (feeIncluded) request.amount else fee?.let { request.amount + it.fee } } /** @@ -92,6 +109,9 @@ data class ExternalSendConfirm( * @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 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. @@ -106,6 +126,7 @@ data class ExternalSendUIState( val amountText: String = "0", val dashMode: Boolean = true, val maxAmount: Dash? = null, + val pinnedAmount: Dash? = null, val fiatCode: String? = null, val rate: Fiat? = null, val source: SendBalance = SendBalance.CORE, @@ -141,7 +162,7 @@ data class ExternalSendUIState( /** The amount in Dash (fiat converted at [rate]); zero when unparseable or no rate. */ val amount: Dash - get() = maxAmount ?: if (dashMode) { + get() = maxAmount ?: pinnedAmount ?: if (dashMode) { parseDashOrNull(amountText) ?: Dash.ZERO } else { val code = fiatCode @@ -174,7 +195,7 @@ data class ExternalSendUIState( amount.isPositive && balance != null && !exceedsBalance && - (dashMode || rate != null) && + (dashMode || rate != null || pinnedAmount != null || maxAmount != null) && !identityBlocks && status == ExternalSendStatus.Idle } @@ -221,6 +242,7 @@ class ExternalSendViewModel internal constructor( 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_PINNED_DUFFS = "external_send_pinned_duffs" internal const val KEY_SOURCE = "external_send_source" internal const val KEY_SOURCE_CHOSEN = "external_send_source_chosen" @@ -266,6 +288,9 @@ class ExternalSendViewModel internal constructor( executor.state .onEach { execution -> val status = when (execution) { + ExternalSendExecution.Restoring -> ExternalSendStatus.Restoring + ExternalSendExecution.InterruptedByRestart -> + ExternalSendStatus.Done(ExternalSendResult.MayHaveGoneThrough, afterRestart = true) ExternalSendExecution.Idle -> ExternalSendStatus.Idle is ExternalSendExecution.Sending -> ExternalSendStatus.Sending( hasShieldedLeg(execution.request.source, execution.request.destination) @@ -302,12 +327,15 @@ class ExternalSendViewModel internal constructor( 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 pinnedAmount = savedState.get(KEY_PINNED_DUFFS)?.let(::Dash) enterAmountStep(parse.destination, amount = null) if (chosen && source != null) { selectSource(source, byUser = true) } // After the source: a source change drops a Max amount. - _uiState.update { it.copy(amountText = amountText, dashMode = dashMode, maxAmount = maxAmount) } + _uiState.update { + it.copy(amountText = amountText, dashMode = dashMode, maxAmount = maxAmount, pinnedAmount = pinnedAmount) + } saveAmount() } } @@ -364,6 +392,8 @@ class ExternalSendViewModel internal constructor( amountText = amount?.toKeypadString() ?: if (sameDestination) it.amountText else "0", dashMode = if (amount != null) true else it.dashMode, maxAmount = if (sameDestination && amount == null) it.maxAmount else null, + // 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 ) @@ -386,7 +416,10 @@ class ExternalSendViewModel internal constructor( // 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 - _uiState.update { it.copy(amountText = processAmountKeyInput(base, key, decimals), maxAmount = null) } + val text = processAmountKeyInput(base, key, decimals) + // A key the keypad rejected (text unchanged) keeps the exact amount. + if (text == state.amountText && !state.isMax) return + _uiState.update { it.copy(amountText = text, maxAmount = null, pinnedAmount = null) } saveAmount() } @@ -394,8 +427,17 @@ class ExternalSendViewModel internal constructor( val state = _uiState.value if (state.dashMode == dashMode) return if (!dashMode && state.rate == null) return - val text = if (state.amount.isZero) "0" else displayTextFor(state.amount, dashMode, state.rate) - _uiState.update { it.copy(dashMode = dashMode, amountText = text) } + 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() } @@ -403,7 +445,9 @@ class ExternalSendViewModel internal constructor( val state = _uiState.value val max = state.maxSendable ?: return if (state.status != ExternalSendStatus.Idle) return - _uiState.update { it.copy(maxAmount = max, amountText = displayTextFor(max, it.dashMode, it.rate)) } + _uiState.update { + it.copy(maxAmount = max, pinnedAmount = null, amountText = displayTextFor(max, it.dashMode, it.rate)) + } saveAmount() } @@ -436,10 +480,13 @@ class ExternalSendViewModel internal constructor( source = source, sourceChosenByUser = it.sourceChosenByUser || byUser, maxAmount = if (changed) null else it.maxAmount, + // A dropped Max keeps its exact amount (no longer Max): its text may be rounded fiat. + pinnedAmount = if (changed && it.isMax) it.amount else it.pinnedAmount, 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) { @@ -510,7 +557,15 @@ class ExternalSendViewModel internal constructor( val state = _uiState.value if (!state.canContinueAmount) return val destination = state.destination ?: return - val request = ExternalSendRequest(state.source, destination, state.amount, state.isMax) + // 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 { @@ -559,7 +614,9 @@ class ExternalSendViewModel internal constructor( val status = _uiState.value.status as? ExternalSendStatus.Done ?: return executor.acknowledge() if (status.result is ExternalSendResult.NotSent) { - _uiState.update { it.copy(maxAmount = null) } + // Max is chosen again deliberately; the amount it was stays exact. + _uiState.update { it.copy(maxAmount = null, pinnedAmount = if (it.isMax) it.amount else it.pinnedAmount) } + saveAmount() } } @@ -596,5 +653,6 @@ class ExternalSendViewModel internal constructor( savedState[KEY_AMOUNT] = state.amountText savedState[KEY_DASH_MODE] = state.dashMode savedState[KEY_MAX_DUFFS] = state.maxAmount?.duffs + savedState[KEY_PINNED_DUFFS] = state.pinnedAmount?.duffs } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt index 73ba79f112..d77b4a3ee3 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -277,4 +277,83 @@ class ExternalSendModelsTest { 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) + } + } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index dad3839158..bff1ddec5b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -18,12 +18,16 @@ package de.schildbach.wallet.service.platform.sdk 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.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 org.dash.wallet.common.money.Dash @@ -93,13 +97,16 @@ class ExternalSendServiceImplTest { 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 - override fun observeOwnIdentityId(): Flow> = flowOf(Result.success(ownIdentity)) + var identityFlow: Flow>? = null + override fun observeOwnIdentityId(): Flow> = identityFlow ?: flowOf(Result.success(ownIdentity)) override suspend fun managedIdentityIds(walletIdHex: String): List = managed override fun observeCoreMaxSendableDuffs(): Flow = flowOf(coreMax) - override fun observeShieldedBalance(): Flow = flowOf(shieldedBalance) + var shieldedFlow: Flow? = null + override fun observeShieldedBalance(): Flow = shieldedFlow ?: flowOf(shieldedBalance) override suspend fun platformAddressBalances(walletIdHex: String): List = platformBalances() override suspend fun identityBalanceCredits(identityIdBase58: String): Long? = 2_000_000_000L override suspend fun identityExists(identityIdBase58: String): Boolean = identityIdBase58 == ownIdentity @@ -195,12 +202,21 @@ class ExternalSendServiceImplTest { private fun service(source: FakeSource) = ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, ioDispatcher = Dispatchers.Unconfined) + /** 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() - val result = service(source).send(SendBalance.CORE, core, amount, isMax = true) + // 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) @@ -211,7 +227,8 @@ class ExternalSendServiceImplTest { fun coreToShielded_completed_isSent_pendingRetry_isInterrupted() = runBlocking { val source = source() assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.CORE, shielded, amount, false)) - assertEquals(listOf(amount), source.shieldedAmounts) + // 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(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY) } assertEquals( @@ -541,4 +558,142 @@ class ExternalSendServiceImplTest { 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, shielded, amount)) + // Max: the whole Core max is locked, the recipient receives it minus the pool fee. + val max = requireNotNull(service.maxSendable(SendBalance.CORE, shielded)) + assertEquals(Dash(5_000_000L) - poolFee, max) + assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, shielded, max, isMax = true)) + assertEquals(listOf(Dash(5_000_000L)), source.shieldedAmounts) + } + + @Test + fun coreToShieldedMax_selectionShort_retriesWithTheReserveOffTheLock() = runBlocking { + val source = source().apply { + shieldFromCoreResult = { value -> + if (value == Dash(5_000_000L)) { + SdkWriteResult.NotBroadcast("asset lock coin selection is short") + } else { + SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) + } + } + } + val service = service(source) + val max = requireNotNull(service.maxSendable(SendBalance.CORE, shielded)) + assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, shielded, max, isMax = true)) + assertEquals(2, source.shieldedAmounts.size) + assertEquals(Dash(5_000_000L) - assetLockMaxFeeReserve(2), source.shieldedAmounts[1]) + } + + @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, ioDispatcher = Dispatchers.Unconfined) + .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.SHIELDED to core, + SendBalance.PLATFORM to platform, + SendBalance.PLATFORM to otherIdentity, + 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, + ioDispatcher = Dispatchers.Unconfined, + retryDelayMs = { 0L } + ) + assertEquals(listOf(null, true), service.observeHasIdentity().take(2).toList()) + assertEquals(listOf(null, Dash(7L)), service.observeBalance(SendBalance.SHIELDED).take(2).toList()) + } + + @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("identity record", Result.failure(IllegalStateException("unknown")), retryDelayMs = { 0L }) + .take(3) + .toList() + assertTrue(values[0].isFailure) + assertTrue(values[1].isFailure) + assertEquals("id", values[2].getOrNull()) + } } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 62af819ca5..e788e1535c 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -41,6 +41,7 @@ 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 @@ -80,7 +81,9 @@ class ExternalSendViewModelTest { 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 @@ -91,33 +94,69 @@ class ExternalSendViewModelTest { source: SendBalance, destination: SendDestination, amount: Dash, - isMax: Boolean + isMax: Boolean, + expectedWalletIdHex: String? ): ExternalSendResult { - sends += ExternalSendRequest(source, destination, amount, isMax) + sends += ExternalSendRequest(source, destination, amount, isMax, expectedWalletIdHex) return sendGate?.await() ?: sendResult } } + /** 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() + + override suspend fun isSet(): Boolean { + if (failReads) throw java.io.IOException("datastore") + return value + } + + override suspend fun set() { + if (failWrites) throw java.io.IOException("datastore") + log += "set" + value = true + } + + override suspend fun clear() { + 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 @Before fun setUp() { Dispatchers.setMain(UnconfinedTestDispatcher()) - executor = ExternalSendExecutor(service, CoroutineScope(UnconfinedTestDispatcher())) + executor = newExecutor() } + private fun newExecutor() = ExternalSendExecutor(service, marker, CoroutineScope(UnconfinedTestDispatcher())) + @After fun tearDown() { Dispatchers.resetMain() } - private fun buildViewModel(savedState: SavedStateHandle = SavedStateHandle()): ExternalSendViewModel { + 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(null) + every { observeExchangeRate(any()) } returns flowOf(rate) } return ExternalSendViewModel(service, executor, walletUIConfig, rates, savedState, network) } @@ -341,12 +380,15 @@ class ExternalSendViewModelTest { val confirm = requireNotNull(viewModel.uiState.value.confirm) assertEquals( - ExternalSendRequest(SendBalance.CORE, SendDestination.Core(coreAddress), twoDash, isMax = true), + ExternalSendRequest(SendBalance.CORE, SendDestination.Core(coreAddress), twoDash, isMax = true, WALLET_A), confirm.request ) assertEquals(service.fee, confirm.fee) assertFalse(confirm.feeLoading) - assertEquals(twoDash + Dash(1_000), confirm.total) + // 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()) } @@ -566,4 +608,229 @@ class ExternalSendViewModelTest { AdvancedSendViewModel.scanActionFor(mainnetCoreAddress, network, true, connect) ) } + + // ── 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_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_andClearedOnADefinitiveResult() { + val gate = CompletableDeferred() + service.sendGate = gate + sendOnce() + assertEquals(1, service.sends.size) + assertTrue("set before the service runs", marker.value) + gate.complete(ExternalSendResult.Sent("txid")) + assertFalse(marker.value) + assertEquals(listOf("set", "clear"), marker.log) + + executor.acknowledge() + 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 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 aDroppedMax_keepsItsExactAmount() { + val max = Dash(123_456_789) + service.balances.getValue(SendBalance.SHIELDED).value = twoDash + service.balances.getValue(SendBalance.PLATFORM).value = twoDash + service.max[SendBalance.SHIELDED] = max + val viewModel = buildViewModel(rate = usd100) + viewModel.goToAmount(platformAddress) + viewModel.onMaxClick() + viewModel.onCurrencySelected(dashMode = false) + assertEquals(max, viewModel.uiState.value.amount) + + viewModel.onSourceSelected(SendBalance.PLATFORM) + assertFalse(viewModel.uiState.value.isMax) + assertEquals(max, viewModel.uiState.value.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) + ) + } } From 4a57407099616d4b939ee762e7f2b804202364dd Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 19:16:50 -0800 Subject: [PATCH 04/30] fix(payments): address pre-review round 2 on External Send MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Keep the in-flight marker after a Sent until the user acknowledges it, so a process kill before the result is seen warns instead of reopening the form. - Claim an acknowledgement atomically (new Acknowledging state) before clearing the marker, so a duplicate acknowledgement cannot clear a later send's marker. - Core→Core: size the fee reserve by UTXO count and turn Max off when the balance does not exceed it, so the recipient amount is always positive. - Core→Shielded Max now comes from the confirmed balance an asset lock can spend, with the L1 fee reserved up front; the Max retry is gone. The Core Max drain is still uncapped by the confirmed amount (finding 1); it is left for device testing. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendServiceImpl.kt | 101 +++++++++++------- .../ui/payments/send/ExternalSendExecutor.kt | 42 +++++--- .../ui/payments/send/ExternalSendViewModel.kt | 2 + .../sdk/ExternalSendServiceImplTest.kt | 83 +++++++++++--- .../send/ExternalSendViewModelTest.kt | 52 ++++++++- 5 files changed, 205 insertions(+), 75 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 7be9b8a706..417ea3c17b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -27,7 +27,6 @@ import de.schildbach.wallet.payments.SendSignerLockedException 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.isAssetLockSelectionShort import de.schildbach.wallet.ui.shielded.shieldedMaxFeeAdjustment import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher @@ -215,6 +214,14 @@ internal interface ExternalSendSource { // 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 — in duffs; + * null when 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? @@ -319,6 +326,16 @@ internal class DashSdkExternalSendSource( if (committed == true) (maxSendable ?: total)?.value else null } + override suspend fun coreAssetLockEligibleDuffs(): Long? = + combine( + sdkL1SendService.cutoverCommittedFlow(), + cutoverUiDataService.sdkConfirmedBalance + ) { committed, confirmed -> + // Only the SDK's own confirmed figure (ShieldedTransferViewModel's post-cutover + // source); never the frozen dashj ChainLocked fallback. + if (committed == true) confirmed?.value else null + }.first() + override fun observeShieldedBalance(): Flow = flow { emitAll(dashPayConfig.observePreservingErrors(DashPayConfig.USE_KOTLIN_SDK_SHIELDED)) } .flatMapLatest { enabled -> @@ -601,9 +618,10 @@ class ExternalSendServiceImpl internal constructor( } /** - * - Core → Core: the SDK send's fee reserve ([SEND_ALL_FEE_RESERVE_DUFFS]), an upper - * bound the real (smaller) fee never exceeds — the same figure the Basic send shows. - * A Max (drain) takes it OUT of the amount; any other send pays it on top. + * - 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. @@ -614,7 +632,7 @@ class ExternalSendServiceImpl internal constructor( private suspend fun estimateFeeInner(source: SendBalance, destination: SendDestination): FeeEstimate? = when (source) { SendBalance.CORE -> when (destination) { - is SendDestination.Core -> FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false) + is SendDestination.Core -> FeeEstimate(Dash(coreSendFeeReserveDuffs()), exact = false) is SendDestination.Shielded -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { FeeEstimate(Dash(shieldPoolFeeDuffs(it)), exact = false) } @@ -628,10 +646,11 @@ class ExternalSendServiceImpl internal constructor( /** * - 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). - * - Core → Shielded: that figure minus the shield pool fee (what the recipient receives - * when the whole balance is locked); a Max send retries once with an L1 reserve if - * the lock selection comes up short. + * 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. * - Shielded → *: the READY balance minus the single-note pool fee; a Max send also * retries once with the exact deficit the note selection reports. * - Everything else: null (no pre-send fee figure). @@ -639,19 +658,8 @@ class ExternalSendServiceImpl internal constructor( override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = try { when (source) { SendBalance.CORE -> when (destination) { - is SendDestination.Core -> - this.source.observeCoreMaxSendableDuffs().first()?.takeIf { it > 0 }?.let(::Dash) - is SendDestination.Shielded -> { - val max = this.source.observeCoreMaxSendableDuffs().first() - val feeCredits = withContext(ioDispatcher) { - this@ExternalSendServiceImpl.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER) - } - if (max == null || feeCredits == null) { - null - } else { - (max - shieldPoolFeeDuffs(feeCredits)).takeIf { it > 0 }?.let(::Dash) - } - } + is SendDestination.Core -> withContext(ioDispatcher) { coreToCoreMaxDuffs() }?.let(::Dash) + is SendDestination.Shielded -> withContext(ioDispatcher) { coreToShieldedMaxDuffs() }?.let(::Dash) else -> null } SendBalance.SHIELDED -> { @@ -674,6 +682,33 @@ class ExternalSendServiceImpl internal constructor( null } + /** 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 } + } + // ── Send ────────────────────────────────────────────────────────── override suspend fun send( @@ -806,7 +841,7 @@ class ExternalSendServiceImpl internal constructor( ): ExternalSendResult { return when (destination) { is SendDestination.Core -> sendCoreToCore(pair, walletIdHex, destination, amount, isMax, coreSession) - is SendDestination.Shielded -> sendCoreToShielded(pair, walletIdHex, destination, amount, isMax) + is SendDestination.Shielded -> sendCoreToShielded(pair, walletIdHex, destination, amount) is SendDestination.Identity -> { if (!stillBound(pair, walletIdHex)) { ExternalSendResult.NotSent(NotSentReason.GENERIC) @@ -859,16 +894,14 @@ class ExternalSendServiceImpl internal constructor( /** * The recipient receives the confirmed [amount]: the lock is `amount + pool fee` - * ([shieldPoolFeeDuffs]), the fee Rust carves out of the lock. A Max whose lock - * selection comes up short (the L1 fee) retries once with an L1 reserve taken off the - * lock, so the recipient then receives that much less (never more than confirmed). + * ([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, - isMax: Boolean + amount: Dash ): ExternalSendResult { val feeCredits = readOrNull("shield pool fee") { this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER) } ?: return notSent(pair, NotSentReason.GENERIC, "shield pool fee unknown") @@ -877,17 +910,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: ArithmeticException) { return notSent(pair, NotSentReason.GENERIC, "amount out of range") } - var result = shieldFromCoreChecked(pair, walletIdHex, destination.address, lock) - val first = result - if (isMax && first is SdkWriteResult.NotBroadcast && isAssetLockSelectionShort(first)) { - val reserve = this.source.spendableUtxoCount()?.let(::assetLockMaxFeeReserve) - val adjusted = reserve?.let { lock - it } - if (adjusted != null && adjusted.isPositive) { - log.info("external send {}: max shield short; retrying once with an L1 fee reserve", pair) - result = shieldFromCoreChecked(pair, walletIdHex, destination.address, adjusted) - } - } - return when (result) { + return when (val result = shieldFromCoreChecked(pair, walletIdHex, destination.address, lock)) { is SdkWriteResult.Broadcast -> when (result.value) { ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) ShieldFromWalletOutcome.SHIELD_PENDING_RETRY -> { diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index 662c58c951..9dabd5d16c 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -71,6 +71,13 @@ sealed class ExternalSendExecution { * 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() } /** @@ -98,9 +105,11 @@ internal class DashPayConfigInFlightMarker(private val config: DashPayConfig) : * 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 only on a definitive Sent / Not sent, and on an - * unknown outcome only when the user acknowledges it. A fresh process that finds it set (or - * cannot read it) starts in [ExternalSendExecution.InterruptedByRestart]. + * (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]. * * Deliberately simpler than the shielded [de.schildbach.wallet.ui.shielded.ShieldedTransferExecutor]: * no system notification and no stall watchdog. The service is itself single-flight. @@ -197,9 +206,11 @@ class ExternalSendExecutor internal constructor( log.error("external send threw; outcome unknown", e) } finally { log.info("external send {} → {} finished: {}", request.source, kindOf(request.destination), kindOf(result)) - // 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 && isDefinitive(result)) { + // 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() } } _state.value = ExternalSendExecution.Finished(request, result) @@ -209,24 +220,27 @@ class ExternalSendExecutor internal constructor( } /** - * The screen showed the outcome; the executor is free again. An unknown outcome (or a - * restart-interrupted one) clears the marker first, and only then becomes Idle, so the - * clear can never race a new send's marker. + * 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 -> !isDefinitive(current.result) + is ExternalSendExecution.Finished -> current.result !is ExternalSendResult.NotSent ExternalSendExecution.InterruptedByRestart -> true else -> return } if (!needsClear) { - _state.update { if (it === current) ExternalSendExecution.Idle else it } + _state.compareAndSet(current, ExternalSendExecution.Idle) return } + if (!_state.compareAndSet(current, ExternalSendExecution.Acknowledging)) return applicationScope.launch { clearMarker() - _state.update { if (it === current) ExternalSendExecution.Idle else it } + _state.compareAndSet(ExternalSendExecution.Acknowledging, ExternalSendExecution.Idle) } } @@ -241,10 +255,6 @@ class ExternalSendExecutor internal constructor( } } - /** Sent and Not sent are definitive; anything else may have moved money. */ - private fun isDefinitive(result: ExternalSendResult): Boolean = - result is ExternalSendResult.Sent || result is ExternalSendResult.NotSent - private fun kindOf(destination: SendDestination): String = destination::class.java.simpleName private fun kindOf(result: ExternalSendResult): String = when (result) { diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index d85a1572dd..76ffaebefa 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -292,6 +292,8 @@ class ExternalSendViewModel internal constructor( 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) ) diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index bff1ddec5b..4dd7bda6a4 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -75,6 +75,8 @@ class ExternalSendServiceImplTest { 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) } @@ -105,6 +107,7 @@ class ExternalSendServiceImplTest { override fun observeOwnIdentityId(): Flow> = identityFlow ?: flowOf(Result.success(ownIdentity)) override suspend fun managedIdentityIds(walletIdHex: String): List = managed 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() @@ -112,7 +115,7 @@ class ExternalSendServiceImplTest { 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? = 2 + override suspend fun spendableUtxoCount(): Int? = utxoCount override suspend fun sendCore(address: String, amount: Dash, emptyWallet: Boolean, session: WalletSession?): String { calls += "sendCore" @@ -541,7 +544,8 @@ class ExternalSendServiceImplTest { @Test fun fees_areNullWhereNoPreSendFigureExists() = runBlocking { val service = service(source()) - assertEquals(FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false), service.estimateFee(SendBalance.CORE, core, amount)) + // The size-based reserve over the spendable UTXO count (2). + assertEquals(FeeEstimate(Dash(sendAllFeeReserveDuffs(2)), exact = false), service.estimateFee(SendBalance.CORE, core, amount)) assertEquals(FeeEstimate(Dash(2_001L), exact = false), service.estimateFee(SendBalance.SHIELDED, core, amount)) assertNull(service.estimateFee(SendBalance.PLATFORM, platform, amount)) assertNull(service.estimateFee(SendBalance.IDENTITY, core, amount)) @@ -568,29 +572,76 @@ class ExternalSendServiceImplTest { 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, shielded, amount)) - // Max: the whole Core max is locked, the recipient receives it minus the pool fee. + // 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, shielded)) - assertEquals(Dash(5_000_000L) - poolFee, max) + assertEquals(Dash(5_000_000L) - assetLockMaxFeeReserve(2) - poolFee, max) assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, shielded, max, isMax = true)) - assertEquals(listOf(Dash(5_000_000L)), source.shieldedAmounts) + assertEquals(listOf(Dash(5_000_000L) - assetLockMaxFeeReserve(2)), source.shieldedAmounts) } @Test - fun coreToShieldedMax_selectionShort_retriesWithTheReserveOffTheLock() = runBlocking { + 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 { - shieldFromCoreResult = { value -> - if (value == Dash(5_000_000L)) { - SdkWriteResult.NotBroadcast("asset lock coin selection is short") - } else { - SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) - } - } + coreMax = 9_000_000L + coreEligible = 3_000_000L + } + val service = service(source) + assertEquals( + Dash(3_000_000L) - assetLockMaxFeeReserve(2) - poolFee, + service.maxSendable(SendBalance.CORE, shielded) + ) + // Fail closed: an unknown eligible balance or UTXO count is no Max. + source.coreEligible = null + assertNull(service.maxSendable(SendBalance.CORE, shielded)) + source.coreEligible = 3_000_000L + source.utxoCount = null + assertNull(service.maxSendable(SendBalance.CORE, 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, 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, shielded)) - assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, shielded, max, isMax = true)) - assertEquals(2, source.shieldedAmounts.size) - assertEquals(Dash(5_000_000L) - assetLockMaxFeeReserve(2), source.shieldedAmounts[1]) + 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, core)) + source.coreMax = 1L + assertNull(service.maxSendable(SendBalance.CORE, 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, core)) + val fee = requireNotNull(service.estimateFee(SendBalance.CORE, core, max)).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, core)) + assertEquals( + FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false), + service.estimateFee(SendBalance.CORE, core, amount) + ) } @Test diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index e788e1535c..1ebb734007 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -109,6 +109,10 @@ class ExternalSendViewModelTest { 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 @@ -121,6 +125,8 @@ class ExternalSendViewModelTest { } override suspend fun clear() { + clearCalls++ + clearGate?.await() if (failWrites) throw java.io.IOException("datastore") log += "clear" value = false @@ -660,17 +666,23 @@ class ExternalSendViewModelTest { } @Test - fun inFlightMarker_isWrittenBeforeTheSend_andClearedOnADefinitiveResult() { + fun inFlightMarker_isWrittenBeforeTheSend_keptOnSentUntilAcknowledged_clearedOnNotSent() { val gate = CompletableDeferred() service.sendGate = gate - sendOnce() + 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) - - executor.acknowledge() + assertEquals(ExternalSendExecution.Idle, executor.state.value) service.sendGate = null service.sendResult = ExternalSendResult.NotSent(NotSentReason.NOT_SYNCED) marker.log.clear() @@ -693,6 +705,38 @@ class ExternalSendViewModelTest { } } + @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) + } + @Test fun inFlightMarker_unwritable_sendsNothing() { marker.failWrites = true From e6d9ca2994b33b03f9a9d32af2628f82dfa8ed05 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 4 Nov 2026 21:28:35 -0800 Subject: [PATCH 05/30] fix(payments): keep the External Send form disabled once a send has finished After the user closed the result of a send that went out (or may have), the executor returned to Idle while the screen was leaving, and the amount form, still holding the sent amount, became enabled again. A `finished` flag, set before the executor is released and kept in saved state, now keeps Continue, the keypad, Max and the source picker inert. A not-sent result still returns to an editable amount. Co-Authored-By: Claude Opus 5.5 --- .../ui/payments/send/ExternalSendScreen.kt | 8 ++- .../ui/payments/send/ExternalSendViewModel.kt | 34 +++++++++-- .../send/ExternalSendViewModelTest.kt | 56 +++++++++++++++++++ 3 files changed, 90 insertions(+), 8 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index dfb8c4cb7b..5fbb465b3e 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -286,7 +286,7 @@ private fun AmountPage(uiState: ExternalSendUIState, actions: ExternalSendAction .weight(1f), secondaryAmount = uiState.secondaryAmountText, showPrimaryChevron = false, - keypadEnabled = uiState.status == ExternalSendStatus.Idle, + keypadEnabled = uiState.formEditable, onCurrencySelected = if (fiatCode != null && uiState.rate != null) { { index -> actions.onCurrencySelected(index == 0) } } else { @@ -325,7 +325,11 @@ private fun FromToCards(uiState: ExternalSendUIState, actions: ExternalSendActio label = stringResource(R.string.external_send_from), title = stringResource(titleFor(uiState.source)), modifier = Modifier - .clickable(role = Role.Button, onClick = actions.onShowSourceSheet) + .clickable( + enabled = !uiState.finished, + role = Role.Button, + onClick = actions.onShowSourceSheet + ) .semantics { contentDescription = changeDescription }, trailing = { Row(verticalAlignment = Alignment.CenterVertically) { diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index 76ffaebefa..d4c35c2477 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -115,6 +115,9 @@ data class ExternalSendConfirm( * @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, @@ -138,14 +141,19 @@ data class ExternalSendUIState( val maxSendable: Dash? = null, val showSourceSheet: Boolean = false, val confirm: ExternalSendConfirm? = null, - val status: ExternalSendStatus = ExternalSendStatus.Idle + val status: ExternalSendStatus = ExternalSendStatus.Idle, + val finished: Boolean = false ) { + /** 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 + get() = addressParse is DestinationParse.Valid && !finished /** The sources the sheet lists, in order; Identity only for a user who has one. */ val sources: List @@ -197,7 +205,7 @@ data class ExternalSendUIState( !exceedsBalance && (dashMode || rate != null || pinnedAmount != null || maxAmount != null) && !identityBlocks && - status == ExternalSendStatus.Idle + formEditable } /** @@ -245,6 +253,7 @@ class ExternalSendViewModel internal constructor( 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 @@ -270,6 +279,9 @@ class ExternalSendViewModel internal constructor( init { restoreOrSeed() + if (savedState.get(KEY_FINISHED) == true) { + _uiState.update { it.copy(finished = true) } + } service.observeHasIdentity() .onEach { has -> @@ -375,6 +387,7 @@ class ExternalSendViewModel internal constructor( } fun onAddressContinue() { + if (!_uiState.value.canContinueAddress) return val parse = _uiState.value.addressParse if (parse is DestinationParse.Valid) { enterAmountStep(parse.destination, parse.amount) @@ -414,7 +427,7 @@ class ExternalSendViewModel internal constructor( fun onKeyInput(key: String) { val state = _uiState.value - if (state.status != ExternalSendStatus.Idle) return + 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 @@ -446,7 +459,7 @@ class ExternalSendViewModel internal constructor( fun onMaxClick() { val state = _uiState.value val max = state.maxSendable ?: return - if (state.status != ExternalSendStatus.Idle) return + if (!state.formEditable) return _uiState.update { it.copy(maxAmount = max, pinnedAmount = null, amountText = displayTextFor(max, it.dashMode, it.rate)) } @@ -454,6 +467,7 @@ class ExternalSendViewModel internal constructor( } fun onShowSourceSheet() { + if (_uiState.value.finished) return _uiState.update { it.copy(showSourceSheet = true) } } @@ -464,6 +478,7 @@ class ExternalSendViewModel internal constructor( /** 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) } @@ -614,11 +629,16 @@ class ExternalSendViewModel internal constructor( */ fun onResultAcknowledged() { val status = _uiState.value.status as? ExternalSendStatus.Done ?: return - executor.acknowledge() 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, 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() } } @@ -630,6 +650,8 @@ class ExternalSendViewModel internal constructor( 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 diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 1ebb734007..5d87f67eaf 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -514,9 +514,65 @@ class ExternalSendViewModelTest { 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 From 6921674d4e07191452099ffed523659838f7b5f7 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 6 Nov 2026 09:40:17 -0800 Subject: [PATCH 06/30] feat(payments): enable External Send from Core to a third-party Platform address MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bump the Kotlin SDK to 5.1.0-int36 (HashEngineering/platform feat/kotlin-sdk-fund-from-asset-lock-external @ 760d00f559), which binds fundFromAssetLockExternal, and use it for Core → Platform (P2PKH only). - The payee gets exactly the amount; the lock carries a 62 000-duff margin (the DPP address-funding admission floor) whose remainder, after the Platform fee, lands on the wallet's own Platform address. - Per the SDK contract the recipients are persisted before the call and the lock outpoint inside onAssetLockBuilt; once a lock is built a failure is "may have gone through", never Not sent. - A resume sweep (executor start and screen open) completes an interrupted funding with exactly the persisted recipients, capped per process. - A pending record blocks a second Core → Platform send. Co-Authored-By: Claude Opus 5.5 --- build.gradle | 15 +- .../platform/sdk/ExternalPlatformFunding.kt | 240 ++++++++++ .../platform/sdk/ExternalSendModels.kt | 26 +- .../platform/sdk/ExternalSendService.kt | 15 + .../platform/sdk/ExternalSendServiceImpl.kt | 436 +++++++++++++++++- .../wallet/ui/dashpay/utils/DashPayConfig.kt | 10 + .../ui/payments/send/ExternalSendExecutor.kt | 32 ++ .../ui/payments/send/ExternalSendViewModel.kt | 3 + .../platform/sdk/ExternalSendModelsTest.kt | 81 +++- .../sdk/ExternalSendServiceImplTest.kt | 395 +++++++++++++++- .../send/ExternalSendViewModelTest.kt | 37 +- 11 files changed, 1254 insertions(+), 36 deletions(-) create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt diff --git a/build.gradle b/build.gradle index 9ca525a2c8..9b0af33810 100644 --- a/build.gradle +++ b/build.gradle @@ -11,15 +11,12 @@ buildscript { // 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.0.0-int32: HashEngineering/platform - // integration/5.0.0-int32 @ 0495544fd5 = int31 (0c5fcfec1c) with v5.0-dev - // 78d494f525 (5.0.0-rc.8) merged in; engine HashEngineering/rust-dashcore - // integration/5.0.0-int32-engine @ 0398ec0a (rust-dashcore v0.45.0 plus #1016 - // and #1063). Carries, as int31: #4312/#4313 (shielded), #5259, #5256, the - // dashj-legacy ECDH fallback and the asset-lock 1 s re-poll; still no - // transaction-record folding. Recipe: HashEngineering/dash-wallet-qa - // recipes/platform/5.0.0-int32.yaml. - dashSdkVersion = '5.0.0-int32-20261026.223239-1' + // can't change what this commit builds. 5.1.0-int36: HashEngineering/platform + // feat/kotlin-sdk-fund-from-asset-lock-external @ 760d00f559 = v5.1-dev plus the + // fund_from_asset_lock_external JNI binding (ManagedPlatformWallet + // .fundFromAssetLockExternal / .resumeFundFromAssetLockExternal), used by the + // Advanced-mode Core → third-party Platform address send. + dashSdkVersion = '5.1.0-int36-20261106.165805-1' // 5.0.0 carries a libsdklib.so that knows document serialization // format 3. Format 3 arrives with Platform protocol version 14 (it // stamps the document with the contract version its bytes conform to, 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..4868f8c819 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt @@ -0,0 +1,240 @@ +/* + * 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]. + * + * [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? +) { + 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" } + } + + /** 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) + + /** 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 + + fun encode(): String = listOf( + 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() + ).joinToString(FIELD_SEPARATOR) + + override fun toString(): String = + "PendingPlatformFunding(id=$id, outPoint=${if (outPointHex == null) "none" else "recorded"}, )" + + companion object { + private const val FORMAT_VERSION = "1" + private const val FIELD_SEPARATOR = "|" + private const val FIELD_COUNT = 10 + + /** + * Decode a stored record. Malformed is NOT absent: this throws + * [IllegalStateException], and every caller fails closed on it. + */ + fun decode(encoded: String): PendingPlatformFunding { + val fields = encoded.split(FIELD_SEPARATOR) + check(fields.size == FIELD_COUNT && 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 } + ) + } 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) +} + +/** [PlatformFundingStore] over [DashPayConfig.EXTERNAL_PLATFORM_FUNDING_PENDING]. */ +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) + } +} diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index fc72249b51..3a10034fb8 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -133,6 +133,18 @@ internal fun decodePlatformAddress(address: String, network: AddressNetwork): Pl 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() @@ -324,14 +336,17 @@ enum class SendSupport { * * | From \ To | Core | Shielded | Platform | Identity | * |---|---|---|---|---| - * | Core | yes | yes | no (1) | own identity only (2) | + * | Core | yes | yes | yes, P2PKH only (1) | own identity only (2) | * | Shielded | yes | yes | yes | yes | * | Platform | no (3) | no (4) | yes | yes | * | Identity | yes | no (5) | yes | yes, not to itself | * - * 1. The pinned Kotlin SDK's `fundFromAssetLock` only funds the wallet's OWN Platform - * addresses (Rust `RecipientOwnership::AllOwned`); the external variant exists in - * the Rust FFI but is not bound in JNI. + * 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. @@ -349,7 +364,8 @@ fun externalSendSupport( return when (source) { SendBalance.CORE -> when (destination) { is SendDestination.Core, is SendDestination.Shielded -> SendSupport.SUPPORTED - is SendDestination.Platform -> SendSupport.NOT_SUPPORTED_YET + 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 } diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt index be370f54cc..6ba9e6de02 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -146,6 +146,11 @@ interface ExternalSendService { * * 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]. */ suspend fun send( source: SendBalance, @@ -154,4 +159,14 @@ interface ExternalSendService { 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, earlier, or as Platform reports). + * 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 index 417ea3c17b..67ba886404 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -24,6 +24,7 @@ import de.schildbach.wallet.database.entity.IdentityCreationState 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.isCompleteTxFailure import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet.ui.shielded.assetLockMaxFeeReserve @@ -31,6 +32,7 @@ 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 @@ -53,7 +55,10 @@ import org.dash.wallet.common.services.WalletSession import org.dash.wallet.common.util.readRetryDelayMs import org.dashfoundation.dashsdk.credits.FundingInput 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 @@ -258,6 +263,58 @@ internal interface ExternalSendSource { amountCredits: Long ) suspend fun identityTransfer(walletIdHex: String, fromId: ByteArray, toId: ByteArray, amountCredits: Long) + + // 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; throws when unreadable. + */ + suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String): Boolean } /** Production [ExternalSendSource]. */ @@ -272,7 +329,8 @@ internal class DashSdkExternalSendSource( private val usernameQueries: SdkUsernameQueries, private val dashPayConfig: DashPayConfig, private val identityConfig: BlockchainIdentityConfig, - private val walletData: WalletData + private val walletData: WalletData, + private val fundingGate: PendingPaymentFundingGate ) : ExternalSendSource { private suspend fun manager(): org.dashfoundation.dashsdk.wallet.PlatformWalletManager { @@ -458,6 +516,70 @@ internal class DashSdkExternalSendSource( ) } + 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): Boolean = + database().assetLockDao() + .observeByWalletAndFundingType(walletIdBytes(walletIdHex), ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP) + .first() + .any { it.statusRaw != ASSET_LOCK_STATUS_CONSUMED } + private companion object { private val log = LoggerFactory.getLogger(DashSdkExternalSendSource::class.java) } @@ -485,15 +607,19 @@ internal class DashSdkExternalSendSource( * 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). + * 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 retryDelayMs: (Long) -> Long = ::readRetryDelayMs, + private val newFundingId: () -> String = { UUID.randomUUID().toString() } ) : ExternalSendService { @Inject @@ -507,17 +633,23 @@ class ExternalSendServiceImpl internal constructor( usernameQueries: SdkUsernameQueries, dashPayConfig: DashPayConfig, identityConfig: BlockchainIdentityConfig, - walletData: WalletData + walletData: WalletData, + fundingGate: PendingPaymentFundingGate ) : this( source = DashSdkExternalSendSource( sdkService, sendPaymentService, sdkL1SendService, cutoverUiDataService, shieldedBalanceService, - transparentTopUp, usernameQueries, dashPayConfig, identityConfig, walletData + transparentTopUp, usernameQueries, dashPayConfig, identityConfig, walletData, fundingGate ), - network = AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id) + network = AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id), + platformFundingStore = DashPayConfigPlatformFundingStore(dashPayConfig) ) + /** 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) @@ -625,6 +757,10 @@ class ExternalSendServiceImpl internal constructor( * - 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. * - Shielded → *: the flat single-note pool fee of the transition; more notes cost more. * - Core → Identity, Platform → *, Identity → *: Rust meters these at execution; no * pre-send figure exists, so null. @@ -636,7 +772,10 @@ class ExternalSendServiceImpl internal constructor( is SendDestination.Shielded -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { FeeEstimate(Dash(shieldPoolFeeDuffs(it)), exact = false) } - else -> null + is SendDestination.Platform -> this.source.spendableUtxoCount()?.let { + FeeEstimate(Dash(coreToPlatformFeeDuffs(it)), exact = false) + } + is SendDestination.Identity -> null } SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destination))?.let { FeeEstimate(Dash(ceilCreditsToDuffs(it)), exact = false) @@ -651,6 +790,8 @@ class ExternalSendServiceImpl internal constructor( * 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. * - Everything else: null (no pre-send fee figure). @@ -660,7 +801,8 @@ class ExternalSendServiceImpl internal constructor( SendBalance.CORE -> when (destination) { is SendDestination.Core -> withContext(ioDispatcher) { coreToCoreMaxDuffs() }?.let(::Dash) is SendDestination.Shielded -> withContext(ioDispatcher) { coreToShieldedMaxDuffs() }?.let(::Dash) - else -> null + is SendDestination.Platform -> withContext(ioDispatcher) { coreToPlatformMaxDuffsOrNull() }?.let(::Dash) + is SendDestination.Identity -> null } SendBalance.SHIELDED -> { val balance = this.source.observeShieldedBalance().first() @@ -709,6 +851,18 @@ class ExternalSendServiceImpl internal constructor( 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( @@ -818,7 +972,7 @@ class ExternalSendServiceImpl internal constructor( // (5)+(6) The one write. return when (source) { - SendBalance.CORE -> sendFromCore(pair, walletIdHex, destination, amount, isMax, coreSession) + SendBalance.CORE -> sendFromCore(pair, walletIdHex, destination, amount, amountCredits, isMax, coreSession) SendBalance.SHIELDED -> sendFromShielded(pair, walletIdHex, destination, amount, isMax) SendBalance.PLATFORM -> sendFromPlatform(pair, walletIdHex, destination, amountCredits) SendBalance.IDENTITY -> sendFromIdentity( @@ -836,6 +990,7 @@ class ExternalSendServiceImpl internal constructor( walletIdHex: String, destination: SendDestination, amount: Dash, + amountCredits: Long, isMax: Boolean, coreSession: WalletSession? ): ExternalSendResult { @@ -849,7 +1004,265 @@ class ExternalSendServiceImpl internal constructor( mapWrite(pair, this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) } } - is SendDestination.Platform -> notSent(pair, NotSentReason.NOT_SUPPORTED, "unreachable: gated") + 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, 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") + } + try { + platformFundingStore.write(record) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("external send {}: could not persist the recipients; not sent", pair, 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 { + 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) { + log.error("external send {}: could not record the lock outpoint (retried after the call)", pair, e) + } + } + }?.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) + return ExternalSendResult.Sent(null) + } + // 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, + (outcome as? SdkWriteResult.NotBroadcast)?.cause ?: (outcome as? SdkWriteResult.Ambiguous)?.cause + ) + return ExternalSendResult.MayHaveGoneThrough + } + + /** 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, 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, 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", 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. + * - 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 on success or when + * Platform answers already consumed. + */ + 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", 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 + 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) { + val unconsumed = readOrNull("address funding locks") { + this.source.hasUnconsumedAddressFundingLocks(record.walletIdHex) + } ?: 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, 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 + if (!stillBound("Core → Platform resume", record.walletIdHex)) return 0 + try { + this.source.resumePlatformFundingExternal(record) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + if (isAssetLockAlreadyConsumed(e)) { + platformFundingStore.clear(record.id) + log.warn("pending platform funding {}: Platform reports the lock already consumed; cleared", record.id) + } else { + log.warn("pending platform funding {}: resume failed (attempt {}); kept", record.id, attempts + 1, e) + } + return 0 + } catch (e: LinkageError) { + log.warn("pending platform funding {}: native library unavailable; kept", record.id, e) + return 0 + } + platformFundingStore.clear(record.id) + log.info("pending platform funding {}: resumed and consumed", record.id) + return 1 + } finally { + inFlight.set(false) } } @@ -1094,6 +1507,9 @@ class ExternalSendServiceImpl internal constructor( /** 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" 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 8eec1b7448..f68df92e72 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt @@ -300,6 +300,16 @@ open class DashPayConfig @Inject constructor( */ 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") + /** * `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/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index 9dabd5d16c..e47e531f47 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -25,6 +25,8 @@ import de.schildbach.wallet.service.platform.sdk.SendDestination 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 @@ -34,6 +36,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.dash.wallet.common.money.Dash import org.slf4j.LoggerFactory +import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton @@ -134,6 +137,9 @@ class ExternalSendExecutor internal constructor( private val _state = MutableStateFlow(ExternalSendExecution.Restoring) val state: StateFlow = _state.asStateFlow() + /** The running [resumePendingPlatformFunding] sweep (declared before `init`, which starts one). */ + private val platformFundingSweep = AtomicReference(null) + init { applicationScope.launch { val interrupted = try { @@ -153,6 +159,32 @@ class ExternalSendExecutor internal constructor( } } } + resumePendingPlatformFunding() + } + + /** + * Finish an interrupted Core → Platform send in the background + * ([ExternalSendService.resumePendingPlatformFunding]): run when the executor starts 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", 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() } /** diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index d4c35c2477..d495db1094 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -297,6 +297,9 @@ class ExternalSendViewModel internal constructor( .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) { diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt index d77b4a3ee3..76892e54db 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -239,7 +239,12 @@ class ExternalSendModelsTest { fun matrix_core() { assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, core)) assertEquals(SendSupport.SUPPORTED, support(SendBalance.CORE, shielded)) - assertEquals(SendSupport.NOT_SUPPORTED_YET, support(SendBalance.CORE, platform)) + // 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. @@ -356,4 +361,78 @@ class ExternalSendModelsTest { 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_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 index 4dd7bda6a4..e5011a76f8 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -35,6 +35,7 @@ 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.dashfoundation.dashsdk.errors.DashSdkError import org.dashfoundation.dashsdk.credits.FundingInput import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals @@ -59,6 +60,9 @@ class ExternalSendServiceImplTest { 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) @@ -194,6 +198,71 @@ class ExternalSendServiceImplTest { lastCredits = amountCredits nativeWrite() } + + // 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 } + 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): Boolean = 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 + } } private fun source( @@ -202,8 +271,8 @@ class ExternalSendServiceImplTest { managed: List = listOf(ownId) ) = FakeSource(bound.toMutableList(), ownIdentity, managed) - private fun service(source: FakeSource) = - ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, ioDispatcher = Dispatchers.Unconfined) + private fun service(source: FakeSource, store: PlatformFundingStore = FakeStore()) = + ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, store, ioDispatcher = Dispatchers.Unconfined) /** A send confirmed while [walletA] was bound (the ViewModel's capture). */ private suspend fun ExternalSendServiceImpl.send( @@ -397,7 +466,8 @@ class ExternalSendServiceImplTest { @Test fun unsupportedPairs_areNotSupported_withNoSeamCall() = runBlocking { val pairs = listOf( - SendBalance.CORE to platform, + // The SDK funds P2PKH Platform addresses only. + SendBalance.CORE to platformP2sh, SendBalance.PLATFORM to core, SendBalance.PLATFORM to shielded, SendBalance.IDENTITY to shielded, @@ -431,6 +501,7 @@ class ExternalSendServiceImplTest { 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 @@ -492,7 +563,7 @@ class ExternalSendServiceImplTest { return SdkWriteResult.Broadcast(Unit) } } - val gated = ExternalSendServiceImpl(slow, AddressNetwork.DASH_TESTNET, ioDispatcher = Dispatchers.Unconfined) + val gated = ExternalSendServiceImpl(slow, AddressNetwork.DASH_TESTNET, FakeStore(), ioDispatcher = Dispatchers.Unconfined) try { val first = async(start = CoroutineStart.UNDISPATCHED) { gated.send(SendBalance.SHIELDED, shielded, amount, false) @@ -649,7 +720,7 @@ class ExternalSendServiceImplTest { val source = object : ExternalSendSource by source() { override suspend fun shieldedFeeCredits(kind: ShieldedFeeKind): Long? = null } - val result = ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, ioDispatcher = Dispatchers.Unconfined) + val result = ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, FakeStore(), ioDispatcher = Dispatchers.Unconfined) .send(SendBalance.CORE, shielded, amount, false, walletA) assertEquals(ExternalSendResult.NotSent(NotSentReason.GENERIC), result) } @@ -683,6 +754,7 @@ class ExternalSendServiceImplTest { 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 otherIdentity, @@ -726,6 +798,7 @@ class ExternalSendServiceImplTest { val service = ExternalSendServiceImpl( source, AddressNetwork.DASH_TESTNET, + FakeStore(), ioDispatcher = Dispatchers.Unconfined, retryDelayMs = { 0L } ) @@ -747,4 +820,316 @@ class ExternalSendServiceImplTest { 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) + + assertEquals(ExternalSendResult.Sent(null), 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_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, platform, amount)) + assertEquals(Dash(5_000_000L) - fee, service.maxSendable(SendBalance.CORE, platform)) + + // Unknown figures are no Max / no fee, never zero. + source.coreEligible = null + assertNull(service.maxSendable(SendBalance.CORE, platform)) + source.coreEligible = 5_000_000L + source.utxoCount = null + assertNull(service.maxSendable(SendBalance.CORE, platform)) + assertNull(service.estimateFee(SendBalance.CORE, platform, amount)) + // 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, platform)) + source.coreEligible = fee.duffs + 499L + assertNull(service.maxSendable(SendBalance.CORE, platform)) + source.coreEligible = fee.duffs + 500L + assertEquals(Dash(500L), service.maxSendable(SendBalance.CORE, 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_orAlreadyConsumedAnswer_clearsTheRecord() = runBlocking { + var source = source().apply { lockStatus = { ASSET_LOCK_STATUS_CONSUMED } } + var store = FakeStore().apply { record = pendingRecord() } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertTrue(source.calls.isEmpty()) + assertNull(store.record) + + source = source().apply { + resume = { throw DashSdkError.PlatformWallet.AssetLockAlreadyConsumed("already consumed") } + } + store = FakeStore().apply { record = pendingRecord() } + assertEquals(0, service(source, store).resumePendingPlatformFunding()) + assertEquals(1, source.resumed.size) + assertNull(store.record) + } + + @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(null), send.await()) + } finally { + release.complete(Unit) + } + 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" + val remainderHash = ByteArray(20) { 7 } + } } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 5d87f67eaf..bfa7582e37 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -63,6 +63,9 @@ class ExternalSendViewModelTest { 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() }) @@ -100,6 +103,12 @@ class ExternalSendViewModelTest { 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. */ @@ -235,9 +244,13 @@ class ExternalSendViewModelTest { val core = buildViewModel().apply { goToAmount(coreAddress) } assertEquals(SendBalance.CORE, core.uiState.value.source) - // Core cannot pay a Platform address; Shielded can. + // Core pays a P2PKH Platform address (fundFromAssetLockExternal) ... val platform = buildViewModel().apply { goToAmount(platformAddress) } - assertEquals(SendBalance.SHIELDED, platform.uiState.value.source) + 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 @@ -255,7 +268,7 @@ class ExternalSendViewModelTest { @Test fun sourceSelection_ignoresUnsupportedAndUnlistedSources() { val viewModel = buildViewModel() - viewModel.goToAmount(platformAddress) + viewModel.goToAmount(platformP2shAddress) viewModel.onSourceSelected(SendBalance.CORE) assertEquals(SendBalance.SHIELDED, viewModel.uiState.value.source) @@ -280,7 +293,7 @@ class ExternalSendViewModelTest { service.balances.getValue(SendBalance.SHIELDED).value = twoDash service.max[SendBalance.SHIELDED] = oneDash val viewModel = buildViewModel() - viewModel.goToAmount(platformAddress) + viewModel.goToAmount(platformP2shAddress) assertEquals(twoDash, viewModel.uiState.value.balance) assertEquals(oneDash, viewModel.uiState.value.maxSendable) @@ -343,12 +356,14 @@ class ExternalSendViewModelTest { fun continue_isBlockedForAnUnsupportedPair() { val state = ExternalSendUIState( step = ExternalSendStep.AMOUNT, - destination = SendDestination.Platform(platformAddress), + 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) } @@ -885,7 +900,7 @@ class ExternalSendViewModelTest { service.balances.getValue(SendBalance.PLATFORM).value = twoDash service.max[SendBalance.SHIELDED] = max val viewModel = buildViewModel(rate = usd100) - viewModel.goToAmount(platformAddress) + viewModel.goToAmount(platformP2shAddress) viewModel.onMaxClick() viewModel.onCurrencySelected(dashMode = false) assertEquals(max, viewModel.uiState.value.amount) @@ -933,4 +948,14 @@ class ExternalSendViewModelTest { 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) + } } From 3f16457abd97036ad9434659d32a3e7f0a0d2dcd Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 6 Nov 2026 14:34:55 -0800 Subject: [PATCH 07/30] =?UTF-8?q?feat(payments):=20resume=20an=20interrupt?= =?UTF-8?q?ed=20Core=20=E2=86=92=20Platform=20send=20at=20app=20start?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run the External Send Platform-funding resume sweep from PlatformSynchronizationService.kickSdkEngines, right after the pending wallet-shield sweep: every kick (app start and each blockchain-service start), after the SDK bind pass. A stuck payee is now paid without the user reopening External Send. The executor is injected as dagger.Lazy so its service graph is built off the main thread and can't form a cycle. Co-Authored-By: Claude Opus 5.5 --- .../service/platform/PlatformSyncService.kt | 26 +++++++ .../ui/payments/send/ExternalSendExecutor.kt | 6 +- .../platform/IdentityDiscoveryLatchTest.kt | 1 + .../platform/PlatformSyncContactGuardTest.kt | 1 + .../platform/PlatformSyncEngineRestartTest.kt | 70 +++++++++++++++++++ .../PlatformSyncEngineTeardownTest.kt | 1 + .../platform/PlatformSyncIntegrityPassTest.kt | 1 + .../platform/PlatformUsernameReconcileTest.kt | 1 + 8 files changed, 105 insertions(+), 2 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt b/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt index 62f1cbd88d..bab0c2bc8b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt @@ -67,6 +67,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.* @@ -263,6 +264,10 @@ class PlatformSynchronizationService @Inject constructor( 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. @@ -649,6 +654,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 @@ -661,6 +676,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), diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index e47e531f47..abd931aa4d 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -164,8 +164,10 @@ class ExternalSendExecutor internal constructor( /** * Finish an interrupted Core → Platform send in the background - * ([ExternalSendService.resumePendingPlatformFunding]): run when the executor starts and - * each time the external send screen opens. One sweep at a time; cheap (one store read) + * ([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). diff --git a/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt b/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt index bbc634e8a3..1e9eab7dda 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt @@ -92,6 +92,7 @@ class IdentityDiscoveryLatchTest { 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() ) diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt index dad866365b..e83ba00d52 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt @@ -118,6 +118,7 @@ class PlatformSyncContactGuardTest { 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() ) diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt index 1536e77db8..088b11761d 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt @@ -20,9 +20,11 @@ import de.schildbach.wallet.service.platform.sdk.L1ShadowSyncService 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 +67,7 @@ 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 engine kick is asynchronous (`syncScope.launch { bindJob.join(); … }`). */ private val kickTimeoutMs = 10_000L @@ -104,6 +107,7 @@ class PlatformSyncEngineRestartTest { sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), shieldedTransferExecutor = mockk(relaxed = true), + externalSendExecutor = { externalSendExecutor }, contactRequestNotificationService = mockk(relaxed = true), dashPaySyncStatus = de.schildbach.wallet.service.DashPaySyncStatus() ) @@ -231,4 +235,70 @@ 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 + } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt index c65a9829d6..a633bb4cbf 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineTeardownTest.kt @@ -79,6 +79,7 @@ class PlatformSyncEngineTeardownTest { 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() ) diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt index 66068dcf52..247f1f007e 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt @@ -152,6 +152,7 @@ class PlatformSyncIntegrityPassTest { 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() ) diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt index 17d6d05743..3d26518cbe 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt @@ -104,6 +104,7 @@ class PlatformUsernameReconcileTest { 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() ) From e1d7ba49ba8c368dfca08748638268ddf0dc0868 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 6 Nov 2026 15:32:48 -0800 Subject: [PATCH 08/30] feat(platform): start the SDK's Platform-address balance sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app never started the Kotlin SDK's Platform-address (BLAST) sync, so credits other wallets sent to our Platform addresses never appeared: the wallet only knew balances it wrote itself. PlatformAddressSyncService starts the SDK loop once the cutover is committed, the SDK wallet is bound and exactly one SDK wallet is loaded. PlatformSynchronizationService starts it with the L1 engine (foreground blockchain-service lifetime, after the bind pass, and on bind heal) and stops it last in stopSdkEngines (shutdown and wallet wipe). A stop generation refuses a start decided before a stop. The SDK's 15 s interval is used; External Send's 15 s Platform balance poll picks up each pass. Verified on testnet emulators: a 0.05 DASH Core → Platform send from one wallet appeared on the receiver's Platform address ten seconds later. Co-Authored-By: Claude Opus 5.5 --- .../service/platform/PlatformSyncService.kt | 34 +++- .../platform/sdk/DashSdkServiceImpl.kt | 13 +- .../sdk/PlatformAddressSyncService.kt | 189 ++++++++++++++++++ .../platform/IdentityDiscoveryLatchTest.kt | 1 + .../platform/PlatformSyncContactGuardTest.kt | 1 + .../platform/PlatformSyncEngineRestartTest.kt | 60 ++++++ .../PlatformSyncEngineTeardownTest.kt | 15 ++ .../platform/PlatformSyncIntegrityPassTest.kt | 1 + .../platform/PlatformUsernameReconcileTest.kt | 1 + .../sdk/PlatformAddressSyncServiceTest.kt | 157 +++++++++++++++ 10 files changed, 464 insertions(+), 8 deletions(-) create mode 100644 wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt create mode 100644 wallet/test/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncServiceTest.kt diff --git a/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt b/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt index bab0c2bc8b..37fb0cc12c 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt @@ -55,6 +55,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 @@ -150,9 +151,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,6 +262,7 @@ 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, @@ -503,7 +506,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 @@ -562,6 +574,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() @@ -610,6 +625,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 @@ -907,6 +930,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/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/PlatformAddressSyncService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt new file mode 100644 index 0000000000..0e7af330e3 --- /dev/null +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt @@ -0,0 +1,189 @@ +/* + * 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.flow.first +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 = !dashjEngineMayStart( + CutoverState.fromStored(dashPayConfig.observePreservingErrors(DashPayConfig.CUTOVER_STATE).first()) + ) + 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/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt b/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt index 1e9eab7dda..a3e6d44f26 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/IdentityDiscoveryLatchTest.kt @@ -88,6 +88,7 @@ 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), diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt index e83ba00d52..1019a5d5b1 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncContactGuardTest.kt @@ -114,6 +114,7 @@ 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), diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt index 088b11761d..74665030c2 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncEngineRestartTest.kt @@ -17,6 +17,8 @@ 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 @@ -69,6 +71,24 @@ class PlatformSyncEngineRestartTest { 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 @@ -103,6 +123,7 @@ class PlatformSyncEngineRestartTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = l1ShadowSyncService, shieldedBalanceService = shieldedBalanceService, + platformAddressSyncService = platformAddressSyncService, cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), @@ -301,4 +322,43 @@ class PlatformSyncEngineRestartTest { 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 a633bb4cbf..7814e040c0 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,6 +77,7 @@ class PlatformSyncEngineTeardownTest { nonInteractiveWalletUnlock = mockk(relaxed = true), l1ShadowSyncService = l1ShadowSyncService, shieldedBalanceService = shieldedBalanceService, + platformAddressSyncService = platformAddressSyncService, cutoverUiDataService = mockk(relaxed = true), sdkBlockchainStateService = mockk(relaxed = true), cutoverTxSeamService = mockk(relaxed = true), @@ -92,6 +95,7 @@ class PlatformSyncEngineTeardownTest { coVerify(exactly = 1) { l1ShadowSyncService.stop() } coVerify(exactly = 1) { shieldedBalanceService.stop() } + coVerify(exactly = 1) { platformAddressSyncService.stop() } } @Test @@ -100,6 +104,7 @@ class PlatformSyncEngineTeardownTest { coVerify(exactly = 1) { l1ShadowSyncService.stop() } coVerify(exactly = 1) { shieldedBalanceService.stop() } + coVerify(exactly = 1) { platformAddressSyncService.stop() } } @Test @@ -111,4 +116,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 247f1f007e..dcd0d0dc70 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt @@ -148,6 +148,7 @@ 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), diff --git a/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt b/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt index 3d26518cbe..9b9d20a467 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/PlatformUsernameReconcileTest.kt @@ -100,6 +100,7 @@ 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), 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) + } +} From 5610dfcdd16e8720a15cc26da1af070d78108181 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 6 Nov 2026 16:36:05 -0800 Subject: [PATCH 09/30] fix(payments): return Home after a finished External Send Closing a Sent or "may have gone through" result (including the one shown after a process restart) now pops back to Home instead of only closing the External Send screen, which left the user on Payments. The back button, Not sent and leaving mid-send still return to Payments; if Home is not on the back stack it falls back to the single pop. Verified on a testnet emulator. Co-Authored-By: Claude Opus 5.5 --- .../ui/payments/send/ExternalSendFragment.kt | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt index 6dde58472c..8f1844bb64 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt @@ -144,10 +144,29 @@ class ExternalSendFragment : Fragment() { } } + /** + * 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) { - leave() + 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() + } } } } From 3406fe76f5b5c6d64b5fc798140d739d95b3a7fa Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 6 Nov 2026 17:22:39 -0800 Subject: [PATCH 10/30] =?UTF-8?q?fix(history):=20show=20a=20Core=20?= =?UTF-8?q?=E2=86=92=20Platform=20send=20as=20a=20send=20titled=20"Platfor?= =?UTF-8?q?m"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Core → Platform-address External Send is an asset lock the SDK tracks with funding type 4, which AssetLockKindResolver did not map, so its row fell back to "Internal" with the internal-transfer icon. Add AssetLockKind.PLATFORM for funding type 4: the row and detail sheet read "Platform" with the sent arrow, count under the Sent filter and never notify as received. The send seeds the kind from onAssetLockBuilt so the row is right before the SDK's asset_locks row lands. A restored wallet's own Platform top-up (also type 4) reads the same, since the funding type cannot tell own from third-party. Co-Authored-By: Claude Opus 5.5 --- wallet/res/values/strings.xml | 2 + .../platform/sdk/AssetLockKindResolver.kt | 11 +++++ .../platform/sdk/CutoverUiDataService.kt | 12 ++++-- .../platform/sdk/ExternalSendServiceImpl.kt | 33 ++++++++++++-- .../platform/sdk/SdkTxDetailProvider.kt | 7 +-- .../AssetLockKindResolverWalletScopeTest.kt | 23 ++++++++++ .../platform/sdk/CutoverUiDataServiceTest.kt | 43 ++++++++++++++++++- .../sdk/ExternalSendServiceImplTest.kt | 38 ++++++++++++++++ 8 files changed, 158 insertions(+), 11 deletions(-) diff --git a/wallet/res/values/strings.xml b/wallet/res/values/strings.xml index d493e468f6..7880f58ee0 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -157,6 +157,8 @@ 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 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 fb69ac3cb0..e7aecfbf5c 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt @@ -55,13 +55,15 @@ enum class AssetLockKind { 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 } 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 3de36cdcc6..f333772aa2 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/CutoverUiDataService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/CutoverUiDataService.kt @@ -486,12 +486,14 @@ internal fun assetLockTitleRes(kind: AssetLockKind): Int = when (kind) { AssetLockKind.PLATFORM -> R.string.transaction_row_platform 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/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt index 76ca3bda14..4062841804 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) @@ -550,7 +550,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 @@ -961,7 +961,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, From 09841a9ced84c71c99afa25c7f13c352101cfc28 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 9 Nov 2026 09:26:33 -0800 Subject: [PATCH 13/30] fix(payments): make Max follow a source change in External Send Switching the source after pressing Max kept the old source's Max as a plain amount, so a Core Max could be confirmed as a Shielded send. Max now follows the source: the amount is 0 and Continue disabled until the new source's Max is read, then it is applied as if Max were pressed. A source with no Max (unknown fee, empty balance) leaves the amount at 0. Typing cancels a pending Max, and it survives process death. Co-Authored-By: Claude Opus 5.5 --- .../ui/payments/send/ExternalSendViewModel.kt | 82 ++++++- .../send/ExternalSendViewModelTest.kt | 219 +++++++++++++++++- 2 files changed, 282 insertions(+), 19 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index d495db1094..23c40edf19 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -109,6 +109,9 @@ data class ExternalSendConfirm( * @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). @@ -129,6 +132,7 @@ data class ExternalSendUIState( 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, @@ -201,6 +205,7 @@ data class ExternalSendUIState( destination != null && supportOf(source) == SendSupport.SUPPORTED && amount.isPositive && + !maxPending && balance != null && !exceedsBalance && (dashMode || rate != null || pinnedAmount != null || maxAmount != null) && @@ -250,6 +255,7 @@ class ExternalSendViewModel internal constructor( 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" @@ -344,16 +350,26 @@ class ExternalSendViewModel internal constructor( 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: a source change drops a Max amount. + // 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, pinnedAmount = pinnedAmount) + 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() } } @@ -409,7 +425,9 @@ class ExternalSendViewModel internal constructor( 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, @@ -435,9 +453,10 @@ class ExternalSendViewModel internal constructor( 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. - if (text == state.amountText && !state.isMax) return - _uiState.update { it.copy(amountText = text, maxAmount = null, pinnedAmount = null) } + // 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() } @@ -464,7 +483,12 @@ class ExternalSendViewModel internal constructor( val max = state.maxSendable ?: return if (!state.formEditable) return _uiState.update { - it.copy(maxAmount = max, pinnedAmount = null, amountText = displayTextFor(max, it.dashMode, it.rate)) + it.copy( + maxAmount = max, + maxPending = false, + pinnedAmount = null, + amountText = displayTextFor(max, it.dashMode, it.rate) + ) } saveAmount() } @@ -496,12 +520,16 @@ class ExternalSendViewModel internal constructor( 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, - // A dropped Max keeps its exact amount (no longer Max): its text may be rounded fiat. - pinnedAmount = if (changed && it.isMax) it.amount else it.pinnedAmount, + 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 ) @@ -544,13 +572,36 @@ class ExternalSendViewModel internal constructor( .onEach { balance -> if (generation == balanceGeneration) _uiState.update { it.copy(balance = balance) } } - .mapLatest { balance -> if (balance == null) null else service.maxSendable(source, destination) } - .onEach { max -> - if (generation == balanceGeneration) _uiState.update { it.copy(maxSendable = max) } + .mapLatest { balance -> balance to if (balance == null) null else service.maxSendable(source, destination) } + .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() @@ -635,7 +686,13 @@ class ExternalSendViewModel internal constructor( 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, pinnedAmount = if (it.isMax) it.amount else it.pinnedAmount) } + _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. @@ -680,6 +737,7 @@ class ExternalSendViewModel internal constructor( 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/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index e319dad77d..8ee6da7ac6 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -27,6 +27,7 @@ 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.ui.shielded.toKeypadString import de.schildbach.wallet_test.R import io.mockk.every import io.mockk.mockk @@ -81,6 +82,9 @@ class ExternalSendViewModelTest { 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() @@ -92,7 +96,10 @@ class ExternalSendViewModelTest { override suspend fun isOwnIdentity(identityIdBase58: String): Boolean? = ownIdentity override suspend fun resolveIdentity(identityIdBase58: String): IdentityResolution = resolution override suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash) = fee - override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = max[source] + override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? { + maxGates[source]?.await() + return max[source] + } override suspend fun send( source: SendBalance, destination: SendDestination, @@ -913,20 +920,218 @@ class ExternalSendViewModelTest { } @Test - fun aDroppedMax_keepsItsExactAmount() { - val max = Dash(123_456_789) + 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] = max + 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(max, viewModel.uiState.value.amount) + assertEquals(shieldedMax, viewModel.uiState.value.amount) viewModel.onSourceSelected(SendBalance.PLATFORM) - assertFalse(viewModel.uiState.value.isMax) - assertEquals(max, viewModel.uiState.value.amount) + 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 From 5b5a77ef938c8290a2a9a6c5ba9a7824a5bd4312 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 11:36:23 -0800 Subject: [PATCH 14/30] refactor(payments): simplify External Send's fee, Max and read plumbing - estimateFee drops its unused amount; estimateFee and maxSendable take the source and destination balance kinds (balanceKindOf, now shared). - The shielded flag and own-identity flows are deduplicated before flatMapLatest, so an unrelated config write no longer restarts the balance flows or re-fetches the Identity balance. - sendFromShielded and nativeWrite return mapWrite's mapping. - The private retryReadErrors copy is replaced by the common helper. - PlatformAddressSyncService shares SdkL1SendService's cutover check. - ExternalSendFragment remembers its actions; the currency codes list is remembered per fiat code. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendModels.kt | 8 ++ .../platform/sdk/ExternalSendService.kt | 12 +- .../platform/sdk/ExternalSendServiceImpl.kt | 94 +++++++-------- .../sdk/PlatformAddressSyncService.kt | 5 +- .../service/platform/sdk/SdkL1SendService.kt | 14 ++- .../ui/payments/send/ExternalSendFragment.kt | 11 +- .../ui/payments/send/ExternalSendScreen.kt | 21 ++-- .../ui/payments/send/ExternalSendViewModel.kt | 7 +- .../sdk/ExternalSendServiceImplTest.kt | 108 ++++++++++++------ .../send/ExternalSendViewModelTest.kt | 4 +- 10 files changed, 166 insertions(+), 118 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 84713e9388..50a7329d60 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -63,6 +63,14 @@ sealed class SendDestination { } } +/** 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 { /** diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt index 0cef4b83e0..ff36294c59 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -121,15 +121,19 @@ interface ExternalSendService { /** Identity lookup for the confirm step (AC8). Never logs the id. */ suspend fun resolveIdentity(identityIdBase58: String): IdentityResolution - /** Fee for this exact send, or null when it cannot be known before the send (never fabricated). */ - suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? + /** + * 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 every other pair the - * amount the recipient receives (balance minus the fee paid on top). + * amount the recipient receives (balance minus the fee paid on top). [destinationKind] is + * [balanceKindOf] of the destination. */ - suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? + suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? /** * Send [amount] from [source] to [destination]. The caller has ALREADY diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 8b67a4514e..d2a54813ed 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -43,7 +43,6 @@ import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.withContext import org.dash.wallet.common.money.Dash import org.dash.wallet.common.payments.parsers.AddressNetwork @@ -53,6 +52,7 @@ 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.slf4j.LoggerFactory import java.util.UUID @@ -261,24 +261,14 @@ internal fun shieldPoolFeeDuffs(shieldFeeCredits: Long): Long = Math.addExact(ceilCreditsToDuffs(shieldFeeCredits), ShieldedBalanceServiceImpl.ASSET_LOCK_BASE_COST_DUFFS) /** - * Keep a live observation alive across read failures: on a (non-cancellation) [Exception] - * emit [unknown] and re-subscribe after [retryDelayMs] (attempt counted from 0) — never - * complete on a transient error. A [Throwable] that is not an [Exception] is rethrown. + * 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 Flow.retryReadErrors( +internal fun logReadRetry( what: String, - unknown: T, retryDelayMs: (Long) -> Long = ::readRetryDelayMs -): Flow = retryWhen { cause, attempt -> - if (cause is CancellationException || cause !is Exception) { - false - } else { - val delayMs = retryDelayMs(attempt) - retryLog.warn("external send: {} unreadable; unknown, retrying in {} ms", what, delayMs, cause) - emit(unknown) - delay(delayMs) - true - } +): (Exception, Long) -> Unit = { cause, attempt -> + retryLog.warn("external send: {} unreadable; unknown, retrying in {} ms", what, retryDelayMs(attempt), cause) } private val retryLog = LoggerFactory.getLogger("de.schildbach.wallet.service.platform.sdk.ExternalSendRetry") @@ -511,7 +501,10 @@ internal class DashSdkExternalSendSource( identityConfig.observePreservingErrors(BlockchainIdentityConfig.IDENTITY_ID), identityConfig.observePreservingErrors(BlockchainIdentityConfig.CREATION_STATE) ) { id, state -> Result.success(ownIdentity(id, state)) } - .retryReadErrors("identity record", Result.failure(IllegalStateException("identity record unreadable"))) + .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? { @@ -544,6 +537,8 @@ internal class DashSdkExternalSendSource( 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) @@ -557,7 +552,7 @@ internal class DashSdkExternalSendSource( } } } - .retryReadErrors("shielded balance", null) + .retryReadErrors(null, onError = logReadRetry("shielded balance")) override suspend fun platformAddressBalances(walletIdHex: String): List = wallet(walletIdHex).addressesWithBalances() @@ -848,7 +843,9 @@ class ExternalSendServiceImpl internal constructor( .fold(0L) { acc, input -> Math.addExact(acc, input.credits) } creditsToDash(credits) } - SendBalance.IDENTITY -> this.source.observeOwnIdentityId().flatMapLatest { own -> + // 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) @@ -856,7 +853,7 @@ class ExternalSendServiceImpl internal constructor( polled { _ -> this.source.identityBalanceCredits(id)?.takeIf { it >= 0 }?.let(::creditsToDash) } } } - }.retryReadErrors("$source balance", null, retryDelayMs).distinctUntilChanged() + }.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 { @@ -877,7 +874,7 @@ class ExternalSendServiceImpl internal constructor( override fun observeHasIdentity(): Flow = source.observeOwnIdentityId() .map, Boolean?> { result -> if (result.isFailure) null else result.getOrNull() != null } - .retryReadErrors("identity record", null, retryDelayMs) + .retryReadErrors(null, retryDelayMs, logReadRetry("identity record", retryDelayMs)) .distinctUntilChanged() override fun currentWalletIdOrNull(): String? = try { @@ -926,9 +923,9 @@ class ExternalSendServiceImpl internal constructor( return IdentityResolution.Found(username) } - override suspend fun estimateFee(source: SendBalance, destination: SendDestination, amount: Dash): FeeEstimate? = + override suspend fun estimateFee(source: SendBalance, destinationKind: SendBalance): FeeEstimate? = try { - withContext(ioDispatcher) { estimateFeeInner(source, destination) } + withContext(ioDispatcher) { estimateFeeInner(source, destinationKind) } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -955,19 +952,19 @@ class ExternalSendServiceImpl internal constructor( * fee of the asset unlock comes out of the amount on top; Platform/Identity → Shielded * add the shielded compute fee to the metered one.) */ - private suspend fun estimateFeeInner(source: SendBalance, destination: SendDestination): FeeEstimate? = + private suspend fun estimateFeeInner(source: SendBalance, destinationKind: SendBalance): FeeEstimate? = when (source) { - SendBalance.CORE -> when (destination) { - is SendDestination.Core -> FeeEstimate(Dash(coreSendFeeReserveDuffs()), exact = false) - is SendDestination.Shielded -> this.source.shieldedFeeCredits(ShieldedFeeKind.TRANSFER)?.let { + 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) } - is SendDestination.Platform -> this.source.spendableUtxoCount()?.let { + SendBalance.PLATFORM -> this.source.spendableUtxoCount()?.let { FeeEstimate(Dash(coreToPlatformFeeDuffs(it)), exact = false) } - is SendDestination.Identity -> null + SendBalance.IDENTITY -> null } - SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destination))?.let { + SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destinationKind))?.let { FeeEstimate(Dash(ceilCreditsToDuffs(it)), exact = false) } SendBalance.PLATFORM, SendBalance.IDENTITY -> null @@ -986,18 +983,18 @@ class ExternalSendServiceImpl internal constructor( * retries once with the exact deficit the note selection reports. * - Everything else: null (no pre-send fee figure). */ - override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? = try { + override suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? = try { when (source) { - SendBalance.CORE -> when (destination) { - is SendDestination.Core -> withContext(ioDispatcher) { coreToCoreMaxDuffs() }?.let(::Dash) - is SendDestination.Shielded -> withContext(ioDispatcher) { coreToShieldedMaxDuffs() }?.let(::Dash) - is SendDestination.Platform -> withContext(ioDispatcher) { coreToPlatformMaxDuffsOrNull() }?.let(::Dash) - is SendDestination.Identity -> null + 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(destination)) + this@ExternalSendServiceImpl.source.shieldedFeeCredits(shieldedKindFor(destinationKind)) } if (balance == null || feeCredits == null) { null @@ -1585,10 +1582,7 @@ class ExternalSendServiceImpl internal constructor( result = attempt(adjustment.adjustedAmount) } } - return when (result) { - is SdkWriteResult.Broadcast -> ExternalSendResult.Sent(null) - else -> mapWrite(pair, result) - } + return mapWrite(pair, result) } private suspend fun sendFromPlatform( @@ -1719,12 +1713,8 @@ class ExternalSendServiceImpl internal constructor( // A native-boundary failure before the call ran (e.g. UnsatisfiedLinkError). SdkWriteResult.NotBroadcast("native library unavailable", e) } - return if (result is SdkWriteResult.Broadcast) { - log.info("external send {}: sent", pair) - ExternalSendResult.Sent(null) - } else { - mapWrite(pair, result) - } + if (result is SdkWriteResult.Broadcast) log.info("external send {}: sent", pair) + return mapWrite(pair, result) } private fun mapWrite(pair: String, result: SdkWriteResult<*>): ExternalSendResult = when (result) { @@ -1785,11 +1775,11 @@ class ExternalSendServiceImpl internal constructor( is SendDestination.Identity -> "Identity" } - private fun shieldedKindFor(destination: SendDestination): ShieldedFeeKind = when (destination) { - is SendDestination.Core -> ShieldedFeeKind.WITHDRAWAL - is SendDestination.Shielded -> ShieldedFeeKind.TRANSFER - is SendDestination.Platform -> ShieldedFeeKind.UNSHIELD - is SendDestination.Identity -> ShieldedFeeKind.IDENTITY_TOP_UP + 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 index 0e7af330e3..b52954e2ba 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/PlatformAddressSyncService.kt @@ -18,7 +18,6 @@ package de.schildbach.wallet.service.platform.sdk import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.flow.first import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull @@ -58,9 +57,7 @@ private class DashSdkPlatformAddressSyncSource( private fun liveManager() = sdkService.walletManagerOrNull()?.takeUnless { it.isClosed } override suspend fun ready(): Boolean { - val cutoverCommitted = !dashjEngineMayStart( - CutoverState.fromStored(dashPayConfig.observePreservingErrors(DashPayConfig.CUTOVER_STATE).first()) - ) + val cutoverCommitted = dashPayConfig.cutoverCommittedOrThrow() if (!cutoverCommitted || !sdkWalletBinder.bindEstablished.value) return false return liveManager()?.wallets?.value?.size == 1 } 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/ui/payments/send/ExternalSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt index 8f1844bb64..e9f92bd31b 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt @@ -27,6 +27,7 @@ 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 @@ -75,9 +76,10 @@ class ExternalSendFragment : Fragment() { DashWalletTheme { val uiState by viewModel.uiState.collectAsStateWithLifecycle() BackHandler { onBack() } - ExternalSendScreen( - uiState = uiState, - actions = ExternalSendActions( + // 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, @@ -97,7 +99,8 @@ class ExternalSendFragment : Fragment() { onLeave = ::leave, onResultClosed = ::onResultClosed ) - ) + } + ExternalSendScreen(uiState = uiState, actions = actions) } } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index 5fbb465b3e..c3234e73e1 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -65,6 +65,7 @@ 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 @@ -263,10 +264,14 @@ private fun ClipboardEntries(entries: List, onSelected: (String) -> Unit // ── 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 = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE) + val codes = remember(fiatCode) { currencyCodesFor(fiatCode) } Column(modifier = Modifier.fillMaxSize()) { TopNavBase( leadingIcon = MyImages.MenuChevron, @@ -677,7 +682,7 @@ private fun ConfirmAmount(amount: Dash, rate: Fiat?, fiatCode: String?) { EnterAmount( primaryAmount = localizeAmountForDisplay(amount.toDisplayString(), separator), secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", - currencyCodes = if (fiatCode != null) listOf(DASH_CURRENCY_CODE, fiatCode) else listOf(DASH_CURRENCY_CODE), + currencyCodes = remember(fiatCode) { currencyCodesFor(fiatCode) }, selectedCurrencyIndex = 0, showMaxButton = false, showBalanceButton = false, @@ -855,7 +860,7 @@ internal fun iconFor(source: SendBalance): Int = when (source) { } @DrawableRes -internal fun iconFor(destination: SendDestination): Int = iconFor(balanceOf(destination)) +internal fun iconFor(destination: SendDestination): Int = iconFor(balanceKindOf(destination)) @StringRes internal fun titleFor(source: SendBalance): Int = when (source) { @@ -866,7 +871,7 @@ internal fun titleFor(source: SendBalance): Int = when (source) { } @StringRes -internal fun titleFor(destination: SendDestination): Int = titleFor(balanceOf(destination)) +internal fun titleFor(destination: SendDestination): Int = titleFor(balanceKindOf(destination)) @StringRes internal fun balanceNameFor(source: SendBalance): Int = when (source) { @@ -876,14 +881,6 @@ internal fun balanceNameFor(source: SendBalance): Int = when (source) { SendBalance.IDENTITY -> R.string.external_send_balance_name_identity } -/** The kind of balance a destination is paid into, for its icon and name. */ -private fun balanceOf(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 -} - @Preview(showBackground = true, widthDp = 420, heightDp = 926) @Composable private fun ExternalSendAmountPreview() { diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index 23c40edf19..a876cbff16 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -30,6 +30,7 @@ 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.balanceKindOf import de.schildbach.wallet.service.platform.sdk.detectSendDestination import de.schildbach.wallet.service.platform.sdk.externalSendSupport import de.schildbach.wallet.ui.shielded.parseDashOrNull @@ -565,14 +566,14 @@ class ExternalSendViewModel internal constructor( private fun restartBalance() { balanceJob?.cancel() val state = _uiState.value - val destination = state.destination ?: return + 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) } } - .mapLatest { balance -> balance to if (balance == null) null else service.maxSendable(source, destination) } + .mapLatest { balance -> balance to if (balance == null) null else service.maxSendable(source, destinationKind) } .onEach { (balance, max) -> if (generation == balanceGeneration) onMaxSendable(balance, max) } @@ -640,7 +641,7 @@ class ExternalSendViewModel internal constructor( _uiState.update { it.copy(confirm = ExternalSendConfirm(request)) } feeJob?.cancel() feeJob = viewModelScope.launch { - val fee = service.estimateFee(request.source, request.destination, request.amount) + val fee = service.estimateFee(request.source, balanceKindOf(request.destination)) _uiState.update { state -> val confirm = state.confirm if (confirm?.request == request) { diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index f68a932547..03ce713886 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -23,6 +23,10 @@ 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 @@ -35,6 +39,7 @@ 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 @@ -115,7 +120,11 @@ class ExternalSendServiceImplTest { var shieldedFlow: Flow? = null override fun observeShieldedBalance(): Flow = shieldedFlow ?: flowOf(shieldedBalance) override suspend fun platformAddressBalances(walletIdHex: String): List = platformBalances() - override suspend fun identityBalanceCredits(identityIdBase58: String): Long? = 2_000_000_000L + 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 @@ -581,8 +590,8 @@ class ExternalSendServiceImplTest { fun int37Pairs_haveNoPreSendFee_andNoMax() = runBlocking { val service = service(source().apply { platformBalances = { listOf(address(1, 900_000_000L)) } }) for ((from, to) in listOf(SendBalance.PLATFORM to core, SendBalance.PLATFORM to shielded, SendBalance.IDENTITY to shielded)) { - assertNull("$from → $to", service.estimateFee(from, to, amount)) - assertNull("$from → $to", service.maxSendable(from, to)) + assertNull("$from → $to", service.estimateFee(from, balanceKindOf(to))) + assertNull("$from → $to", service.maxSendable(from, balanceKindOf(to))) } } @@ -863,7 +872,7 @@ class ExternalSendServiceImplTest { 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, core)) + assertNull(service.maxSendable(SendBalance.SHIELDED, balanceKindOf(core))) } @Test @@ -875,19 +884,19 @@ class ExternalSendServiceImplTest { 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, core)) - assertNull(service.maxSendable(SendBalance.PLATFORM, platform)) + 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, core, amount)) - assertEquals(FeeEstimate(Dash(2_001L), exact = false), service.estimateFee(SendBalance.SHIELDED, core, amount)) - assertNull(service.estimateFee(SendBalance.PLATFORM, platform, amount)) - assertNull(service.estimateFee(SendBalance.IDENTITY, core, amount)) - assertNull(service.estimateFee(SendBalance.CORE, ownIdentity, amount)) + assertEquals(FeeEstimate(Dash(sendAllFeeReserveDuffs(2)), exact = false), service.estimateFee(SendBalance.CORE, balanceKindOf(core))) + assertEquals(FeeEstimate(Dash(2_001L), exact = false), service.estimateFee(SendBalance.SHIELDED, balanceKindOf(core))) + assertNull(service.estimateFee(SendBalance.PLATFORM, balanceKindOf(platform))) + assertNull(service.estimateFee(SendBalance.IDENTITY, balanceKindOf(core))) + assertNull(service.estimateFee(SendBalance.CORE, balanceKindOf(ownIdentity))) } @Test @@ -909,10 +918,10 @@ class ExternalSendServiceImplTest { 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, shielded, 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, shielded)) + val max = requireNotNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) assertEquals(Dash(5_000_000L) - assetLockMaxFeeReserve(2) - poolFee, max) assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, shielded, max, isMax = true)) assertEquals(listOf(Dash(5_000_000L) - assetLockMaxFeeReserve(2)), source.shieldedAmounts) @@ -929,18 +938,18 @@ class ExternalSendServiceImplTest { val service = service(source) assertEquals( Dash(3_000_000L) - assetLockMaxFeeReserve(2) - poolFee, - service.maxSendable(SendBalance.CORE, shielded) + 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, shielded)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) source.coreEligible = 3_000_000L source.utxoCount = null - assertNull(service.maxSendable(SendBalance.CORE, shielded)) + 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, shielded)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) } @Test @@ -949,7 +958,7 @@ class ExternalSendServiceImplTest { shieldFromCoreResult = { SdkWriteResult.NotBroadcast("asset lock coin selection is short") } } val service = service(source) - val max = requireNotNull(service.maxSendable(SendBalance.CORE, shielded)) + val max = requireNotNull(service.maxSendable(SendBalance.CORE, balanceKindOf(shielded))) assertEquals( ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), service.send(SendBalance.CORE, shielded, max, isMax = true) @@ -963,22 +972,22 @@ class ExternalSendServiceImplTest { val service = service(source) val reserve = sendAllFeeReserveDuffs(2) source.coreMax = reserve - assertNull(service.maxSendable(SendBalance.CORE, core)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(core))) source.coreMax = 1L - assertNull(service.maxSendable(SendBalance.CORE, core)) + 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, core)) - val fee = requireNotNull(service.estimateFee(SendBalance.CORE, core, max)).fee + 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, core)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(core))) assertEquals( FeeEstimate(Dash(SEND_ALL_FEE_RESERVE_DUFFS), exact = false), - service.estimateFee(SendBalance.CORE, core, amount) + service.estimateFee(SendBalance.CORE, balanceKindOf(core)) ) } @@ -1073,6 +1082,35 @@ class ExternalSendServiceImplTest { 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 + ) + 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 @@ -1080,7 +1118,11 @@ class ExternalSendServiceImplTest { reads++ if (reads <= 2) throw IllegalStateException("unknown creation state") emit(Result.success("id")) - }.retryReadErrors("identity record", Result.failure(IllegalStateException("unknown")), retryDelayMs = { 0L }) + }.retryReadErrors( + Result.failure(IllegalStateException("unknown")), + retryDelayMs = { 0L }, + onError = logReadRetry("identity record") { 0L } + ) .take(3) .toList() assertTrue(values[0].isFailure) @@ -1300,24 +1342,24 @@ class ExternalSendServiceImplTest { 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, platform, amount)) - assertEquals(Dash(5_000_000L) - fee, service.maxSendable(SendBalance.CORE, platform)) + 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, platform)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) source.coreEligible = 5_000_000L source.utxoCount = null - assertNull(service.maxSendable(SendBalance.CORE, platform)) - assertNull(service.estimateFee(SendBalance.CORE, platform, amount)) + 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, platform)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) source.coreEligible = fee.duffs + 499L - assertNull(service.maxSendable(SendBalance.CORE, platform)) + assertNull(service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) source.coreEligible = fee.duffs + 500L - assertEquals(Dash(500L), service.maxSendable(SendBalance.CORE, platform)) + assertEquals(Dash(500L), service.maxSendable(SendBalance.CORE, balanceKindOf(platform))) } @Test diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 8ee6da7ac6..91d7216639 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -95,8 +95,8 @@ class ExternalSendViewModelTest { 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, destination: SendDestination, amount: Dash) = fee - override suspend fun maxSendable(source: SendBalance, destination: SendDestination): Dash? { + override suspend fun estimateFee(source: SendBalance, destinationKind: SendBalance) = fee + override suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? { maxGates[source]?.await() return max[source] } From 7aad25f1f3eb87bc79725f9c78721f45b280a5e0 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 15:02:04 -0800 Subject: [PATCH 15/30] fix(payments): draw the External Send result inside the screen The result used ModalDialog, a separate window that stayed above the lock screen and could be closed without the PIN. It is now an in-screen overlay like the source and confirm sheets, so the lock screen covers it and it shows again after unlock. Back acknowledges the result as the dialog did, and is ignored while the lock screen shows. Co-Authored-By: Claude Opus 5.5 --- .../ui/payments/send/ExternalSendFragment.kt | 12 +++ .../ui/payments/send/ExternalSendScreen.kt | 100 ++++++++++++++---- 2 files changed, 92 insertions(+), 20 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt index 8f1844bb64..56fa3cf980 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt @@ -39,6 +39,7 @@ import de.schildbach.wallet.service.platform.sdk.ExternalSendResult import de.schildbach.wallet_test.R import kotlinx.coroutines.launch import org.dash.wallet.common.services.AuthenticationManager +import org.dash.wallet.common.ui.LockScreenHost import org.dash.wallet.common.ui.components.DashWalletTheme import org.dash.wallet.common.ui.scan.ScanActivity import javax.inject.Inject @@ -102,7 +103,18 @@ class ExternalSendFragment : Fragment() { } } + /** + * 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 status = viewModel.uiState.value.status + if (status is ExternalSendStatus.Done) { + onResultClosed(status.result) + return + } if (!viewModel.onBack()) leave() } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index 5fbb465b3e..426c24ee6a 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -39,6 +39,8 @@ 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 @@ -73,7 +75,6 @@ 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.ButtonData 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 @@ -83,7 +84,6 @@ 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.ModalDialog import org.dash.wallet.common.ui.components.MyImages import org.dash.wallet.common.ui.components.MyTheme import org.dash.wallet.common.ui.components.Size @@ -123,7 +123,7 @@ class ExternalSendActions( * 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 [ModalDialog]. + * shielded flows (a dimmed progress card) and [org.dash.wallet.common.ui.components.ModalDialog]. */ @Composable fun ExternalSendScreen(uiState: ExternalSendUIState, actions: ExternalSendActions) { @@ -150,7 +150,7 @@ fun ExternalSendScreen(uiState: ExternalSendUIState, actions: ExternalSendAction when (val status = uiState.status) { is ExternalSendStatus.Sending -> SendingOverlay(status.shieldedLeg, actions.onLeave) is ExternalSendStatus.Done -> - ResultDialog(status.result, status.afterRestart) { actions.onResultClosed(status.result) } + ResultOverlay(status.result, status.afterRestart) { actions.onResultClosed(status.result) } ExternalSendStatus.Idle, ExternalSendStatus.Restoring -> {} } } @@ -776,25 +776,85 @@ private fun SendingOverlay(shieldedLeg: Boolean, onLeave: () -> Unit) { } } -/** The terminal outcome. Only Not sent offers to go back and edit; nothing offers a retry. */ +/** + * 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 ResultDialog(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { +private fun ResultOverlay(result: ExternalSendResult, afterRestart: Boolean, onClose: () -> Unit) { + val colors = LocalDashColors.current val content = resultContentFor(result, afterRestart) - ModalDialog( - showDialog = true, - onDismissRequest = onClose, - icon = ImageVector.vectorResource(content.icon), - heading = stringResource(content.title), - textBlocks = listOf(stringResource(content.message)), - buttons = listOf( - ButtonData( - label = stringResource(content.button), - onClick = onClose, - isPrimary = true, - style = Style.TintedGray + 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]. */ From 45c60f2ddc9e4609054163c1a89ff23fec9cad62 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 15:15:11 -0800 Subject: [PATCH 16/30] feat(payments): open the transaction result after a Core-sourced External Send A Core send that builds a transaction now returns its txid: the payment itself for Core -> Core, and the asset lock for Core -> Platform, Core -> Shielded and Core -> own identity. The screen then opens TransactionResultActivity once, acknowledges the outcome and returns Home, as the Basic send flow does. It opens only while the screen is resumed and the wallet is unlocked. Sends without a Core transaction, and every failure or unknown outcome, keep the in-screen result. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendServiceImpl.kt | 33 +++++-- .../platform/sdk/SdkTransparentTopUp.kt | 55 ++++++++++- .../platform/sdk/ShieldedBalanceService.kt | 17 +++- .../sdk/ShieldedBalanceServiceImpl.kt | 43 +++++++-- .../ui/payments/send/ExternalSendFragment.kt | 45 ++++++++- .../ui/payments/send/ExternalSendScreen.kt | 4 +- .../ui/payments/send/ExternalSendViewModel.kt | 37 +++++++ .../transactions/TransactionResultActivity.kt | 13 +++ .../sdk/ExternalSendServiceImplTest.kt | 96 ++++++++++++++++--- .../platform/sdk/SdkTransparentTopUpTest.kt | 94 +++++++++++++++++- .../sdk/ShieldedBalanceServiceTest.kt | 27 +++++- .../send/ExternalSendViewModelTest.kt | 69 +++++++++++++ 12 files changed, 491 insertions(+), 42 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 8b67a4514e..9fbd7bb4f1 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -366,8 +366,8 @@ internal interface ExternalSendSource { walletIdHex: String, address: String, amount: Dash - ): SdkWriteResult - suspend fun coreTopUpIdentity(identityIdBase58: String, amountDuffs: Long): SdkWriteResult + ): SdkWriteResult + suspend fun coreTopUpIdentity(identityIdBase58: String, amountDuffs: Long): SdkWriteResult suspend fun platformTransfer(walletIdHex: String, to: PlatformAddressBytes, amountCredits: Long) suspend fun platformTopUpIdentity(walletIdHex: String, identityId: ByteArray, inputs: List) suspend fun identityWithdraw(walletIdHex: String, fromId: ByteArray, amountCredits: Long, coreAddress: String) @@ -604,8 +604,8 @@ internal class DashSdkExternalSendSource( 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.topUp(identityIdBase58, amountDuffs, newUserIntent = true) + 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() @@ -1192,7 +1192,11 @@ class ExternalSendServiceImpl internal constructor( if (!stillBound(pair, walletIdHex)) { ExternalSendResult.NotSent(NotSentReason.GENERIC) } else { - mapWrite(pair, this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) + when (val result = this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) { + is SdkWriteResult.Broadcast -> + ExternalSendResult.Sent(displayTxIdOrNull(result.value.lockTxIdDisplayHexOrNull)) + else -> mapWrite(pair, result) + } } } is SendDestination.Platform -> sendCoreToPlatform(pair, walletIdHex, destination, amount, amountCredits) @@ -1312,7 +1316,8 @@ class ExternalSendServiceImpl internal constructor( if (outcome is SdkWriteResult.Broadcast) { clearPlatformFunding(pair, record.id) log.info("external send {}: sent", pair) - return ExternalSendResult.Sent(null) + // 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. @@ -1532,8 +1537,9 @@ class ExternalSendServiceImpl internal constructor( 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) { - ShieldFromWalletOutcome.COMPLETED -> ExternalSendResult.Sent(null) + 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 @@ -1548,7 +1554,7 @@ class ExternalSendServiceImpl internal constructor( walletIdHex: String, address: String, amount: Dash - ): SdkWriteResult = + ): SdkWriteResult = if (!stillBound(pair, walletIdHex)) { SdkWriteResult.NotBroadcast("the bound wallet changed") } else { @@ -1727,6 +1733,15 @@ class ExternalSendServiceImpl internal constructor( } } + /** + * [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 -> { 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..2d2defd1c2 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,7 @@ 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.AtomicReference import javax.inject.Inject import javax.inject.Singleton @@ -230,6 +231,16 @@ 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. + */ +data class TopUpOutcome( + val creditBalance: Long, + val lockTxIdDisplayHexOrNull: String? +) + /** * TRANSPARENT-funded identity TOP-UP ("Buy Credits") — the post-cutover * replacement for the dashj asset-lock funding path in @@ -389,6 +400,34 @@ 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. + */ + suspend fun topUpReportingLockTxId( + identityIdBase58: String, + amountDuffs: Long, + newUserIntent: Boolean + ): SdkWriteResult { + val lockTxId = AtomicReference(null) + return when ( + val result = topUpGuarded(identityIdBase58, amountDuffs, newUserIntent, onLockTxId = { lockTxId.set(it) }) + ) { + is SdkWriteResult.Broadcast -> SdkWriteResult.Broadcast(TopUpOutcome(result.value, lockTxId.get())) + is SdkWriteResult.NotBroadcast -> result + is SdkWriteResult.Ambiguous -> result + } + } + + private suspend fun topUpGuarded( + identityIdBase58: String, + amountDuffs: Long, + newUserIntent: Boolean, + onLockTxId: (String) -> Unit ): SdkWriteResult { synchronized(this) { when (guard) { @@ -407,7 +446,9 @@ class SdkTransparentTopUp internal constructor( } } val result = try { - withContext(ioDispatcher) { topUpTransparent(identityIdBase58, amountDuffs, newUserIntent) } + withContext(ioDispatcher) { + topUpTransparent(identityIdBase58, amountDuffs, newUserIntent, onLockTxId = onLockTxId) + } } 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 +491,12 @@ 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 = {} ): SdkWriteResult { // Fail closed unless the cutover is committed — pre-cutover this path // must submit nothing (the dashj path owns funding then). @@ -575,6 +621,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 +641,8 @@ class SdkTransparentTopUp internal constructor( identityIdBase58, amountDuffs, newUserIntent, - skipLockOutpoint = existingLock.outpointTxid to existingLock.outpointVout + skipLockOutpoint = existingLock.outpointTxid to existingLock.outpointVout, + onLockTxId = onLockTxId ) } return when (val classified = classifyBroadcastFailure(t)) { @@ -656,6 +704,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 { 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 6884c4652d..1373ab6df1 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: @@ -622,12 +634,15 @@ interface ShieldedBalanceService { * 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 + ): SdkWriteResult /** * The consensus-pinned flat pool fee, in credits, of a single-note (2-action) 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 04e0e3da44..d72f7d2b29 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 @@ -2261,7 +2262,12 @@ class ShieldedBalanceServiceImpl internal constructor( * address — [shieldFromWalletToAddress]. Changes the stage (b) classification, see * [classifyWalletShieldFailure]. */ - externalRecipientRaw43: ByteArray? = null + 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") @@ -2460,14 +2466,18 @@ class ShieldedBalanceServiceImpl internal constructor( // classification instead of "Internal". 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, 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) @@ -2771,15 +2781,28 @@ class ShieldedBalanceServiceImpl internal constructor( toShieldedAddress: String, amount: Dash, expectedWalletIdHex: String - ): SdkWriteResult { + ): SdkWriteResult { val recipientRaw43 = decodeOrchardAddress(toShieldedAddress, displayHrpSafe()) ?: return notBroadcast("shieldFromWallet", "malformed or wrong-network shielded address", null) - return shieldFromWalletInternal( - amount, - fundingPath = null, - expectedWalletIdHex = expectedWalletIdHex, - externalRecipientRaw43 = recipientRaw43 - ) + 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? { diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt index 56fa3cf980..be9d3e84e2 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendFragment.kt @@ -36,10 +36,14 @@ 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 @@ -60,6 +64,9 @@ class ExternalSendFragment : Fragment() { @Inject lateinit var authManager: AuthenticationManager + @Inject + lateinit var lockScreenBroadcaster: LockScreenBroadcaster + private val scanLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> @@ -103,6 +110,23 @@ class ExternalSendFragment : Fragment() { } } + 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 @@ -110,7 +134,13 @@ class ExternalSendFragment : Fragment() { */ private fun onBack() { if ((activity as? LockScreenHost)?.lockScreenDisplayed == true) return - val status = viewModel.uiState.value.status + 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 @@ -168,6 +198,19 @@ class ExternalSendFragment : Fragment() { } } + /** + * 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. diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index 426c24ee6a..2b992e3f07 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -149,8 +149,10 @@ fun ExternalSendScreen(uiState: ExternalSendUIState, actions: ExternalSendAction when (val status = uiState.status) { is ExternalSendStatus.Sending -> SendingOverlay(status.shieldedLeg, actions.onLeave) - is ExternalSendStatus.Done -> + // 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 -> {} } } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index 23c40edf19..aa612bc7d8 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -41,13 +41,17 @@ import de.schildbach.wallet.ui.shielded.toKeypadStringTwoDecimals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job 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.mapLatest import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.dash.wallet.common.data.WalletUIConfig @@ -59,6 +63,8 @@ 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 } @@ -148,6 +154,20 @@ data class ExternalSendUIState( 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 @@ -277,6 +297,16 @@ class ExternalSendViewModel internal constructor( 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 @@ -677,6 +707,13 @@ class ExternalSendViewModel internal constructor( 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). 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/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index f68a932547..e8374c2030 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -84,8 +84,10 @@ class ExternalSendServiceImplTest { var shieldedBalance: Dash? = Dash(1_000_000L) var platformBalances: () -> List = { emptyList() } var shieldedResult: (Dash) -> SdkWriteResult = { SdkWriteResult.Broadcast(Unit) } - var shieldFromCoreResult: (Dash) -> SdkWriteResult = - { SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED) } + 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: () -> Unit = {} val shieldedAmounts = mutableListOf() @@ -145,16 +147,23 @@ class ExternalSendServiceImplTest { return shielded("shieldedTopUpIdentity", amount) } - override suspend fun shieldFromCore(walletIdHex: String, address: String, amount: Dash): SdkWriteResult { + 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 { + override suspend fun coreTopUpIdentity( + identityIdBase58: String, + amountDuffs: Long + ): SdkWriteResult { calls += "coreTopUpIdentity" lastDuffs = amountDuffs - return SdkWriteResult.Broadcast(1L) + return coreTopUpResult() } override suspend fun platformTransfer(walletIdHex: String, to: PlatformAddressBytes, amountCredits: Long) { @@ -330,11 +339,16 @@ class ExternalSendServiceImplTest { @Test fun coreToShielded_completed_isSent_pendingRetry_isInterrupted() = runBlocking { val source = source() - assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.CORE, shielded, amount, false)) + 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(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY) } + source.shieldFromCoreResult = { + SdkWriteResult.Broadcast(ShieldToAddressOutcome(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY)) + } assertEquals( ExternalSendResult.InterruptedFundsReturnToShielded, service(source).send(SendBalance.CORE, shielded, amount, false) @@ -342,13 +356,46 @@ class ExternalSendServiceImplTest { } @Test - fun coreToOwnIdentity_topsUpInDuffs() = runBlocking { + 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(null), service(source).send(SendBalance.CORE, ownIdentity, amount, false)) + 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 shieldedToEachDestination_callsItsShieldedWrite() = runBlocking { val expected = mapOf( @@ -914,7 +961,10 @@ class ExternalSendServiceImplTest { // minus the pool fee. val max = requireNotNull(service.maxSendable(SendBalance.CORE, shielded)) assertEquals(Dash(5_000_000L) - assetLockMaxFeeReserve(2) - poolFee, max) - assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, shielded, max, isMax = true)) + assertEquals( + ExternalSendResult.Sent(SHIELD_LOCK_TXID), + service.send(SendBalance.CORE, shielded, max, isMax = true) + ) assertEquals(listOf(Dash(5_000_000L) - assetLockMaxFeeReserve(2)), source.shieldedAmounts) } @@ -1113,7 +1163,8 @@ class ExternalSendServiceImplTest { } val result = service(source, store).send(SendBalance.CORE, platform, amount, false) - assertEquals(ExternalSendResult.Sent(null), result) + // 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. @@ -1152,7 +1203,7 @@ class ExternalSendServiceImplTest { ioDispatcher = Dispatchers.Unconfined, seedAssetLockKind = { hex, kind -> seeds += hex to kind } ) - assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, platform, amount, false)) + 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) @@ -1169,10 +1220,24 @@ class ExternalSendServiceImplTest { ioDispatcher = Dispatchers.Unconfined, seedAssetLockKind = { _, _ -> throw IllegalStateException("seed") } ) - assertEquals(ExternalSendResult.Sent(null), service.send(SendBalance.CORE, platform, amount, false)) + 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() @@ -1417,7 +1482,7 @@ class ExternalSendServiceImplTest { assertEquals(0, service.resumePendingPlatformFunding()) assertTrue(source.resumed.isEmpty()) release.complete(Unit) - assertEquals(ExternalSendResult.Sent(null), send.await()) + assertEquals(ExternalSendResult.Sent(LOCK_TXID), send.await()) } finally { release.complete(Unit) } @@ -1435,6 +1500,9 @@ class ExternalSendServiceImplTest { 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/SdkTransparentTopUpTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt index 065983ca4f..505e2ed8d7 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,95 @@ 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_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 97737a533c..2b8cfdce34 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -3666,11 +3666,30 @@ class ShieldedBalanceServiceTest { val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) - assertEquals(SdkWriteResult.Broadcast(ShieldFromWalletOutcome.COMPLETED), result) + // 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 + ) + } + @Test fun shieldFromWalletToAddress_otherWallet_isNotBroadcast_beforeFunding() = runBlocking { val source = readySource() @@ -3711,7 +3730,11 @@ class ShieldedBalanceServiceTest { source.onFund = { funded = true; throw DashSdkError.InvalidParameter("shield transition rejected") } val result = service.shieldFromWalletToAddress(recipientAddress, Dash.COIN, walletIdHex) - assertEquals(SdkWriteResult.Broadcast(ShieldFromWalletOutcome.SHIELD_PENDING_RETRY), result) + // 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()) diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 8ee6da7ac6..550b7c88c7 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -834,6 +834,75 @@ class ExternalSendViewModelTest { assertTrue(marker.value) } + // ── 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 From 9a51adc222256011937ebe67c60d625a0fbc4b24 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 16:17:25 -0800 Subject: [PATCH 17/30] fix(payments): restore the External Send From/To card colours The material3 Card import added for the result overlay took precedence over the screen's private Card, so the From/To cards drew as Material3 cards (lavender, no padding). The private one is now SendCard. Co-Authored-By: Claude Opus 5.5 --- .../wallet/ui/payments/send/ExternalSendScreen.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index cd6c5fe8e2..d199a759ff 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -324,7 +324,7 @@ private fun FromToCards(uiState: ExternalSendUIState, actions: ExternalSendActio val destination = uiState.destination ?: return Box(modifier = Modifier.fillMaxWidth()) { Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { - Card { + SendCard { val balance = uiState.balance val changeDescription = stringResource(R.string.external_send_change_source) DirectionRow( @@ -379,7 +379,7 @@ private fun FromToCards(uiState: ExternalSendUIState, actions: ExternalSendActio } ) } - Card { + SendCard { DirectionRow( icon = iconFor(destination), label = stringResource(R.string.external_send_to), @@ -419,7 +419,7 @@ private fun FromToCards(uiState: ExternalSendUIState, actions: ExternalSendActio /** A Figma "menu" card: secondary background, 20dp corners, 6dp padding. */ @Composable -private fun Card(content: @Composable ColumnScope.() -> Unit) { +private fun SendCard(content: @Composable ColumnScope.() -> Unit) { Column( modifier = Modifier .fillMaxWidth() From 6aecbaeb0403d9b7b53b858d1c8ae242da0bf78c Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Tue, 10 Nov 2026 16:17:26 -0800 Subject: [PATCH 18/30] fix(payments): clear a Core -> Platform funding Platform already has A Core -> Platform send interrupted after its transition was submitted could never resume: each resume rebuilds the same bytes, Tenderdash refuses them as already in its cache, and the SDK returns that error without waiting for the result. The record was kept, so every later Core -> Platform send was refused as still pending. The resume sweep now clears the record on the SDK's AlreadyExists error. Platform consumes a lock once, so nothing can be paid twice. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalPlatformFunding.kt | 31 ++++++++++++++++ .../platform/sdk/ExternalSendServiceImpl.kt | 18 ++++++++- .../sdk/ExternalSendServiceImplTest.kt | 37 +++++++++++++++++++ 3 files changed, 84 insertions(+), 2 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt index 4868f8c819..51f7ac73de 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt @@ -21,6 +21,7 @@ import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet.ui.shielded.assetLockMaxFeeReserve import kotlinx.coroutines.runBlocking import org.bitcoinj.core.Utils +import org.dashfoundation.dashsdk.errors.DashSdkError // Advanced-mode External Send, Core → third-party Platform address (MO-1121): // the persisted recipient record the SDK's resume contract requires, and the @@ -65,6 +66,36 @@ internal const val EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX = 0 */ internal const val ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP = 4 +/** + * Whether an SDK funding call was refused because Platform already knows this exact state + * transition: rs-sdk `Error::AlreadyExists`, which the JNI surfaces as a Generic error + * reading "Object already exists: …" — Tenderdash's "tx already exists in cache", or + * DAPI's "state transition already in mempool" / "already in chain". + * + * On a resume this is terminal for the record: the transition is signed over the lock and + * exactly the persisted recipients and nothing else varies (no fee bump on resume), so every + * resume rebuilds the same bytes and Tenderdash refuses them again for as long as its cache + * holds the first submission. The SDK does not wait for that submission's result after this + * error (rs-sdk `broadcast_and_wait_for_affected_state_with_metadata` returns on the + * broadcast error), so the wallet never learns the outcome from the call. + * + * Message-matched, down the cause chain because the JNI wraps it, until the SDK types it; + * only errors raised by the SDK ([DashSdkError]) qualify. + */ +internal fun isTransitionAlreadyKnownToPlatform(t: Throwable): Boolean { + if (t !is DashSdkError) return false + var cause: Throwable? = t + var hops = 0 + while (cause != null && hops++ < 8) { + if (cause.message?.contains(SDK_ALREADY_EXISTS_PREFIX) == true) return true + cause = cause.cause + } + return false +} + +/** rs-sdk `Error::AlreadyExists`'s display prefix. */ +private const val SDK_ALREADY_EXISTS_PREFIX = "Object already exists:" + /** 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) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index d434920d1c..b2b6993bef 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -1389,8 +1389,12 @@ class ExternalSendServiceImpl internal constructor( * - 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 on success or when - * Platform answers already consumed. + * [MAX_PLATFORM_RESUME_ATTEMPTS_PER_PROCESS] times per process; clear on success, when + * Platform answers already consumed, or when Platform already has the identical + * transition ([isTransitionAlreadyKnownToPlatform]: submitted before a process death, + * so no resume can submit anything new). Clearing never pays twice: Platform consumes + * a lock's outpoint once (drive-abci `verify_asset_lock_is_not_spent_and_has_enough_balance`), + * and a later send builds a new lock. */ private suspend fun resumePendingPlatformFundingInner(): Int { val first = try { @@ -1460,6 +1464,16 @@ class ExternalSendServiceImpl internal constructor( if (isAssetLockAlreadyConsumed(e)) { platformFundingStore.clear(record.id) log.warn("pending platform funding {}: Platform reports the lock already consumed; cleared", record.id) + } else if (isTransitionAlreadyKnownToPlatform(e)) { + // The same transition (this lock, these recipients) was submitted before; + // every resume rebuilds identical bytes, so nothing more can be done here + // and keeping the record would only block every later Core → Platform send. + platformFundingStore.clear(record.id) + log.warn( + "pending platform funding {}: Platform already has this funding transition; " + + "its outcome is Platform's — cleared", + record.id + ) } else { log.warn("pending platform funding {}: resume failed (attempt {}); kept", record.id, attempts + 1, e) } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index 6c79e29122..f014d3bbc4 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -1460,6 +1460,43 @@ class ExternalSendServiceImplTest { assertNull(store.record) } + @Test + fun resume_transitionAlreadyKnownToPlatform_clearsTheRecord_andUnblocksTheNextSend() = runBlocking { + // Observed on-device after a process death mid-send: every resume rebuilt the same + // transition and Tenderdash refused it, so the record blocked all later sends. + val alreadyKnown = DashSdkError.PlatformWallet.Generic( + 1, + "SDK error: Object already exists: tx already exists in cache", + RuntimeException("SDK error: Object already exists: tx already exists in cache") + ) + val source = source().apply { resume = { throw alreadyKnown } } + val store = FakeStore().apply { record = pendingRecord() } + val service = service(source, store) + assertEquals(0, service.resumePendingPlatformFunding()) + assertEquals(1, source.resumed.size) + assertNull(store.record) + + // The next Core → Platform send is no longer refused as "still confirming". + source.resume = { throw AssertionError("nothing left to resume") } + assertEquals(ExternalSendResult.Sent(LOCK_TXID), service.send(SendBalance.CORE, platform, amount, false)) + assertEquals(1, source.funded.size) + } + + @Test + fun transitionAlreadyKnown_matchesOnlyTheSdkAlreadyExistsShape() { + val wrapped = DashSdkError.PlatformWallet.Generic( + 1, + "resume failed", + RuntimeException("SDK error: Object already exists: state transition already in chain") + ) + assertTrue(isTransitionAlreadyKnownToPlatform(wrapped)) + assertTrue( + !isTransitionAlreadyKnownToPlatform(RuntimeException("SDK error: Object already exists: tx already exists in cache")) + ) + assertTrue(!isTransitionAlreadyKnownToPlatform(DashSdkError.PlatformWallet.Generic(1, "Wallet already exists: x"))) + assertTrue(!isTransitionAlreadyKnownToPlatform(DashSdkError.PlatformWallet.Generic(1, "platform timeout"))) + } + @Test fun resume_failure_keepsTheRecord_andAttemptsAreCappedPerProcess() = runBlocking { val source = source().apply { resume = { throw RuntimeException("platform timeout") } } From 2fccaa602fa393b10e10368ed3141d676c423959 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 11 Nov 2026 10:20:59 -0800 Subject: [PATCH 19/30] fix(payments): pay the confirmed amount on External Send withdrawals Pre-review findings on #1680: - Platform, Identity and Shielded -> Core withdrawals now withdraw the amount plus the 190-duff Core fee, which Platform takes out of the withdrawn amount, so the recipient receives exactly what was confirmed. Limits and input selection use the gross amount; a Shielded -> Core Max shows the recipient amount net of the fee. - A Core -> own identity send that only resumed an earlier unfinished top-up is now Not sent (EARLIER_TOP_UP_COMPLETED) instead of Sent. - The confirm sheet's details scroll inside a weighted region, so the Cancel/Confirm row keeps its height on short screens or large text. Co-Authored-By: Claude Opus 5.5 --- wallet/res/values/strings.xml | 1 + .../platform/sdk/ExternalSendModels.kt | 3 +- .../platform/sdk/ExternalSendService.kt | 25 ++-- .../platform/sdk/ExternalSendServiceImpl.kt | 117 ++++++++++++++---- .../platform/sdk/SdkTransparentTopUp.kt | 50 ++++++-- .../ui/payments/send/ExternalSendScreen.kt | 7 +- .../ui/payments/send/ExternalSendViewModel.kt | 27 +++- .../sdk/ExternalSendServiceImplTest.kt | 88 +++++++++++-- .../platform/sdk/SdkTransparentTopUpTest.kt | 47 +++++++ .../send/ExternalSendViewModelTest.kt | 35 ++++++ 10 files changed, 345 insertions(+), 55 deletions(-) diff --git a/wallet/res/values/strings.xml b/wallet/res/values/strings.xml index a82668d3fd..ecd54a1acf 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -583,6 +583,7 @@ 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 diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 50a7329d60..0dbd6f767e 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -360,7 +360,8 @@ enum class SendSupport { * 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]) are refused before signing. + * 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). diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt index ff36294c59..21a77e203f 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -62,6 +62,13 @@ enum class NotSentReason { */ 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 } @@ -129,9 +136,10 @@ interface ExternalSendService { /** * 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 every other pair the - * amount the recipient receives (balance minus the fee paid on top). [destinationKind] is - * [balanceKindOf] of the destination. + * 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. */ suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? @@ -156,10 +164,13 @@ interface ExternalSendService { * persisted before the SDK call ([PendingPlatformFunding]); while an earlier one is still * pending a new Core → Platform send is [NotSentReason.PAYMENT_STILL_CONFIRMING]. * - * Platform → Core: a partial withdrawal of exactly [amount] from the wallet's Platform - * addresses (the inputs are selected here, never above an address's balance); the Core fee - * of the asset unlock comes out of [amount], the Platform fee out of what the fee-paying - * address keeps. Below the withdrawal minimum it is refused before anything is signed. + * 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). */ diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index b2b6993bef..b5ddbe34e7 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -154,6 +154,19 @@ 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 @@ -161,14 +174,30 @@ private const val ASSET_UNLOCK_TX_SIZE_BYTES = 190L * 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. + * 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 + ASSET_UNLOCK_TX_SIZE_BYTES * PLATFORM_WITHDRAW_CORE_FEE_PER_BYTE * CREDITS_PER_DUFF +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 @@ -946,11 +975,14 @@ class ExternalSendServiceImpl internal constructor( * part lands on the wallet's own Platform address. 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. * - Core → Identity, 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, and the Core - * fee of the asset unlock comes out of the amount on top; Platform/Identity → Shielded - * add the shielded compute fee to the metered one.) + * 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) { @@ -965,7 +997,13 @@ class ExternalSendServiceImpl internal constructor( SendBalance.IDENTITY -> null } SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destinationKind))?.let { - FeeEstimate(Dash(ceilCreditsToDuffs(it)), exact = false) + 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 } @@ -980,7 +1018,10 @@ class ExternalSendServiceImpl internal constructor( * - 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. + * 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). * - Everything else: null (no pre-send fee figure). */ override suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? = try { @@ -999,7 +1040,12 @@ class ExternalSendServiceImpl internal constructor( if (balance == null || feeCredits == null) { null } else { - (balance - Dash(ceilCreditsToDuffs(feeCredits))).takeIf { it.isPositive } + 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, SendBalance.IDENTITY -> null @@ -1190,8 +1236,13 @@ class ExternalSendServiceImpl internal constructor( ExternalSendResult.NotSent(NotSentReason.GENERIC) } else { when (val result = this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) { - is SdkWriteResult.Broadcast -> + // 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) } } @@ -1593,10 +1644,22 @@ class ExternalSendServiceImpl internal constructor( ) } } - var result = attempt(amount) + // 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(amount, first) + 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) @@ -1636,12 +1699,13 @@ class ExternalSendServiceImpl internal constructor( } /** - * Partial withdrawal: the inputs take exactly [amountCredits] ([selectPlatformWithdrawalInputs] + * 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. [amountCredits] is the GROSS withdrawal: the Core fee of the asset unlock - * comes out of it, as for Identity → Core. Every refusal here happens before anything is - * signed (NotSent); the SDK re-checks each input against its on-chain balance before - * signing. + * 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, @@ -1649,12 +1713,8 @@ class ExternalSendServiceImpl internal constructor( destination: SendDestination.Core, amountCredits: Long ): ExternalSendResult { - if (amountCredits < PLATFORM_MIN_WITHDRAWAL_CREDITS) { - return notSent(pair, NotSentReason.GENERIC, "below the platform withdrawal minimum") - } - if (amountCredits > PLATFORM_MAX_WITHDRAWAL_CREDITS) { - return notSent(pair, NotSentReason.GENERIC, "above the platform withdrawal maximum") - } + 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) } @@ -1668,7 +1728,7 @@ class ExternalSendServiceImpl internal constructor( // 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, amountCredits, feeReserve, minInput) + 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) } } @@ -1682,10 +1742,15 @@ class ExternalSendServiceImpl internal constructor( amountCredits: Long ): ExternalSendResult { return when (destination) { - is SendDestination.Core -> + 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, amountCredits, destination.address) + 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") 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 2d2defd1c2..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,7 @@ 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 @@ -235,10 +236,15 @@ internal class DashSdkTransparentTopUpSource( * [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 lockTxIdDisplayHexOrNull: String?, + val resumedEarlier: Boolean = false ) /** @@ -406,7 +412,9 @@ class SdkTransparentTopUp internal constructor( * [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. + * 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, @@ -414,10 +422,18 @@ class SdkTransparentTopUp internal constructor( newUserIntent: Boolean ): SdkWriteResult { val lockTxId = AtomicReference(null) + val resumedEarlier = AtomicBoolean(false) return when ( - val result = topUpGuarded(identityIdBase58, amountDuffs, newUserIntent, onLockTxId = { lockTxId.set(it) }) + val result = topUpGuarded( + identityIdBase58, + amountDuffs, + newUserIntent, + onLockTxId = { lockTxId.set(it) }, + onResumedEarlier = { resumedEarlier.set(true) } + ) ) { - is SdkWriteResult.Broadcast -> SdkWriteResult.Broadcast(TopUpOutcome(result.value, lockTxId.get())) + is SdkWriteResult.Broadcast -> + SdkWriteResult.Broadcast(TopUpOutcome(result.value, lockTxId.get(), resumedEarlier.get())) is SdkWriteResult.NotBroadcast -> result is SdkWriteResult.Ambiguous -> result } @@ -427,7 +443,8 @@ class SdkTransparentTopUp internal constructor( identityIdBase58: String, amountDuffs: Long, newUserIntent: Boolean, - onLockTxId: (String) -> Unit + onLockTxId: (String) -> Unit, + onResumedEarlier: () -> Unit = {} ): SdkWriteResult { synchronized(this) { when (guard) { @@ -447,7 +464,13 @@ class SdkTransparentTopUp internal constructor( } val result = try { withContext(ioDispatcher) { - topUpTransparent(identityIdBase58, amountDuffs, newUserIntent, onLockTxId = onLockTxId) + topUpTransparent( + identityIdBase58, + amountDuffs, + newUserIntent, + onLockTxId = onLockTxId, + onResumedEarlier = onResumedEarlier + ) } } catch (t: Throwable) { // A thrown (non-cancellation) failure escaping the pipeline is, by @@ -496,7 +519,14 @@ class SdkTransparentTopUp internal constructor( * 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 = {} + 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). @@ -642,7 +672,8 @@ class SdkTransparentTopUp internal constructor( amountDuffs, newUserIntent, skipLockOutpoint = existingLock.outpointTxid to existingLock.outpointVout, - onLockTxId = onLockTxId + onLockTxId = onLockTxId, + onResumedEarlier = onResumedEarlier ) } return when (val classified = classifyBroadcastFailure(t)) { @@ -719,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/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index d199a759ff..a22843b376 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -588,12 +588,16 @@ private fun ConfirmSheet(uiState: ExternalSendUIState, confirm: ExternalSendConf 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). + // What the recipient receives (a Core Max drain: the amount minus the fee; a + // Shielded → Core Max: the amount minus the Core fee). ConfirmAmount(confirm.recipientAmount, uiState.rate, uiState.fiatCode) Spacer(modifier = Modifier.height(20.dp)) Menu { @@ -908,6 +912,7 @@ internal fun notSentMessageFor(reason: NotSentReason): Int = when (reason) { 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 } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index 40eec69e8b..4e1f05bc3f 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -30,6 +30,7 @@ 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 @@ -102,12 +103,30 @@ data class ExternalSendConfirm( val feeIncluded: Boolean get() = request.isMax && request.source == SendBalance.CORE && request.destination is SendDestination.Core - /** What the recipient receives: the amount, or for a drain the amount minus the fee (when known). */ + /** + * 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 (when known); + * for a Shielded → Core Max the amount minus the Core fee. + */ val recipientAmount: Dash - get() = if (feeIncluded) fee?.let { request.amount - it.fee } ?: request.amount else request.amount + get() = when { + feeIncluded -> fee?.let { request.amount - it.fee } ?: request.amount + coreFeeIncluded -> request.amount - Dash(WITHDRAWAL_CORE_FEE_DUFFS) + else -> request.amount + } - /** What leaves the balance: amount plus fee (null while the fee is unknown), or for a drain the amount. */ - val total: Dash? get() = if (feeIncluded) request.amount else fee?.let { request.amount + it.fee } + /** + * 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 fee?.let { recipientAmount + it.fee } } /** diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index f014d3bbc4..6f01580877 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -405,6 +405,20 @@ class ExternalSendServiceImplTest { 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( @@ -417,10 +431,27 @@ class ExternalSendServiceImplTest { val source = source() assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.SHIELDED, dest, amount, false)) assertEquals(listOf(call), source.calls) - assertEquals(listOf(amount), source.shieldedAmounts) + // 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() @@ -467,8 +498,41 @@ class ExternalSendServiceImplTest { assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.IDENTITY, dest, amount, false)) assertEquals(listOf(call), source.calls) assertArrayEquals(ownId, source.lastFromId) - assertEquals(amountCredits, source.lastCredits) + // 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 ── @@ -487,7 +551,8 @@ class ExternalSendServiceImplTest { assertEquals(listOf("platformWithdraw"), source.calls) assertEquals(core.address, source.lastCoreAddress) val inputs = requireNotNull(source.lastInputs) - assertEquals(amountCredits, inputs.sumOf { it.credits }) + // 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) }) @@ -536,15 +601,20 @@ class ExternalSendServiceImplTest { listOf(address(1, 900_000_000L)) } } - // 1 189 duffs = 1 189 000 credits < 1 000 000 + 190 × 1 000. + // 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(1_189L), false) + service(source).send(SendBalance.PLATFORM, core, Dash(PLATFORM_MAX_WITHDRAWAL_CREDITS / 1_000L), false) ) assertTrue(source.calls.isEmpty()) assertTrue(!read) - // Exactly at the minimum is sent. - assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, core, Dash(1_190L), false)) + // 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 }) } @@ -940,7 +1010,9 @@ class ExternalSendServiceImplTest { 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))) - assertEquals(FeeEstimate(Dash(2_001L), exact = false), service.estimateFee(SendBalance.SHIELDED, 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))) assertNull(service.estimateFee(SendBalance.CORE, balanceKindOf(ownIdentity))) 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 505e2ed8d7..4b8f5f88d9 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkTransparentTopUpTest.kt @@ -297,6 +297,53 @@ class SdkTransparentTopUpTest { 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() diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index a9c033c247..ba224977d3 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -27,6 +27,7 @@ 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.WITHDRAWAL_CORE_FEE_DUFFS import de.schildbach.wallet.ui.shielded.toKeypadString import de.schildbach.wallet_test.R import io.mockk.every @@ -738,6 +739,40 @@ class ExternalSendViewModelTest { 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 From 44408819927833f4520037e6c0ee473f712d35f4 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 11 Nov 2026 10:28:53 -0800 Subject: [PATCH 20/30] fix(history): show a Core -> third-party Shielded payment as a send A shield to another wallet's Orchard address seeded the same SHIELD kind as a shield into the wallet's own pool, so history showed it as an internal transfer although the funds left the wallet. The external path now seeds SHIELD_EXTERNAL: sent arrow, outgoing amount, titled "Shielded", as the Core -> Platform send is titled "Platform". Like PLATFORM, the kind is in-memory only; after a restart the funding-type fallback reads SHIELD again. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/AssetLockKindResolver.kt | 11 +++++ .../platform/sdk/CutoverUiDataService.kt | 15 ++++--- .../platform/sdk/SdkTxDetailProvider.kt | 2 +- .../sdk/ShieldedBalanceServiceImpl.kt | 22 ++++++--- .../AssetLockKindResolverWalletScopeTest.kt | 24 ++++++++++ .../platform/sdk/CutoverUiDataServiceTest.kt | 45 ++++++++++++++++++- .../sdk/ShieldedBalanceServiceTest.kt | 42 ++++++++++++++++- 7 files changed, 148 insertions(+), 13 deletions(-) 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 e7aecfbf5c..9238ffcce3 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolver.kt @@ -51,6 +51,17 @@ enum class AssetLockKind { */ 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, 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 f333772aa2..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,21 +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 (the - * Platform-address send included) 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. + * 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.PLATFORM + this == AssetLockKind.PLATFORM || this == AssetLockKind.SHIELD_EXTERNAL /** * Whether the display pass asks the asset-lock resolver about an OUTGOING @@ -484,6 +486,9 @@ internal fun assetLockTitleRes(kind: AssetLockKind): Int = when (kind) { 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. // A received AssetUnlock carries no source, so it may be a Platform address 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 01e2f1dbc8..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,7 +83,7 @@ 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 / Platform-address send). The SDK records these as INTERNAL + * 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. 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 be5734843c..29d14a7b12 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -1182,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 @@ -2481,9 +2482,13 @@ 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. The same txid is @@ -2496,7 +2501,14 @@ class ShieldedBalanceServiceImpl internal constructor( ?.takeIf { it.length == 64 } ?.let { onLockTxId(it) - seedAssetLockKind(it, AssetLockKind.SHIELD) + seedAssetLockKind( + it, + if (externalRecipientRaw43 != null) { + AssetLockKind.SHIELD_EXTERNAL + } else { + AssetLockKind.SHIELD + } + ) } } catch (t: Throwable) { if (t is CancellationException) throw t 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 98a9e5e9df..74b090d30b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolverWalletScopeTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/AssetLockKindResolverWalletScopeTest.kt @@ -141,6 +141,30 @@ class AssetLockKindResolverWalletScopeTest { 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 8afb23b380..333fbbd55b 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/CutoverUiDataServiceTest.kt @@ -271,7 +271,8 @@ class CutoverUiDataServiceTest { 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.PLATFORM to R.string.transaction_row_platform + 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) @@ -339,6 +340,48 @@ class CutoverUiDataServiceTest { 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: 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 9c11ef7720..39800691e1 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceTest.kt @@ -483,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), @@ -499,6 +500,7 @@ class ShieldedBalanceServiceTest { afterReadyCommitted = afterReadyCommitted, afterStopFallbackBump = afterStopFallbackBump, freshFundingBlocked = freshFundingBlocked, + seedAssetLockKind = seedAssetLockKind, fundingSelection = de.schildbach.wallet.payments.FundingSelectionLock() ) @@ -3717,6 +3719,44 @@ class ShieldedBalanceServiceTest { ) } + /** + * 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() From 7c232ff791dde233f14a9efd990006d620760acf Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 11 Nov 2026 14:58:12 -0800 Subject: [PATCH 21/30] fix(payments): hold the wallet-wipe barrier on External Send submissions Every non Core -> Core External Send route, and the Core -> Platform resume sweep, now submits under FundingSelectionLock.withSharedSubmission with the final bound-wallet check inside the hold, so a Reset Wallet can neither race a credit payment nor have a stale funding record written back after it cleared the store. ExternalSendExecutor now forgets its state on wallet wipe (wipe listener + generation counter), so a finished or late-completing send of the wiped wallet is never shown to, or opened by, the next wallet. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendServiceImpl.kt | 218 ++++++++++++------ .../ui/payments/send/ExternalSendExecutor.kt | 78 ++++++- .../sdk/ExternalSendServiceImplTest.kt | 178 +++++++++++++- .../send/ExternalSendViewModelTest.kt | 52 +++++ 4 files changed, 442 insertions(+), 84 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index b5ddbe34e7..2ea2fcdde8 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -21,10 +21,12 @@ 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 @@ -828,7 +830,13 @@ class ExternalSendServiceImpl internal constructor( * 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 = { _, _ -> } + 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 @@ -852,7 +860,8 @@ class ExternalSendServiceImpl internal constructor( ), network = AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id), platformFundingStore = DashPayConfigPlatformFundingStore(dashPayConfig), - seedAssetLockKind = { displayHex, kind -> assetLockKindResolver.seed(displayHex, kind) } + seedAssetLockKind = { displayHex, kind -> assetLockKindResolver.seed(displayHex, kind) }, + fundingSelection = fundingGate.selectionLock ) /** Single-flight for [send] AND [resumePendingPlatformFunding]: the one owner of the funding record. */ @@ -1232,19 +1241,21 @@ class ExternalSendServiceImpl internal constructor( is SendDestination.Core -> sendCoreToCore(pair, walletIdHex, destination, amount, isMax, coreSession) is SendDestination.Shielded -> sendCoreToShielded(pair, walletIdHex, destination, amount) is SendDestination.Identity -> { - if (!stillBound(pair, walletIdHex)) { - ExternalSendResult.NotSent(NotSentReason.GENERIC) - } else { - when (val result = this.source.coreTopUpIdentity(destination.identityIdBase58, amount.duffs)) { - // 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) + // 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) @@ -1302,6 +1313,24 @@ class ExternalSendServiceImpl internal constructor( } 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) { @@ -1319,6 +1348,7 @@ class ExternalSendServiceImpl internal constructor( } 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) @@ -1506,41 +1536,63 @@ class ExternalSendServiceImpl internal constructor( return 0 } platformResumeAttempts[record.id] = attempts + 1 - if (!stillBound("Core → Platform resume", record.walletIdHex)) return 0 - try { - this.source.resumePlatformFundingExternal(record) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - if (isAssetLockAlreadyConsumed(e)) { - platformFundingStore.clear(record.id) - log.warn("pending platform funding {}: Platform reports the lock already consumed; cleared", record.id) - } else if (isTransitionAlreadyKnownToPlatform(e)) { - // The same transition (this lock, these recipients) was submitted before; - // every resume rebuilds identical bytes, so nothing more can be done here - // and keeping the record would only block every later Core → Platform send. - platformFundingStore.clear(record.id) - log.warn( - "pending platform funding {}: Platform already has this funding transition; " + - "its outcome is Platform's — cleared", - record.id - ) - } else { - log.warn("pending platform funding {}: resume failed (attempt {}); kept", record.id, attempts + 1, e) + // 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 } - return 0 - } catch (e: LinkageError) { - log.warn("pending platform funding {}: native library unavailable; kept", record.id, e) - return 0 - } - platformFundingStore.clear(record.id) - log.info("pending platform funding {}: resumed and consumed", record.id) - return 1 + ) { 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) { + if (isAssetLockAlreadyConsumed(e)) { + platformFundingStore.clear(record.id) + log.warn("pending platform funding {}: Platform reports the lock already consumed; cleared", record.id) + } else if (isTransitionAlreadyKnownToPlatform(e)) { + // The same transition (this lock, these recipients) was submitted before; + // every resume rebuilds identical bytes, so nothing more can be done here + // and keeping the record would only block every later Core → Platform send. + platformFundingStore.clear(record.id) + log.warn( + "pending platform funding {}: Platform already has this funding transition; " + + "its outcome is Platform's — cleared", + record.id + ) + } else { + log.warn("pending platform funding {}: resume failed (attempt {}); kept", record.id, attempt, e) + } + return 0 + } catch (e: LinkageError) { + log.warn("pending platform funding {}: native library unavailable; kept", record.id, 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 it runs. So the drain is only started while the SDK's @@ -1568,6 +1620,8 @@ class ExternalSendServiceImpl internal constructor( 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) @@ -1617,11 +1671,8 @@ class ExternalSendServiceImpl internal constructor( address: String, amount: Dash ): SdkWriteResult = - if (!stillBound(pair, walletIdHex)) { - SdkWriteResult.NotBroadcast("the bound wallet changed") - } else { - this.source.shieldFromCore(walletIdHex, address, amount) - } + // 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, @@ -1631,9 +1682,9 @@ class ExternalSendServiceImpl internal constructor( isMax: Boolean ): ExternalSendResult { val identityId = (destination as? SendDestination.Identity)?.let { decodeIdentityId(it.identityIdBase58) } - suspend fun attempt(value: Dash): SdkWriteResult { - if (!stillBound(pair, walletIdHex)) return SdkWriteResult.NotBroadcast("the bound wallet changed") - return when (destination) { + 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) @@ -1771,37 +1822,72 @@ class ExternalSendServiceImpl internal constructor( /** * One [ShieldedBalanceService] write (it pins [walletIdHex] itself and classifies its own - * outcome), after the bound-wallet re-check; mapped by [mapWrite]. + * 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 { - if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) - val result = call() + 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, after the wallet re-check, classified by [classifyBroadcastFailure]. */ + /** + * 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 { - if (!stillBound(pair, walletIdHex)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) - val result: SdkWriteResult = try { - 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) + 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 diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index abd931aa4d..0c3eaa9e8b 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -17,6 +17,7 @@ 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 @@ -36,6 +37,7 @@ 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 @@ -114,6 +116,11 @@ internal class DashPayConfigInFlightMarker(private val config: DashPayConfig) : * 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. */ @@ -127,8 +134,11 @@ class ExternalSendExecutor internal constructor( constructor( service: ExternalSendService, dashPayConfig: DashPayConfig, + walletData: WalletData, applicationScope: CoroutineScope - ) : this(service, DashPayConfigInFlightMarker(dashPayConfig), applicationScope) + ) : this(service, DashPayConfigInFlightMarker(dashPayConfig), applicationScope) { + walletData.attachOnWalletWipedListener { forgetWalletState() } + } companion object { private val log = LoggerFactory.getLogger(ExternalSendExecutor::class.java) @@ -137,6 +147,13 @@ class ExternalSendExecutor internal constructor( 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) @@ -195,6 +212,11 @@ class ExternalSendExecutor internal constructor( * 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) { @@ -213,6 +235,11 @@ class ExternalSendExecutor internal constructor( 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 @@ -223,6 +250,13 @@ class ExternalSendExecutor internal constructor( log.warn("external send: could not record the in-flight marker; not sent", e) result = ExternalSendResult.NotSent(NotSentReason.GENERIC) } + if (marked && !isCurrent()) { + // A wipe ran while the marker was written, possibly after it cleared the + // marker: this one belongs to the wiped wallet. Nothing is sent. + withContext(NonCancellable) { clearMarker() } + marked = false + result = ExternalSendResult.NotSent(NotSentReason.GENERIC) + } if (marked) { result = service.send( request.source, @@ -240,14 +274,23 @@ class ExternalSendExecutor internal constructor( log.error("external send threw; outcome unknown", e) } finally { log.info("external send {} → {} finished: {}", request.source, kindOf(request.destination), kindOf(result)) - // 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() } + 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 } } - _state.value = ExternalSendExecution.Finished(request, result) } } return true @@ -271,13 +314,30 @@ class ExternalSendExecutor internal constructor( _state.compareAndSet(current, ExternalSendExecution.Idle) return } + val acknowledgedIn = generation.get() if (!_state.compareAndSet(current, ExternalSendExecution.Acknowledging)) return applicationScope.launch { - clearMarker() + // 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() diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index 6f01580877..13dcd61813 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -17,6 +17,7 @@ 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 @@ -34,6 +35,7 @@ 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 @@ -94,7 +96,7 @@ class ExternalSendServiceImplTest { var coreTopUpResult: () -> SdkWriteResult = { SdkWriteResult.Broadcast(TopUpOutcome(1L, TOP_UP_LOCK_TXID)) } var coreSend: () -> String = { "txid" } - var nativeWrite: () -> Unit = {} + var nativeWrite: suspend () -> Unit = {} val shieldedAmounts = mutableListOf() var lastCoreEmptyWallet: Boolean? = null var lastSession: WalletSession? = null @@ -321,8 +323,17 @@ class ExternalSendServiceImplTest { managed: List = listOf(ownId) ) = FakeSource(bound.toMutableList(), ownIdentity, managed) - private fun service(source: FakeSource, store: PlatformFundingStore = FakeStore()) = - ExternalSendServiceImpl(source, AddressNetwork.DASH_TESTNET, store, ioDispatcher = Dispatchers.Unconfined) + 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( @@ -956,7 +967,13 @@ class ExternalSendServiceImplTest { return SdkWriteResult.Broadcast(Unit) } } - val gated = ExternalSendServiceImpl(slow, AddressNetwork.DASH_TESTNET, FakeStore(), ioDispatcher = Dispatchers.Unconfined) + 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) @@ -1118,7 +1135,13 @@ class ExternalSendServiceImplTest { 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) + 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) } @@ -1198,7 +1221,8 @@ class ExternalSendServiceImplTest { AddressNetwork.DASH_TESTNET, FakeStore(), ioDispatcher = Dispatchers.Unconfined, - retryDelayMs = { 0L } + 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()) @@ -1223,7 +1247,8 @@ class ExternalSendServiceImplTest { AddressNetwork.DASH_TESTNET, FakeStore(), ioDispatcher = Dispatchers.Unconfined, - balancePollMs = 60_000L + balancePollMs = 60_000L, + fundingSelection = FundingSelectionLock() ) val values = mutableListOf() val job = launch { service.observeBalance(SendBalance.IDENTITY).collect { values += it } } @@ -1315,7 +1340,8 @@ class ExternalSendServiceImplTest { AddressNetwork.DASH_TESTNET, FakeStore(), ioDispatcher = Dispatchers.Unconfined, - seedAssetLockKind = { hex, kind -> seeds += hex to kind } + 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. @@ -1332,7 +1358,8 @@ class ExternalSendServiceImplTest { AddressNetwork.DASH_TESTNET, store, ioDispatcher = Dispatchers.Unconfined, - seedAssetLockKind = { _, _ -> throw IllegalStateException("seed") } + seedAssetLockKind = { _, _ -> throw IllegalStateException("seed") }, + fundingSelection = FundingSelectionLock() ) assertEquals(ExternalSendResult.Sent(LOCK_TXID), service.send(SendBalance.CORE, platform, amount, false)) assertNull(store.record) @@ -1640,6 +1667,139 @@ class ExternalSendServiceImplTest { 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 otherIdentity, + 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) diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index ba224977d3..8d857a8a3a 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -39,6 +39,7 @@ 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 @@ -869,6 +870,57 @@ class ExternalSendViewModelTest { 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 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) From e7bda1e26aa44addcc1e146693be1d83222d1e22 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 11 Nov 2026 17:16:10 -0800 Subject: [PATCH 22/30] build: pin the Dash SDK to 5.1.0-int38 int38 carries int37's External Send bindings plus v5.1-dev, including platform#5556 (uncertain submission outcomes surface as typed *Unconfirmed errors) and #5823 (proven transition outcomes; no Kotlin binding yet). No wallet API changes were needed. Co-Authored-By: Claude Opus 5.5 --- build.gradle | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/build.gradle b/build.gradle index e7d5913c69..f70ecac5ab 100644 --- a/build.gradle +++ b/build.gradle @@ -11,15 +11,16 @@ buildscript { // 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-int37: HashEngineering/platform - // integration/5.1.0-int37 @ 45d7bcb1b2 = int36 (fund_from_asset_lock_external, - // used by the Core → third-party Platform address send) plus three bindings the - // Advanced-mode External Send uses: the partial-amount Platform-address withdrawal - // (ManagedPlatformWallet.withdrawCredits with explicit WithdrawalInputs, Platform → - // Core), and the third-party shields PlatformWalletManager.shieldedShieldToRecipient - // (Type 15, Platform → Shielded) and .shieldedShieldFromIdentityToRecipient - // (Type 21, Identity → Shielded). - dashSdkVersion = '5.1.0-int37-20261108.041023-1' + // can't change what this commit builds. 5.1.0-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-int38-20261111.213211-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; From 91ff74a306d7af0d04bbb7a6e1fae237112bb64e Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Wed, 11 Nov 2026 17:16:12 -0800 Subject: [PATCH 23/30] fix(payments): handle int38's unconfirmed outcomes and unproven consumed locks - Classify every typed *Unconfirmed SDK error (StateTransitionResultUnconfirmed, TransactionBroadcastUnconfirmed, shielded/masternode variants) as "may have gone through", ahead of any message match, in the credit writes, the shielded invite claim and the top-up recovery. - Core -> Platform resume: the "Object already exists" match is gone (int38 waits for the proved result itself). An unconfirmed outcome keeps the pending record for the next sweep. - An AssetLockAlreadyConsumed answer is not proof, so, as the iOS wallet does, the record is moved to a durable "completion unconfirmed" set: it is no longer resumed automatically and no longer blocks new Core -> Platform sends, but is kept for a later manual retry. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalPlatformFunding.kt | 113 +++++++---- .../platform/sdk/ExternalSendService.kt | 8 +- .../platform/sdk/ExternalSendServiceImpl.kt | 103 +++++++--- .../service/platform/sdk/SdkDashPayWrites.kt | 33 ++++ .../sdk/SdkShieldedUsernameCreation.kt | 3 + .../platform/sdk/SdkTopUpRecoveryService.kt | 3 + .../wallet/ui/dashpay/utils/DashPayConfig.kt | 10 + .../platform/sdk/ExternalSendModelsTest.kt | 31 +++ .../sdk/ExternalSendServiceImplTest.kt | 183 +++++++++++++++--- .../platform/sdk/SdkDashPayWritesTest.kt | 33 ++++ .../sdk/SdkShieldedUsernameCreationTest.kt | 8 + .../sdk/SdkTopUpRecoveryServiceTest.kt | 16 ++ 12 files changed, 446 insertions(+), 98 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt index 51f7ac73de..36809a90e2 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalPlatformFunding.kt @@ -21,7 +21,6 @@ import de.schildbach.wallet.ui.dashpay.utils.DashPayConfig import de.schildbach.wallet.ui.shielded.assetLockMaxFeeReserve import kotlinx.coroutines.runBlocking import org.bitcoinj.core.Utils -import org.dashfoundation.dashsdk.errors.DashSdkError // Advanced-mode External Send, Core → third-party Platform address (MO-1121): // the persisted recipient record the SDK's resume contract requires, and the @@ -66,36 +65,6 @@ internal const val EXTERNAL_FUNDING_PLATFORM_ACCOUNT_INDEX = 0 */ internal const val ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP = 4 -/** - * Whether an SDK funding call was refused because Platform already knows this exact state - * transition: rs-sdk `Error::AlreadyExists`, which the JNI surfaces as a Generic error - * reading "Object already exists: …" — Tenderdash's "tx already exists in cache", or - * DAPI's "state transition already in mempool" / "already in chain". - * - * On a resume this is terminal for the record: the transition is signed over the lock and - * exactly the persisted recipients and nothing else varies (no fee bump on resume), so every - * resume rebuilds the same bytes and Tenderdash refuses them again for as long as its cache - * holds the first submission. The SDK does not wait for that submission's result after this - * error (rs-sdk `broadcast_and_wait_for_affected_state_with_metadata` returns on the - * broadcast error), so the wallet never learns the outcome from the call. - * - * Message-matched, down the cause chain because the JNI wraps it, until the SDK types it; - * only errors raised by the SDK ([DashSdkError]) qualify. - */ -internal fun isTransitionAlreadyKnownToPlatform(t: Throwable): Boolean { - if (t !is DashSdkError) return false - var cause: Throwable? = t - var hops = 0 - while (cause != null && hops++ < 8) { - if (cause.message?.contains(SDK_ALREADY_EXISTS_PREFIX) == true) return true - cause = cause.cause - } - return false -} - -/** rs-sdk `Error::AlreadyExists`'s display prefix. */ -private const val SDK_ALREADY_EXISTS_PREFIX = "Object already exists:" - /** 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) @@ -121,6 +90,13 @@ internal fun coreToPlatformMaxDuffs(eligibleDuffs: Long, spendableUtxoCount: Int * 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( @@ -131,7 +107,8 @@ internal class PendingPlatformFunding( val explicitCredits: Long, val remainder: PlatformAddressBytes, /** `:`, the SDK `asset_locks` key; null until the lock is built. */ - val outPointHex: String? + val outPointHex: String?, + val completionUnconfirmed: Boolean = false ) { init { require(id.isNotEmpty() && FIELD_SEPARATOR !in id) { "malformed id" } @@ -142,6 +119,7 @@ internal class PendingPlatformFunding( 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. */ @@ -158,6 +136,11 @@ internal class PendingPlatformFunding( 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 && @@ -168,9 +151,14 @@ internal class PendingPlatformFunding( explicitCredits == other.explicitCredits && remainder.addressType == other.remainder.addressType && remainder.hash.contentEquals(other.remainder.hash) && - outPointHex == other.outPointHex + outPointHex == other.outPointHex && + completionUnconfirmed == other.completionUnconfirmed - fun encode(): String = listOf( + /** + * 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(), @@ -180,24 +168,31 @@ internal class PendingPlatformFunding( explicitCredits.toString(), remainder.addressType.toString(), Utils.HEX.encode(remainder.hash), - outPointHex.orEmpty() + outPointHex.orEmpty(), + COMPLETION_UNCONFIRMED.takeIf { completionUnconfirmed } ).joinToString(FIELD_SEPARATOR) override fun toString(): String = - "PendingPlatformFunding(id=$id, outPoint=${if (outPointHex == null) "none" else "recorded"}, )" + "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. + * [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) - check(fields.size == FIELD_COUNT && fields[0] == FORMAT_VERSION) { "malformed pending platform funding" } + 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], @@ -206,7 +201,8 @@ internal class PendingPlatformFunding( 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 } + outPointHex = fields[9].ifEmpty { null }, + completionUnconfirmed = marked ) } catch (e: IllegalArgumentException) { // NumberFormatException included; the message carries no field value. @@ -240,9 +236,26 @@ internal interface PlatformFundingStore { /** 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]. */ +/** + * [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) @@ -268,4 +281,24 @@ internal class DashPayConfigPlatformFundingStore(private val config: DashPayConf } 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/ExternalSendService.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt index 21a77e203f..fc14743145 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -162,7 +162,9 @@ interface ExternalSendService { * 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]. + * 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 @@ -186,7 +188,9 @@ interface ExternalSendService { * 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, earlier, or as Platform reports). + * 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). */ diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 2ea2fcdde8..6616df0a85 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -481,9 +481,10 @@ internal interface ExternalSendSource { /** * Whether [walletIdHex] has any Platform-address funding lock - * ([ASSET_LOCK_FUNDING_TYPE_ADDRESS_TOPUP]) that is not Consumed; throws when unreadable. + * ([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): Boolean + suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String, excludingOutPoints: Set): Boolean } /** Production [ExternalSendSource]. */ @@ -777,11 +778,13 @@ internal class DashSdkExternalSendSource( ?.statusRaw } - override suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String): Boolean = - database().assetLockDao() + 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 } + .any { it.statusRaw != ASSET_LOCK_STATUS_CONSUMED && it.outPointHex.lowercase() !in excluded } + } private companion object { private val log = LoggerFactory.getLogger(DashSdkExternalSendSource::class.java) @@ -1466,16 +1469,26 @@ class ExternalSendServiceImpl internal constructor( * 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. + * 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 on success, when - * Platform answers already consumed, or when Platform already has the identical - * transition ([isTransitionAlreadyKnownToPlatform]: submitted before a process death, - * so no resume can submit anything new). Clearing never pays twice: Platform consumes - * a lock's outpoint once (drive-abci `verify_asset_lock_is_not_spent_and_has_enough_balance`), - * and a later send builds a new lock. + * [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 { @@ -1493,6 +1506,11 @@ class ExternalSendServiceImpl internal constructor( 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() } @@ -1502,8 +1520,18 @@ class ExternalSendServiceImpl internal constructor( } val outPointHex = record.outPointHex if (outPointHex == null) { + 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, e) + return 0 + } val unconsumed = readOrNull("address funding locks") { - this.source.hasUnconsumedAddressFundingLocks(record.walletIdHex) + 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) @@ -1567,19 +1595,46 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - if (isAssetLockAlreadyConsumed(e)) { - platformFundingStore.clear(record.id) - log.warn("pending platform funding {}: Platform reports the lock already consumed; cleared", record.id) - } else if (isTransitionAlreadyKnownToPlatform(e)) { - // The same transition (this lock, these recipients) was submitted before; - // every resume rebuilds identical bytes, so nothing more can be done here - // and keeping the record would only block every later Core → Platform send. - platformFundingStore.clear(record.id) + // 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 {}: Platform already has this funding transition; " + - "its outcome is Platform's — cleared", - record.id + "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, + e + ) + } } else { log.warn("pending platform funding {}: resume failed (attempt {}); kept", record.id, attempt, e) } 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 ded85f2ff3..3bf5d549f4 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkDashPayWrites.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/SdkDashPayWrites.kt @@ -154,7 +154,40 @@ internal const val REASON_PRE_BROADCAST_ASSET_LOCK_SIGNING = 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 || 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/ui/dashpay/utils/DashPayConfig.kt b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt index f68df92e72..0bc4a17b3e 100644 --- a/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt +++ b/wallet/src/de/schildbach/wallet/ui/dashpay/utils/DashPayConfig.kt @@ -310,6 +310,16 @@ open class DashPayConfig @Inject constructor( */ 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/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt index f0f134532d..4d8dbfc879 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -392,6 +392,37 @@ class ExternalSendModelsTest { 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() diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index 13dcd61813..cdd79351c4 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -260,6 +260,7 @@ class ExternalSendServiceImplTest { var resume: (PendingPlatformFunding) -> Unit = {} var lockStatus: () -> Int? = { 2 } var unconsumedLocks: () -> Boolean = { false } + var lastExcludedOutPoints: Set? = null val funded = mutableListOf() val resumed = mutableListOf() @@ -285,7 +286,10 @@ class ExternalSendServiceImplTest { } override suspend fun trackedAssetLockStatus(walletIdHex: String, outPointHex: String): Int? = lockStatus() - override suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String): Boolean = unconsumedLocks() + override suspend fun hasUnconsumedAddressFundingLocks(walletIdHex: String, excludingOutPoints: Set): Boolean { + lastExcludedOutPoints = excludingOutPoints + return unconsumedLocks() + } } private class FakeStore : PlatformFundingStore { @@ -315,6 +319,25 @@ class ExternalSendServiceImplTest { 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( @@ -1543,57 +1566,153 @@ class ExternalSendServiceImplTest { } @Test - fun resume_consumedLock_orAlreadyConsumedAnswer_clearsTheRecord() = runBlocking { - var source = source().apply { lockStatus = { ASSET_LOCK_STATUS_CONSUMED } } - var store = FakeStore().apply { record = pendingRecord() } + 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) + } - source = source().apply { + @Test + fun resume_alreadyConsumedAnswer_keepsTheRecordAsCompletionUnconfirmed_neverResumedAgain_andStopsBlocking() = runBlocking { + val source = source().apply { resume = { throw DashSdkError.PlatformWallet.AssetLockAlreadyConsumed("already consumed") } } - store = FakeStore().apply { record = pendingRecord() } - assertEquals(0, service(source, store).resumePendingPlatformFunding()) + 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_transitionAlreadyKnownToPlatform_clearsTheRecord_andUnblocksTheNextSend() = runBlocking { - // Observed on-device after a process death mid-send: every resume rebuilt the same - // transition and Tenderdash refused it, so the record blocked all later sends. - val alreadyKnown = DashSdkError.PlatformWallet.Generic( - 1, - "SDK error: Object already exists: tx already exists in cache", - RuntimeException("SDK error: Object already exists: tx already exists in cache") - ) - val source = source().apply { resume = { throw alreadyKnown } } - val store = FakeStore().apply { record = pendingRecord() } + 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) - // The next Core → Platform send is no longer refused as "still confirming". - source.resume = { throw AssertionError("nothing left to resume") } - assertEquals(ExternalSendResult.Sent(LOCK_TXID), service.send(SendBalance.CORE, platform, amount, false)) - assertEquals(1, source.funded.size) + // 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 transitionAlreadyKnown_matchesOnlyTheSdkAlreadyExistsShape() { - val wrapped = DashSdkError.PlatformWallet.Generic( - 1, - "resume failed", - RuntimeException("SDK error: Object already exists: state transition already in chain") - ) - assertTrue(isTransitionAlreadyKnownToPlatform(wrapped)) - assertTrue( - !isTransitionAlreadyKnownToPlatform(RuntimeException("SDK error: Object already exists: tx already exists in cache")) + 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")) ) - assertTrue(!isTransitionAlreadyKnownToPlatform(DashSdkError.PlatformWallet.Generic(1, "Wallet already exists: x"))) - assertTrue(!isTransitionAlreadyKnownToPlatform(DashSdkError.PlatformWallet.Generic(1, "platform 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 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 8c06491d45..2fab40cfb4 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkDashPayWritesTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/SdkDashPayWritesTest.kt @@ -583,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) From d4a6e580cf7b11f5087ec21c8faf7c8b10abef8e Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Thu, 12 Nov 2026 17:00:35 -0800 Subject: [PATCH 24/30] fix(payments): limit Platform -> Identity to own identity; keep SDK messages out of logs - The SDK's identityCredits.topUpFromAddresses only finds identities the wallet manages, so a Platform -> someone else's identity send failed on device with "Identity not found". External Send now offers Platform -> Identity only for the wallet's own (SDK-managed) identity, like Core -> Identity, and the service refuses the rest before building. Someone else's identity needs a Kotlin binding of platform#5860. - That failure was logged with the SDK message, which named the recipient identity. External Send now logs only error class names (and a native code) via safeErrorSummary, never an exception message or stack trace. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendModels.kt | 19 ++++- .../platform/sdk/ExternalSendServiceImpl.kt | 84 ++++++++++++------- .../ui/payments/send/ExternalSendExecutor.kt | 11 +-- .../platform/sdk/ExternalSendModelsTest.kt | 8 +- .../sdk/ExternalSendServiceImplTest.kt | 53 ++++++++++-- .../send/ExternalSendViewModelTest.kt | 11 +++ 6 files changed, 140 insertions(+), 46 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 0dbd6f767e..00fa8ce753 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -331,7 +331,10 @@ enum class SendSupport { /** 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. */ + /** + * A Core- or Platform-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. */ @@ -346,7 +349,7 @@ enum class SendSupport { * |---|---|---|---|---| * | Core | yes | yes | yes, P2PKH only (1) | own identity only (2) | * | Shielded | yes | yes | yes | yes | - * | Platform | yes (3) | yes (4) | yes | yes | + * | Platform | yes (3) | yes (4) | yes | own identity only (6) | * | Identity | yes | yes (5) | yes | yes, not to itself | * * 1. `ManagedPlatformWallet.fundFromAssetLockExternal`: the payee gets the explicit @@ -366,6 +369,12 @@ enum class SendSupport { * selects the Platform-address inputs). * 5. `shieldedShieldFromIdentityToRecipient` (Type 21 to a third party's Orchard address). * + * 6. `identityCredits.topUpFromAddresses` only finds identities this wallet + * manages (someone else's identity fails `NotFound`). A top-up of someone else's + * identity needs a Kotlin binding of platform#5860 (top-up of an unmanaged identity + * from Platform addresses). [destinationIsOwnIdentity] null (could not tell) fails + * closed, as in 2. + * * 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. */ @@ -385,7 +394,11 @@ fun externalSendSupport( if (destinationIsOwnIdentity == true) SendSupport.SUPPORTED else SendSupport.NEEDS_OWN_IDENTITY } SendBalance.SHIELDED -> SendSupport.SUPPORTED - SendBalance.PLATFORM -> SendSupport.SUPPORTED + SendBalance.PLATFORM -> when (destination) { + is SendDestination.Core, is SendDestination.Shielded, is SendDestination.Platform -> SendSupport.SUPPORTED + is SendDestination.Identity -> + if (destinationIsOwnIdentity == true) SendSupport.SUPPORTED else SendSupport.NEEDS_OWN_IDENTITY + } 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. diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 6616df0a85..c738fd217e 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -56,6 +56,7 @@ 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 @@ -66,6 +67,25 @@ 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 @@ -299,7 +319,7 @@ 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), cause) + 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") @@ -904,7 +924,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: balance read failed; unknown", e) + log.warn("external send: balance read failed; unknown ({})", safeErrorSummary(e)) null } emit(value) @@ -921,7 +941,7 @@ class ExternalSendServiceImpl internal constructor( override fun currentWalletIdOrNull(): String? = try { source.currentBoundWalletIdOrNull() } catch (e: Exception) { - log.warn("external send: bound wallet unreadable", e) + log.warn("external send: bound wallet unreadable ({})", safeErrorSummary(e)) null } @@ -935,7 +955,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: managed-identity lookup failed; unknown", e) + log.warn("external send: managed-identity lookup failed; unknown ({})", safeErrorSummary(e)) null } } @@ -948,7 +968,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: identity lookup failed; unknown", e) + log.warn("external send: identity lookup failed; unknown ({})", safeErrorSummary(e)) return IdentityResolution.Unknown } if (!exists) return IdentityResolution.NotFound @@ -958,7 +978,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: username lookup failed; showing the identity without a name", e) + log.warn("external send: username lookup failed; showing the identity without a name ({})", safeErrorSummary(e)) null } return IdentityResolution.Found(username) @@ -970,7 +990,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: fee estimate failed; unknown", e) + log.warn("external send: fee estimate failed; unknown ({})", safeErrorSummary(e)) null } @@ -1065,7 +1085,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: max sendable unreadable", e) + log.warn("external send: max sendable unreadable ({})", safeErrorSummary(e)) null } @@ -1137,7 +1157,7 @@ class ExternalSendServiceImpl internal constructor( } 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), e) + log.error("external send {} → {} failed unclassified; outcome unknown ({})", source, kindOf(destination), safeErrorSummary(e)) ExternalSendResult.MayHaveGoneThrough } finally { inFlight.set(false) @@ -1177,7 +1197,9 @@ class ExternalSendServiceImpl internal constructor( ?: return notSent(pair, NotSentReason.GENERIC, "identity record unreadable") val ownIdentityId = ownIdentity.getOrNull() val destinationIsOwnIdentity: Boolean? = when (destination) { - is SendDestination.Identity -> if (source == SendBalance.CORE) { + // A Core or Platform top-up needs an identity the SDK wallet manages; 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) } @@ -1300,7 +1322,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send {}: pending platform funding unreadable; not sent", pair, e) + log.warn("external send {}: pending platform funding unreadable; not sent ({})", pair, safeErrorSummary(e)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) } if (pending != null) { @@ -1339,7 +1361,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send {}: could not persist the recipients; not sent", pair, e) + log.warn("external send {}: could not persist the recipients; not sent ({})", pair, safeErrorSummary(e)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) } @@ -1358,7 +1380,7 @@ class ExternalSendServiceImpl internal constructor( try { platformFundingStore.writeBlocking(record.withOutPoint(outPointHex)) } catch (e: Exception) { - log.error("external send {}: could not record the lock outpoint (retried after the call)", pair, e) + log.error("external send {}: could not record the lock outpoint, retried after the call ({})", pair, safeErrorSummary(e)) } seedPlatformLockKind(pair, outPointHex) } @@ -1404,10 +1426,10 @@ class ExternalSendServiceImpl internal constructor( // 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", + "external send {}: lock built, funding not confirmed ({}: {}) — may have gone through; resumed automatically", pair, outcome.javaClass.simpleName, - (outcome as? SdkWriteResult.NotBroadcast)?.cause ?: (outcome as? SdkWriteResult.Ambiguous)?.cause + safeErrorSummary((outcome as? SdkWriteResult.NotBroadcast)?.cause ?: (outcome as? SdkWriteResult.Ambiguous)?.cause) ) return ExternalSendResult.MayHaveGoneThrough } @@ -1424,7 +1446,7 @@ class ExternalSendServiceImpl internal constructor( .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, e) + log.warn("external send {}: lock kind seed failed; the row may momentarily read Internal ({})", pair, safeErrorSummary(e)) } } @@ -1438,7 +1460,7 @@ class ExternalSendServiceImpl internal constructor( } 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, e) + log.error("external send {}: could not record the lock outpoint; the lock cannot be resumed automatically ({})", pair, safeErrorSummary(e)) } } @@ -1449,7 +1471,7 @@ class ExternalSendServiceImpl internal constructor( 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, e) + log.warn("external send {}: could not clear the pending platform funding ({})", pair, safeErrorSummary(e)) } } @@ -1460,7 +1482,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("pending platform funding sweep failed; retried on the next trigger", e) + log.warn("pending platform funding sweep failed; retried on the next trigger ({})", safeErrorSummary(e)) 0 } @@ -1496,7 +1518,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("pending platform funding unreadable or malformed; kept, not resumed", e) + log.warn("pending platform funding unreadable or malformed; kept, not resumed ({})", safeErrorSummary(e)) return 0 } ?: return 0 if (!inFlight.compareAndSet(false, true)) { @@ -1527,7 +1549,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("pending platform funding {}: completion-unconfirmed records unreadable; kept", record.id, e) + log.warn("pending platform funding {}: completion-unconfirmed records unreadable; kept ({})", record.id, safeErrorSummary(e)) return 0 } val unconsumed = readOrNull("address funding locks") { @@ -1546,7 +1568,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("pending platform funding {}: lock status unreadable; kept", record.id, e) + log.warn("pending platform funding {}: lock status unreadable; kept ({})", record.id, safeErrorSummary(e)) return 0 } if (status == null) { @@ -1630,17 +1652,17 @@ class ExternalSendServiceImpl internal constructor( } catch (e: Exception) { log.warn( "pending platform funding {}: Platform reports the lock already consumed, unproven; " + - "could not mark it, kept pending", + "could not mark it, kept pending ({})", record.id, - e + safeErrorSummary(e) ) } } else { - log.warn("pending platform funding {}: resume failed (attempt {}); kept", record.id, attempt, e) + 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, e) + log.warn("pending platform funding {}: native library unavailable; kept ({})", record.id, safeErrorSummary(e)) return 0 } platformFundingStore.clear(record.id) @@ -1668,7 +1690,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send {}: max sendable unreadable before the drain; not sent", pair, e) + log.warn("external send {}: max sendable unreadable before the drain; not sent ({})", pair, safeErrorSummary(e)) return ExternalSendResult.NotSent(NotSentReason.GENERIC) } if (maxNow != amount.duffs) { @@ -1685,7 +1707,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - classifyCoreSendThrowable(e).also { log.warn("external send {}: {}", pair, it, e) } + classifyCoreSendThrowable(e).also { log.warn("external send {}: {} ({})", pair, it, safeErrorSummary(e)) } } } @@ -1956,11 +1978,11 @@ class ExternalSendServiceImpl internal constructor( is SdkWriteResult.Broadcast -> ExternalSendResult.Sent(null) is SdkWriteResult.NotBroadcast -> { val reason = notSentReasonFor(result) - log.warn("external send {}: not sent ({})", pair, reason, result.cause) + 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, result.cause) + log.error("external send {}: outcome unconfirmed — may have gone through; do NOT retry ({})", pair, safeErrorSummary(result.cause)) ExternalSendResult.MayHaveGoneThrough } } @@ -1985,7 +2007,7 @@ class ExternalSendServiceImpl internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: {} unreadable", what, e) + log.warn("external send: {} unreadable ({})", what, safeErrorSummary(e)) null } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index 0c3eaa9e8b..f251aef289 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -23,6 +23,7 @@ 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 @@ -164,7 +165,7 @@ class ExternalSendExecutor internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send in-flight marker unreadable; assuming a send may have gone through", e) + 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") @@ -198,7 +199,7 @@ class ExternalSendExecutor internal constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - log.warn("external send: pending Core → Platform sweep failed", e) + 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") @@ -247,7 +248,7 @@ class ExternalSendExecutor internal constructor( 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", e) + log.warn("external send: could not record the in-flight marker; not sent ({})", safeErrorSummary(e)) result = ExternalSendResult.NotSent(NotSentReason.GENERIC) } if (marked && !isCurrent()) { @@ -271,7 +272,7 @@ class ExternalSendExecutor internal constructor( // is unknown and stays "may have gone through". throw e } catch (e: Exception) { - log.error("external send threw; outcome unknown", e) + log.error("external send threw; outcome unknown ({})", safeErrorSummary(e)) } finally { log.info("external send {} → {} finished: {}", request.source, kindOf(request.destination), kindOf(result)) if (!isCurrent()) { @@ -345,7 +346,7 @@ class ExternalSendExecutor internal constructor( 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", e) + log.warn("external send: could not clear the in-flight marker ({})", safeErrorSummary(e)) } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt index 4d8dbfc879..ad9d423931 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -271,8 +271,14 @@ class ExternalSendModelsTest { // The Platform source needs no identity. assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, core, hasIdentity = false)) assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, platform)) - assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity)) + // topUpFromAddresses only finds a managed identity: someone else's needs a Kotlin + // binding of platform#5860. assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, identity, own = true)) + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.PLATFORM, identity, own = false)) + // Could not tell: fail closed. + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.PLATFORM, identity, own = null)) + // No identity at all: nothing is managed. + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.PLATFORM, identity, hasIdentity = false)) } @Test diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index cdd79351c4..49a2b830e1 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -46,6 +46,7 @@ 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.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -509,9 +510,9 @@ class ExternalSendServiceImplTest { listOf(FundingInput(0, ByteArray(20) { 1 }, 60_000_000L), FundingInput(0, ByteArray(20) { 2 }, 70_000_000L)) } } - assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, otherIdentity, amount, false)) + assertEquals(ExternalSendResult.Sent(null), service(source).send(SendBalance.PLATFORM, ownIdentity, amount, false)) assertEquals(amountCredits, source.lastInputs?.sumOf { it.credits }) - assertArrayEquals(otherId, source.lastToId) + assertArrayEquals(ownId, source.lastToId) } @Test @@ -519,7 +520,7 @@ class ExternalSendServiceImplTest { val source = source().apply { platformBalances = { listOf(FundingInput(0, ByteArray(20) { 1 }, 1_000L)) } } assertEquals( ExternalSendResult.NotSent(NotSentReason.INSUFFICIENT_FUNDS), - service(source).send(SendBalance.PLATFORM, otherIdentity, amount, false) + service(source).send(SendBalance.PLATFORM, ownIdentity, amount, false) ) assertTrue(source.calls.isEmpty()) } @@ -891,6 +892,19 @@ class ExternalSendServiceImplTest { 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 @@ -900,7 +914,10 @@ class ExternalSendServiceImplTest { SendBalance.CORE to platformP2sh, SendBalance.IDENTITY to ownIdentity, // Someone else's identity from Core: the resume gate cannot protect it. - SendBalance.CORE to otherIdentity + SendBalance.CORE to otherIdentity, + // Someone else's identity from Platform: topUpFromAddresses only finds a managed + // identity (needs a Kotlin binding of platform#5860). + SendBalance.PLATFORM to otherIdentity ) for ((from, to) in pairs) { val source = source() @@ -913,6 +930,30 @@ class ExternalSendServiceImplTest { } } + @Test + fun platformToIdentity_needsAManagedIdentity_withNoSeamCall() = runBlocking { + // A wallet with no identity manages none: any identity destination is refused. + val noIdentity = source(ownIdentity = null, managed = emptyList()).apply { + platformBalances = { listOf(address(1, 900_000_000L)) } + } + for (to in listOf(ownIdentity, otherIdentity)) { + assertEquals( + "$to", + ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), + service(noIdentity).send(SendBalance.PLATFORM, to, amount, false) + ) + } + assertTrue(noIdentity.calls.isEmpty()) + + // The user's identity record, but not one the SDK wallet manages. + val unmanaged = source(managed = emptyList()).apply { platformBalances = { listOf(address(1, 900_000_000L)) } } + assertEquals( + ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), + service(unmanaged).send(SendBalance.PLATFORM, ownIdentity, amount, false) + ) + assertTrue(unmanaged.calls.isEmpty()) + } + @Test fun identitySource_withoutAnIdentity_isNotSupported() = runBlocking { val source = source(ownIdentity = null) @@ -1201,7 +1242,7 @@ class ExternalSendServiceImplTest { SendBalance.CORE to platform, SendBalance.SHIELDED to core, SendBalance.PLATFORM to platform, - SendBalance.PLATFORM to otherIdentity, + SendBalance.PLATFORM to ownIdentity, SendBalance.IDENTITY to core ) for ((from, to) in pairs) { @@ -1799,7 +1840,7 @@ class ExternalSendServiceImplTest { SendBalance.SHIELDED to platform, SendBalance.SHIELDED to otherIdentity, SendBalance.PLATFORM to platform, - SendBalance.PLATFORM to otherIdentity, + SendBalance.PLATFORM to ownIdentity, SendBalance.PLATFORM to core, SendBalance.PLATFORM to shielded, SendBalance.IDENTITY to core, diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 8d857a8a3a..26aec4c6ef 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -27,6 +27,7 @@ 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.shielded.toKeypadString import de.schildbach.wallet_test.R @@ -268,10 +269,20 @@ class ExternalSendViewModelTest { service.ownIdentity = false val other = buildViewModel().apply { goToAmount(identityId) } assertEquals(SendBalance.SHIELDED, other.uiState.value.source) + // Platform tops up only a managed identity (someone else's needs platform#5860). + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, other.uiState.value.supportOf(SendBalance.PLATFORM)) + other.onSourceSelected(SendBalance.PLATFORM) + assertEquals(SendBalance.SHIELDED, 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: fails closed. + service.ownIdentity = null + val unknown = buildViewModel().apply { goToAmount(identityId) } + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, unknown.uiState.value.supportOf(SendBalance.PLATFORM)) } @Test From 378630bcb1d5b67034dcdc6e26445039dbc29659 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 13 Nov 2026 08:29:49 -0800 Subject: [PATCH 25/30] feat(payments): pin the Dash SDK to 5.1.0-int39; Platform -> any identity int39 adds IdentityCredits.topUpExternalIdentityFromAddresses (a Kotlin binding of dashpay/platform#5860). Platform -> Identity now uses topUpFromAddresses for an identity the SDK wallet manages and the external top-up for any other; an unreadable managed set is NotSent. A missing identity fails DashSdkError.NotFound before signing, read as NotSent. Core -> someone else's identity stays unsupported. Co-Authored-By: Claude Opus 5.5 --- build.gradle | 6 +- .../platform/sdk/ExternalSendModels.kt | 24 ++-- .../platform/sdk/ExternalSendServiceImpl.kt | 54 ++++++++- .../platform/sdk/ExternalSendModelsTest.kt | 13 +-- .../sdk/ExternalSendServiceImplTest.kt | 105 +++++++++++++----- .../send/ExternalSendViewModelTest.kt | 15 ++- 6 files changed, 154 insertions(+), 63 deletions(-) diff --git a/build.gradle b/build.gradle index f70ecac5ab..19f532634a 100644 --- a/build.gradle +++ b/build.gradle @@ -11,7 +11,9 @@ buildscript { // 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-int38: HashEngineering/platform + // 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 @@ -20,7 +22,7 @@ buildscript { // 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-int38-20261111.213211-1' + 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/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 00fa8ce753..8d8ea8863b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -331,10 +331,7 @@ enum class SendSupport { /** The SDK (or the wallet) cannot do this pair yet. */ NOT_SUPPORTED_YET, - /** - * A Core- or Platform-funded identity top-up is only possible for an identity this - * wallet manages. - */ + /** 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. */ @@ -349,7 +346,7 @@ enum class SendSupport { * |---|---|---|---|---| * | Core | yes | yes | yes, P2PKH only (1) | own identity only (2) | * | Shielded | yes | yes | yes | yes | - * | Platform | yes (3) | yes (4) | yes | own identity only (6) | + * | 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 @@ -369,11 +366,12 @@ enum class SendSupport { * selects the Platform-address inputs). * 5. `shieldedShieldFromIdentityToRecipient` (Type 21 to a third party's Orchard address). * - * 6. `identityCredits.topUpFromAddresses` only finds identities this wallet - * manages (someone else's identity fails `NotFound`). A top-up of someone else's - * identity needs a Kotlin binding of platform#5860 (top-up of an unmanaged identity - * from Platform addresses). [destinationIsOwnIdentity] null (could not tell) fails - * closed, as in 2. + * 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. @@ -394,11 +392,7 @@ fun externalSendSupport( if (destinationIsOwnIdentity == true) SendSupport.SUPPORTED else SendSupport.NEEDS_OWN_IDENTITY } SendBalance.SHIELDED -> SendSupport.SUPPORTED - SendBalance.PLATFORM -> when (destination) { - is SendDestination.Core, is SendDestination.Shielded, is SendDestination.Platform -> SendSupport.SUPPORTED - is SendDestination.Identity -> - if (destinationIsOwnIdentity == true) SendSupport.SUPPORTED else SendSupport.NEEDS_OWN_IDENTITY - } + 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. diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index c738fd217e..bfb40cf80b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -410,7 +410,15 @@ internal interface ExternalSendSource { ): 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, @@ -674,6 +682,20 @@ internal class DashSdkExternalSendSource( ) } + 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( @@ -1197,8 +1219,9 @@ class ExternalSendServiceImpl internal constructor( ?: return notSent(pair, NotSentReason.GENERIC, "identity record unreadable") val ownIdentityId = ownIdentity.getOrNull() val destinationIsOwnIdentity: Boolean? = when (destination) { - // A Core or Platform top-up needs an identity the SDK wallet manages; an identity - // transfer only needs to tell the user's own identity (no self-transfer). + // 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") { @@ -1216,6 +1239,15 @@ class ExternalSendServiceImpl internal constructor( 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) { @@ -1241,7 +1273,8 @@ class ExternalSendServiceImpl internal constructor( 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) + SendBalance.PLATFORM -> + sendFromPlatform(pair, walletIdHex, destination, amount, amountCredits, platformTopUpOfManaged) SendBalance.IDENTITY -> sendFromIdentity( pair, walletIdHex, @@ -1801,7 +1834,8 @@ class ExternalSendServiceImpl internal constructor( walletIdHex: String, destination: SendDestination, amount: Dash, - amountCredits: Long + amountCredits: Long, + destinationIsManagedIdentity: Boolean? ): ExternalSendResult { return when (destination) { is SendDestination.Core -> sendPlatformToCore(pair, walletIdHex, destination, amountCredits) @@ -1821,7 +1855,17 @@ class ExternalSendServiceImpl internal constructor( } ?: return notSent(pair, NotSentReason.GENERIC, "platform address balances unreadable") val inputs = selectPlatformInputs(candidates, amountCredits) ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount") - nativeWrite(pair, walletIdHex) { this.source.platformTopUpIdentity(walletIdHex, identityId, inputs) } + 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) + } + } } } } diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt index ad9d423931..c216e6eed0 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -271,14 +271,13 @@ class ExternalSendModelsTest { // The Platform source needs no identity. assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, core, hasIdentity = false)) assertEquals(SendSupport.SUPPORTED, support(SendBalance.PLATFORM, platform)) - // topUpFromAddresses only finds a managed identity: someone else's needs a Kotlin - // binding of platform#5860. + // 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.NEEDS_OWN_IDENTITY, support(SendBalance.PLATFORM, identity, own = false)) - // Could not tell: fail closed. - assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.PLATFORM, identity, own = null)) - // No identity at all: nothing is managed. - assertEquals(SendSupport.NEEDS_OWN_IDENTITY, support(SendBalance.PLATFORM, identity, hasIdentity = false)) + 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 diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index 49a2b830e1..acac32c594 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -119,7 +119,8 @@ class ExternalSendServiceImplTest { override suspend fun ownIdentityIdOrThrow(): String? = ownIdentity var identityFlow: Flow>? = null override fun observeOwnIdentityId(): Flow> = identityFlow ?: flowOf(Result.success(ownIdentity)) - override suspend fun managedIdentityIds(walletIdHex: String): List = managed + 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 @@ -192,6 +193,17 @@ class ExternalSendServiceImplTest { 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 @@ -515,6 +527,68 @@ class ExternalSendServiceImplTest { assertArrayEquals(ownId, source.lastToId) } + @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)) } } @@ -914,10 +988,7 @@ class ExternalSendServiceImplTest { SendBalance.CORE to platformP2sh, SendBalance.IDENTITY to ownIdentity, // Someone else's identity from Core: the resume gate cannot protect it. - SendBalance.CORE to otherIdentity, - // Someone else's identity from Platform: topUpFromAddresses only finds a managed - // identity (needs a Kotlin binding of platform#5860). - SendBalance.PLATFORM to otherIdentity + SendBalance.CORE to otherIdentity ) for ((from, to) in pairs) { val source = source() @@ -930,30 +1001,6 @@ class ExternalSendServiceImplTest { } } - @Test - fun platformToIdentity_needsAManagedIdentity_withNoSeamCall() = runBlocking { - // A wallet with no identity manages none: any identity destination is refused. - val noIdentity = source(ownIdentity = null, managed = emptyList()).apply { - platformBalances = { listOf(address(1, 900_000_000L)) } - } - for (to in listOf(ownIdentity, otherIdentity)) { - assertEquals( - "$to", - ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), - service(noIdentity).send(SendBalance.PLATFORM, to, amount, false) - ) - } - assertTrue(noIdentity.calls.isEmpty()) - - // The user's identity record, but not one the SDK wallet manages. - val unmanaged = source(managed = emptyList()).apply { platformBalances = { listOf(address(1, 900_000_000L)) } } - assertEquals( - ExternalSendResult.NotSent(NotSentReason.NOT_SUPPORTED), - service(unmanaged).send(SendBalance.PLATFORM, ownIdentity, amount, false) - ) - assertTrue(unmanaged.calls.isEmpty()) - } - @Test fun identitySource_withoutAnIdentity_isNotSupported() = runBlocking { val source = source(ownIdentity = null) diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 26aec4c6ef..a1b27679f8 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -269,20 +269,25 @@ class ExternalSendViewModelTest { service.ownIdentity = false val other = buildViewModel().apply { goToAmount(identityId) } assertEquals(SendBalance.SHIELDED, other.uiState.value.source) - // Platform tops up only a managed identity (someone else's needs platform#5860). - assertEquals(SendSupport.NEEDS_OWN_IDENTITY, other.uiState.value.supportOf(SendBalance.PLATFORM)) - other.onSourceSelected(SendBalance.PLATFORM) + // 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: fails closed. + // 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.PLATFORM)) + assertEquals(SendSupport.NEEDS_OWN_IDENTITY, unknown.uiState.value.supportOf(SendBalance.CORE)) + assertEquals(SendSupport.SUPPORTED, unknown.uiState.value.supportOf(SendBalance.PLATFORM)) } @Test From d7c2f682a66fcf526b907c9fa3b1b32aef6951e1 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 13 Nov 2026 08:41:33 -0800 Subject: [PATCH 26/30] fix(payments): cap Platform -> Core at what the withdrawal can take maxSendable returned null for a Platform source, so the Amount page fell back to the raw balance and allowed amounts the send then refused as INSUFFICIENT_FUNDS (MO-1121 QA). The cap now mirrors the withdrawal's own input selection: the first-sorting input keeps the SDK preflight's fee reserve and the 190-duff Core fee comes out of the gross. An unknown cap blocks Continue instead of falling back to the balance. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendModels.kt | 10 ++ .../platform/sdk/ExternalSendService.kt | 3 +- .../platform/sdk/ExternalSendServiceImpl.kt | 80 ++++++++++++- .../ui/payments/send/ExternalSendViewModel.kt | 12 +- .../sdk/ExternalSendServiceImplTest.kt | 105 +++++++++++++++++- .../send/ExternalSendViewModelTest.kt | 48 +++++++- 6 files changed, 251 insertions(+), 7 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 8d8ea8863b..2e643bbc6d 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -324,6 +324,16 @@ private fun detectCoreDashUri(input: String, network: AddressNetwork): Destinati } } +/** + * 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: the fee payer keeps the SDK's withdrawal fee reserve + * (about 0.004 DASH), far more than the fee finally charged, so the balance overstates what + * can be withdrawn. + */ +fun maxBoundsAmount(source: SendBalance, destinationKind: SendBalance): Boolean = + source == SendBalance.PLATFORM && destinationKind == SendBalance.CORE + /** Whether a pair can be sent, and if not, why (the UI maps each to its own copy). */ enum class 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 index fc14743145..b84107ed61 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendService.kt @@ -139,7 +139,8 @@ interface ExternalSendService { * 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. + * [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? diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index bfb40cf80b..487ab8e5bd 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -292,6 +292,60 @@ internal fun selectPlatformWithdrawalInputs( 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 → 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) { @@ -1076,6 +1130,10 @@ class ExternalSendServiceImpl internal constructor( * 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. * - Everything else: null (no pre-send fee figure). */ override suspend fun maxSendable(source: SendBalance, destinationKind: SendBalance): Dash? = try { @@ -1102,7 +1160,11 @@ class ExternalSendServiceImpl internal constructor( } } } - SendBalance.PLATFORM, SendBalance.IDENTITY -> null + SendBalance.PLATFORM -> when (destinationKind) { + SendBalance.CORE -> withContext(ioDispatcher) { platformToCoreMaxDuffsOrNull() }?.let(::Dash) + SendBalance.SHIELDED, SendBalance.PLATFORM, SendBalance.IDENTITY -> null + } + SendBalance.IDENTITY -> null } } catch (e: CancellationException) { throw e @@ -1111,6 +1173,22 @@ class ExternalSendServiceImpl internal constructor( 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 Core send fee reserve: size-based, the flat reserve when the UTXO count is unknown. */ private suspend fun coreSendFeeReserveDuffs(): Long = sendAllFeeReserveDuffs(source.spendableUtxoCount()) diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index 4e1f05bc3f..57d6dd3792 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -34,6 +34,7 @@ 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 @@ -229,9 +230,15 @@ data class ExternalSendUIState( amount.toKeypadString() } - /** What the amount may not exceed: the max sendable when known, else the balance. */ + /** + * 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() = maxSendable ?: balance + 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 @@ -247,6 +254,7 @@ data class ExternalSendUIState( amount.isPositive && !maxPending && balance != null && + limit != null && !exceedsBalance && (dashMode || rate != null || pinnedAmount != null || maxAmount != null) && !identityBlocks && diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index acac32c594..60da217c89 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -47,6 +47,7 @@ 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 @@ -813,12 +814,112 @@ class ExternalSendServiceImplTest { } @Test - fun int37Pairs_haveNoPreSendFee_andNoMax() = runBlocking { + 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 core, SendBalance.PLATFORM to shielded, SendBalance.IDENTITY to shielded)) { + 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 ──────────────────────────────── diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index a1b27679f8..6588a79684 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -377,6 +377,49 @@ class ExternalSendViewModelTest { 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( @@ -400,10 +443,13 @@ class ExternalSendViewModelTest { source = SendBalance.PLATFORM, amountText = "1", balance = twoDash, + maxSendable = twoDash, hasIdentity = true ) - // Platform → Core (partial withdrawal), Platform / Identity → Shielded (third-party shields). + // 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)) From 9d5fc46c0f9aa76b3e43f11bb7dfe7c09dd88f1b Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 13 Nov 2026 08:43:33 -0800 Subject: [PATCH 27/30] fix(payments): match the External Send confirm notes to Figma Drop the identity-balance note (not in the design), use Figma's info-rect-small and system_message-public icons for the two Shielded notes, and keep the sheet clear of the system bars like the app's other bottom sheets. Adds 320dp previews of the Shielded confirm sheet. Co-Authored-By: Claude Opus 5.5 --- .../res/drawable/ic_system_message_info.xml | 27 +++++ .../res/drawable/ic_system_message_public.xml | 30 ++++++ wallet/res/values/strings.xml | 1 - .../ui/payments/send/ExternalSendScreen.kt | 99 +++++++++++++++---- 4 files changed, 136 insertions(+), 21 deletions(-) create mode 100644 wallet/res/drawable/ic_system_message_info.xml create mode 100644 wallet/res/drawable/ic_system_message_public.xml 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/values/strings.xml b/wallet/res/values/strings.xml index ecd54a1acf..e3d33516c5 100644 --- a/wallet/res/values/strings.xml +++ b/wallet/res/values/strings.xml @@ -566,7 +566,6 @@ 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 - The funds go to this identity\'s balance on Dash Platform, not to its owner\'s Dash wallet. Sending… This could take about 30 seconds. You can leave this screen; the payment will continue. This will only take a moment. diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index a22843b376..151febdd23 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -33,8 +33,10 @@ 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 @@ -62,6 +64,7 @@ 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 @@ -506,13 +509,22 @@ private fun StatusText(text: String, color: Color) { // ── Sheets ────────────────────────────────────────────────────────────────── -/** Dimmed backdrop and a bottom sheet with a grabber, as in the shielded flows. */ +/** + * 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() } @@ -526,6 +538,7 @@ private fun SheetOverlay(onDismiss: () -> Unit, content: @Composable ColumnScope RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp) ) .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + .navigationBarsPadding() ) { Grabber() content() @@ -700,37 +713,34 @@ private fun ConfirmAmount(amount: Dash, rate: Fiat?, fiatCode: String?) { } /** - * Figma 7107:48425: from the Shielded balance to anywhere but Shielded, the send is not instant - * and becomes public. An identity destination is paid into its Platform balance (AC8). + * 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) { - val notes = buildList { - if (source == SendBalance.SHIELDED && destination !is SendDestination.Shielded) { - add(R.string.external_send_shielded_not_instant) - add( - 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 - } - ) - } - if (destination is SendDestination.Identity) { - add(R.string.external_send_identity_balance_note) - } + 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 } - if (notes.isEmpty()) return + 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 -> + notes.forEach { (note, icon) -> SystemMessage( description = stringResource(note), - iconRes = org.dash.wallet.common.R.drawable.ic_info_blue + // 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) } ) } } @@ -967,6 +977,55 @@ private fun ExternalSendAmountPreview() { } } +/** 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 = {}, From 652dbee8702355a9d6f42e178a702356ee3ee3c9 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 13 Nov 2026 08:50:29 -0800 Subject: [PATCH 28/30] fix(payments): keep a fee reserve on Platform -> Identity top-ups IdentityTopUpFromAddresses pays its fee from the first-sorting input's remainder (DeductFromInput(0)), but the inputs were picked to spend exactly the amount, so a top-up that emptied that address could not pay its fee. Select with the withdrawal selector and a fixed reserve (the SDK's withdrawal reserve at 16 inputs), refuse amounts below the identity funding minimum, and cap the Amount page at the same Max for both the managed and the external top-up. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendModels.kt | 8 +- .../platform/sdk/ExternalSendServiceImpl.kt | 81 +++++++++++--- .../platform/sdk/ExternalSendModelsTest.kt | 11 ++ .../sdk/ExternalSendServiceImplTest.kt | 101 +++++++++++++++++- 4 files changed, 183 insertions(+), 18 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt index 2e643bbc6d..7d38a422f0 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendModels.kt @@ -327,12 +327,12 @@ private fun detectCoreDashUri(input: String, network: AddressNetwork): Destinati /** * 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: the fee payer keeps the SDK's withdrawal fee reserve - * (about 0.004 DASH), far more than the fee finally charged, so the balance overstates what - * can be withdrawn. + * 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 + 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 { diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 487ab8e5bd..7fb25f2e7a 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -154,15 +154,28 @@ internal fun classifyCoreSendThrowable(e: Exception): ExternalSendResult = when } /** - * Pick Platform-address inputs that spend EXACTLY [targetCredits] (largest balances - * first), or null when the addresses cannot cover it — never a partial spend. + * 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 fun selectPlatformInputs(candidates: List, targetCredits: Long): List? { - if (targetCredits <= 0) return null - val picked = packOverageInputs(candidates, targetCredits) - val covered = picked.fold(0L) { acc, input -> Math.addExact(acc, input.credits) } - return picked.takeIf { covered == targetCredits } -} +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 @@ -235,8 +248,10 @@ private val ADDRESS_HASH_ORDER = Comparator { a, b -> } /** - * Inputs for a partial Platform → Core withdrawal (`withdrawCredits` with explicit inputs) - * that take EXACTLY [targetCredits] in total, or null when the addresses cannot cover it. + * 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. @@ -324,6 +339,23 @@ internal fun maxPlatformWithdrawalCredits( 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 @@ -1134,6 +1166,8 @@ class ExternalSendServiceImpl internal constructor( * 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 { @@ -1162,7 +1196,8 @@ class ExternalSendServiceImpl internal constructor( } SendBalance.PLATFORM -> when (destinationKind) { SendBalance.CORE -> withContext(ioDispatcher) { platformToCoreMaxDuffsOrNull() }?.let(::Dash) - SendBalance.SHIELDED, SendBalance.PLATFORM, SendBalance.IDENTITY -> null + SendBalance.IDENTITY -> withContext(ioDispatcher) { platformToIdentityMaxDuffsOrNull() }?.let(::Dash) + SendBalance.SHIELDED, SendBalance.PLATFORM -> null } SendBalance.IDENTITY -> null } @@ -1189,6 +1224,19 @@ class ExternalSendServiceImpl internal constructor( 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()) @@ -1931,8 +1979,15 @@ class ExternalSendServiceImpl internal constructor( val candidates = readOrNull("platform address balances") { this.source.platformAddressBalances(walletIdHex) } ?: return notSent(pair, NotSentReason.GENERIC, "platform address balances unreadable") - val inputs = selectPlatformInputs(candidates, amountCredits) - ?: return notSent(pair, NotSentReason.INSUFFICIENT_FUNDS, "platform addresses cannot cover the amount") + 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 diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt index c216e6eed0..2360e66515 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendModelsTest.kt @@ -280,6 +280,17 @@ class ExternalSendModelsTest { 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)) diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index 60da217c89..684778e210 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -520,7 +520,7 @@ class ExternalSendServiceImplTest { fun platformToIdentity_spendsExactlyTheAmount_fromTheAddresses() = runBlocking { val source = source().apply { platformBalances = { - listOf(FundingInput(0, ByteArray(20) { 1 }, 60_000_000L), FundingInput(0, ByteArray(20) { 2 }, 70_000_000L)) + 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)) @@ -528,6 +528,105 @@ class ExternalSendServiceImplTest { 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)) } } From ddbf90aa35c18ab66a28c98101ca6e978f0501a0 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 13 Nov 2026 15:35:27 -0800 Subject: [PATCH 29/30] fix(payments): address pre-review findings on External Send - Retry a failed Max read for Platform -> Core / Identity while the balance is unchanged, so Continue can't stay blocked - Show the recipient amount as unknown while a Max drain fee is unknown - Advanced scan: use the shared DashConnectUri.isConnectUri predicate (dashpay://connect was rejected) - Shielded external routes: log safeErrorSummary, not the throwable - Core asset-lock Max: cap the confirmed balance at the SDK max-sendable - Executor: don't clear a marker after a wipe; it may be the new wallet's - Docs: drain amount check is best-effort; accepted-risk note for a failed outpoint write followed by process death Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendServiceImpl.kt | 39 ++++++--- .../sdk/ShieldedBalanceServiceImpl.kt | 30 ++++--- .../ui/payments/send/AdvancedSendFragment.kt | 5 +- .../ui/payments/send/ExternalSendExecutor.kt | 7 +- .../ui/payments/send/ExternalSendScreen.kt | 18 +++-- .../ui/payments/send/ExternalSendViewModel.kt | 36 +++++++-- .../send/ExternalSendViewModelTest.kt | 81 ++++++++++++++++++- 7 files changed, 172 insertions(+), 44 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index 7fb25f2e7a..e37b932f85 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -464,8 +464,9 @@ internal interface ExternalSendSource { /** * 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 — in duffs; - * null when unknown or the cutover is not committed (fail closed). + * 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? @@ -674,11 +675,19 @@ internal class DashSdkExternalSendSource( override suspend fun coreAssetLockEligibleDuffs(): Long? = combine( sdkL1SendService.cutoverCommittedFlow(), - cutoverUiDataService.sdkConfirmedBalance - ) { committed, confirmed -> - // Only the SDK's own confirmed figure (ShieldedTransferViewModel's post-cutover - // source); never the frozen dashj ChainLocked fallback. - if (committed == true) confirmed?.value else null + 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 = @@ -1539,6 +1548,10 @@ class ExternalSendServiceImpl internal constructor( 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) @@ -1701,6 +1714,9 @@ class ExternalSendServiceImpl internal constructor( } 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) } @@ -1831,9 +1847,12 @@ class ExternalSendServiceImpl internal constructor( /** * A Max is the SDK drain (`emptyWallet`), whose amount is display-only: it spends - * whatever is spendable when it runs. So the drain is only started while the SDK's - * max-sendable figure is still exactly the [amount] the user confirmed; anything else - * (funds arrived or left in between, or unreadable) is NotSent with nothing spent. + * 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, 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 29d14a7b12..e45ae3a58b 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ShieldedBalanceServiceImpl.kt @@ -2558,7 +2558,7 @@ class ShieldedBalanceServiceImpl internal constructor( 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 && @@ -2567,29 +2567,33 @@ class ShieldedBalanceServiceImpl internal constructor( 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, failure + "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) } @@ -2843,7 +2847,7 @@ class ShieldedBalanceServiceImpl internal constructor( 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", t) + log.warn("shielded fee estimate failed; the fee is unknown ({})", safeErrorSummary(t)) null } } @@ -2978,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 @@ -3270,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/payments/send/AdvancedSendFragment.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt index ca4a91d184..ffa353f7eb 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/AdvancedSendFragment.kt @@ -146,8 +146,9 @@ class AdvancedSendFragment : Fragment() { val action = AdvancedSendViewModel.scanActionFor( input, AddressNetwork.fromId(Constants.NETWORK_PARAMETERS.id), - Constants.SUPPORTS_CONNECT - ) { DashConnectUri.isKeyUri(it) || DashConnectUri.isStUri(it) } + Constants.SUPPORTS_CONNECT, + DashConnectUri::isConnectUri + ) when (action) { is AdvancedScanAction.DashConnect -> { val navController = findNavController() diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt index f251aef289..7d35611112 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendExecutor.kt @@ -252,9 +252,10 @@ class ExternalSendExecutor internal constructor( result = ExternalSendResult.NotSent(NotSentReason.GENERIC) } if (marked && !isCurrent()) { - // A wipe ran while the marker was written, possibly after it cleared the - // marker: this one belongs to the wiped wallet. Nothing is sent. - withContext(NonCancellable) { clearMarker() } + // 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) } diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt index 151febdd23..b115daa416 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendScreen.kt @@ -609,9 +609,10 @@ private fun ConfirmSheet(uiState: ExternalSendUIState, confirm: ExternalSendConf .weight(1f, fill = false) .verticalScroll(rememberScrollState()) ) { - // What the recipient receives (a Core Max drain: the amount minus the fee; a - // Shielded → Core Max: the amount minus the Core fee). - ConfirmAmount(confirm.recipientAmount, uiState.rate, uiState.fiatCode) + // 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( @@ -693,13 +694,16 @@ private fun DashValueRow(label: String, value: String?, unknown: String) { 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. */ +/** + * 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?) { +private fun ConfirmAmount(amount: Dash?, rate: Fiat?, fiatCode: String?, unknown: String) { val separator = remember { decimalSeparatorFor(Locale.getDefault()) } - val fiat = amount.toFiatAt(rate) + val fiat = amount?.toFiatAt(rate) EnterAmount( - primaryAmount = localizeAmountForDisplay(amount.toDisplayString(), separator), + primaryAmount = amount?.let { localizeAmountForDisplay(it.toDisplayString(), separator) } ?: unknown, secondaryAmount = fiat?.let { localizeAmountForDisplay(it.toPlainString(), separator) } ?: "0", currencyCodes = remember(fiatCode) { currencyCodesFor(fiatCode) }, selectedCurrencyIndex = 0, diff --git a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt index 57d6dd3792..6cf197f295 100644 --- a/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt +++ b/wallet/src/de/schildbach/wallet/ui/payments/send/ExternalSendViewModel.kt @@ -25,6 +25,7 @@ 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 @@ -43,6 +44,7 @@ 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 @@ -52,9 +54,9 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.mapLatest 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 @@ -113,12 +115,13 @@ data class ExternalSendConfirm( 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 (when known); - * for a Shielded → Core Max the amount minus the Core fee. + * 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 + val recipientAmount: Dash? get() = when { - feeIncluded -> fee?.let { request.amount - it.fee } ?: request.amount + feeIncluded -> fee?.let { request.amount - it.fee } coreFeeIncluded -> request.amount - Dash(WITHDRAWAL_CORE_FEE_DUFFS) else -> request.amount } @@ -127,7 +130,8 @@ data class ExternalSendConfirm( * 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 fee?.let { recipientAmount + it.fee } + val total: Dash? + get() = if (feeIncluded) request.amount else recipientAmount?.let { amount -> fee?.let { amount + it.fee } } } /** @@ -274,7 +278,8 @@ class ExternalSendViewModel internal constructor( walletUIConfig: WalletUIConfig, exchangeRates: ExchangeRatesProvider, private val savedState: SavedStateHandle, - private val network: AddressNetwork + private val network: AddressNetwork, + private val maxRetryDelayMs: Long = ExternalSendServiceImpl.BALANCE_POLL_MS ) : ViewModel() { @Inject @@ -630,7 +635,22 @@ class ExternalSendViewModel internal constructor( .onEach { balance -> if (generation == balanceGeneration) _uiState.update { it.copy(balance = balance) } } - .mapLatest { balance -> balance to if (balance == null) null else service.maxSendable(source, destinationKind) } + .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) } diff --git a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt index 6588a79684..1144d7510e 100644 --- a/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/payments/send/ExternalSendViewModelTest.kt @@ -22,6 +22,7 @@ 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 @@ -29,6 +30,7 @@ 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 @@ -137,7 +139,11 @@ class ExternalSendViewModelTest { 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 @@ -160,9 +166,11 @@ class ExternalSendViewModelTest { private val marker = FakeMarker() private lateinit var executor: ExternalSendExecutor + private val mainDispatcher = UnconfinedTestDispatcher() + @Before fun setUp() { - Dispatchers.setMain(UnconfinedTestDispatcher()) + Dispatchers.setMain(mainDispatcher) executor = newExecutor() } @@ -503,6 +511,43 @@ class ExternalSendViewModelTest { 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 @@ -776,6 +821,21 @@ class ExternalSendViewModelTest { ) } + @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 @@ -954,6 +1014,25 @@ class ExternalSendViewModelTest { 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( From 7f2099417b208eadc383fa526c130ca58109daf0 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Mon, 16 Nov 2026 14:42:35 -0800 Subject: [PATCH 30/30] feat(payments): estimate the Core -> Identity network fee The confirm sheet showed "---" for the fee and total. Core -> Identity now estimates the L1 asset-lock reserve (assetLockMaxFeeReserve over the spendable UTXO count, an upper bound paid on top; null when the count is unknown), shown as "~" like Core -> Platform. Platform's top-up fee comes out of the locked amount and is not included. Co-Authored-By: Claude Opus 5.5 --- .../platform/sdk/ExternalSendServiceImpl.kt | 11 ++++++++-- .../sdk/ExternalSendServiceImplTest.kt | 22 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt index e37b932f85..a63e0de01d 100644 --- a/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt +++ b/wallet/src/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImpl.kt @@ -1123,10 +1123,15 @@ class ExternalSendServiceImpl internal constructor( * 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. - * - Core → Identity, Platform → *, Identity → *: Rust meters these at execution; no + * - 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 @@ -1143,7 +1148,9 @@ class ExternalSendServiceImpl internal constructor( SendBalance.PLATFORM -> this.source.spendableUtxoCount()?.let { FeeEstimate(Dash(coreToPlatformFeeDuffs(it)), exact = false) } - SendBalance.IDENTITY -> null + SendBalance.IDENTITY -> this.source.spendableUtxoCount()?.let { + FeeEstimate(assetLockMaxFeeReserve(it), exact = false) + } } SendBalance.SHIELDED -> this.source.shieldedFeeCredits(shieldedKindFor(destinationKind))?.let { val poolFee = ceilCreditsToDuffs(it) diff --git a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt index 684778e210..f8cddbbfc2 100644 --- a/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt +++ b/wallet/test/de/schildbach/wallet/service/platform/sdk/ExternalSendServiceImplTest.kt @@ -1343,7 +1343,29 @@ class ExternalSendServiceImplTest { 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