diff --git a/app/src/androidTest/java/to/bitkit/services/WatchOnlyAccountXpubDerivationTest.kt b/app/src/androidTest/java/to/bitkit/services/WatchOnlyAccountXpubDerivationTest.kt new file mode 100644 index 0000000000..7f53383700 --- /dev/null +++ b/app/src/androidTest/java/to/bitkit/services/WatchOnlyAccountXpubDerivationTest.kt @@ -0,0 +1,54 @@ +package to.bitkit.services + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.synonym.bitkitcore.AccountType +import com.synonym.bitkitcore.deriveOnchainDescriptor +import org.junit.Test +import org.junit.runner.RunWith +import org.lightningdevkit.ldknode.Network +import to.bitkit.models.toCoreNetwork +import to.bitkit.test.BaseAndroidTest +import to.bitkit.test.annotations.CoreServiceIntegration +import to.bitkit.test.annotations.DeviceIntegration +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +@DeviceIntegration +@CoreServiceIntegration +class WatchOnlyAccountXpubDerivationTest : BaseAndroidTest() { + @Test + fun coreDerivationMatchesTheMainnetAccountXpub() { + assertEquals(MAINNET_ACCOUNT_1_XPUB, coreAccountXpub(Network.BITCOIN, 1)) + } + + @Test + fun coreDerivationMatchesTheRegtestAccountXpubLdkNodeExports() { + assertEquals(REGTEST_ACCOUNT_1_TPUB, coreAccountXpub(Network.REGTEST, 1)) + } + + private fun coreAccountXpub(network: Network, accountIndex: Int): String { + val descriptor = deriveOnchainDescriptor( + mnemonicPhrase = TEST_MNEMONIC, + network = network.toCoreNetwork(), + bip39Passphrase = null, + accountType = AccountType.NATIVE_SEGWIT, + accountIndex = accountIndex.toUInt(), + ) + return accountXpubForNetwork(descriptorAccountXpub(descriptor), network) + } + + private companion object { + const val TEST_MNEMONIC = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" + + // m/84'/0'/1'; ldk-node only accepts watch-only accounts from index 1. Derived independently of bitkit-core. + const val MAINNET_ACCOUNT_1_XPUB = + "xpub6CatWdiZiodmYVtWLtEQsAg1H9ooS1bmsJUBwQ83FE1Fyk386FWcyic" + + "JgEZv3quZSJKA5dh5Lo2PbubMGxCfZtRthV6ST2qquL9w3HSzcUn" + + // m/84'/1'/1' with tpub version bytes, as ldk-node exports it on regtest; derived independently of bitkit-core. + const val REGTEST_ACCOUNT_1_TPUB = + "tpubDC8msFGeGuwnP2xwTZBBZSie1BLgRAkJhgzpFYTdpGgZNzguXQhNDVWp7mJb" + + "HJUjQQvV2myLU9dkx67a7VAUnzY7yT7nvhHj7FgS4oNivvq" + } +} diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt index 36bdc5b643..83f26930f1 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt @@ -23,7 +23,9 @@ import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.services.LightningService import to.bitkit.services.WatchOnlyAccountLifecycleCoordinator +import to.bitkit.services.WatchOnlyAccountXpubDeriver import to.bitkit.utils.AppError +import to.bitkit.utils.Logger import java.net.URI import java.net.URLDecoder import java.nio.ByteBuffer @@ -39,7 +41,6 @@ sealed class WatchOnlyAccountError : AppError() { class AuthorizationAccountMissing : WatchOnlyAccountError() class InvalidAccountName : WatchOnlyAccountError() class InvalidExtendedPublicKey : WatchOnlyAccountError() - class NodeUnavailable : WatchOnlyAccountError() } class WatchOnlyAccountAuthorizationStartError( @@ -55,6 +56,7 @@ class WatchOnlyAccountRepo @Inject constructor( private val lightningService: LightningService, private val lifecycleCoordinator: WatchOnlyAccountLifecycleCoordinator, private val xpubSerializer: WatchOnlyAccountXpubSerializer, + private val xpubDeriver: WatchOnlyAccountXpubDeriver, ) { val accounts: Flow> = store.data.map { it.accounts } val currentWalletAccounts: Flow> = accounts.map { accounts -> @@ -225,16 +227,35 @@ class WatchOnlyAccountRepo @Inject constructor( } } - private suspend fun exportAccountXpub(accountIndex: Int): String = ServiceQueue.LDK.background { - val node = lightningService.node ?: throw WatchOnlyAccountError.NodeUnavailable() - node.exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, accountIndex.toUInt()) - } + private suspend fun exportAccountXpub(accountIndex: Int): String = xpubDeriver.derive(accountIndex) + /** + * Applies [enabled] to the running node. Without a node (stopped, or being rebuilt after the app returned to the + * foreground) only the store changes: the next build loads tracked accounts from it, and + * [LightningService.reconcileWatchOnlyAccounts] on start adds or removes any account the build missed. + * + * The node is checked before queueing because a rebuild holds the LDK queue for the whole build while the node is + * still null; checking only inside the queue would make the approval wait for the build. + */ private suspend fun setAccountTracking( account: WatchOnlyAccountRecord, enabled: Boolean, + ) { + if (lightningService.node == null) return logTrackingWithoutNode(account) + applyAccountTracking(account, enabled) + } + + // Journeys read this line to prove an approval finished before the node was built. + private fun logTrackingWithoutNode(account: WatchOnlyAccountRecord) = Logger.info( + "Paykit Server account ${account.accountIndex} tracking stored without a node; it loads when the node starts", + context = TAG, + ) + + private suspend fun applyAccountTracking( + account: WatchOnlyAccountRecord, + enabled: Boolean, ) = ServiceQueue.LDK.background { - val node = lightningService.node ?: throw WatchOnlyAccountError.NodeUnavailable() + val node = lightningService.node ?: return@background logTrackingWithoutNode(account) val addressType = when (account.addressType) { WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE -> AddressType.NATIVE_SEGWIT else -> throw WatchOnlyAccountError.InvalidExtendedPublicKey() @@ -313,6 +334,7 @@ class WatchOnlyAccountRepo @Inject constructor( } companion object { + private const val TAG = "WatchOnlyAccountRepo" private const val MAX_NAME_LENGTH = 64 } } diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 9b639c2f48..d7a950a647 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout @@ -176,6 +177,34 @@ internal fun enabledOnchainWalletAccountConfigs( ) } +/** + * Builds with [config], and when ldk-node rejects a configured Paykit Server account (its xpub does not match the + * seed, which fails the whole build) builds again without those accounts, so the wallet still starts. The reconcile on + * start then adds each account the node accepts. + */ +internal suspend fun buildAcceptingPaykitServerAccounts(config: Config, build: suspend (Config) -> Node): Node = + try { + build(config) + } catch (e: BuildException.InvalidSeedBytes) { + if (config.onchainWalletAccounts.isEmpty()) throw LdkError(e) + Logger.error( + "Node rejected Paykit Server accounts at build, building without them", + e, + context = "LightningService", + ) + try { + build(config.copy(onchainWalletAccounts = emptyList())) + } catch (retryError: BuildException) { + throw LdkError(retryError) + } + } catch (e: BuildException) { + throw LdkError(e) + } + +/** Whether ldk-node rejected a Paykit Server account's xpub for this seed, which no retry can fix. */ +internal fun Throwable.isRejectedPaykitServerAccount(): Boolean = + generateSequence(this) { it.cause }.any { it is NodeException.InvalidSeedBytes } + internal fun LdkAddressType.toBitkitAddressType(): AddressType = when (this) { LdkAddressType.LEGACY -> AddressType.P2PKH LdkAddressType.NESTED_SEGWIT -> AddressType.P2SH @@ -211,6 +240,7 @@ class LightningService internal constructor( companion object { private const val TAG = "LightningService" private const val RELEASE_FEE_ATTEMPTS = 4 + private val WATCH_ONLY_RECONCILE_RETRY_DELAY = 15.seconds /** A small fixed payment to a new wallet address; the rest returns as change, which pays the fee. */ private const val RELEASE_AMOUNT_SATS = 1_000uL @@ -289,6 +319,10 @@ class LightningService internal constructor( private var listenerJob: Job? = null + @Volatile + private var watchOnlyReconcileRetryJob: Job? = null + private val watchOnlyReconcileRetryLock = Any() + // Release of the previous node's rust handle (free_node). Rebuild and destructive storage work // wait on this so a new node never touches storage the old one is still draining. @Volatile @@ -343,6 +377,20 @@ class LightningService internal constructor( runtimeMonitor: NodeRuntimeMonitor, channelMigration: ChannelDataMigration? = null, ): Node = ServiceQueue.LDK.background(ldkQueue) { + buildAcceptingPaykitServerAccounts(config) { + buildNode(walletIndex, customServerUrl, customRgsServerUrl, it, runtimeMonitor, channelMigration) + } + } + + @Suppress("ForbiddenComment") + private suspend fun buildNode( + walletIndex: Int, + customServerUrl: String?, + customRgsServerUrl: String?, + config: Config, + runtimeMonitor: NodeRuntimeMonitor, + channelMigration: ChannelDataMigration?, + ): Node { val storedSettings = settingsStore.data.first() val settings = storedSettings.withRequiredNativeSegwitMonitoring() if (settings != storedSettings) { @@ -393,9 +441,7 @@ class LightningService internal constructor( throw ServiceError.VssAuthRequired() } - builder.buildWithVssStore(vssUrl, vssStoreId, lnurlAuthServerUrl, fixedHeaders) - } catch (e: BuildException) { - throw LdkError(e) + return builder.buildWithVssStore(vssUrl, vssStoreId, lnurlAuthServerUrl, fixedHeaders) } finally { // TODO: cleanup sensitive data after implementing a `SecureString` value holder for Keychain return values } @@ -487,9 +533,11 @@ class LightningService internal constructor( Logger.info("Node started", context = TAG) } + // No wallet sync here: it holds the watch-only lock and the LDK queue for the whole Electrum round trip, which + // delays the node start and any Pubky auth approval waiting on that lock. The initial sync after start covers it. private suspend fun reconcileWatchOnlyAccountsBestEffort() { runSuspendCatching { - reconcileWatchOnlyAccounts() + reconcileWatchOnlyAccounts(syncAfterReconcile = false) }.onFailure { error -> Logger.error("Failed to reconcile Paykit Server accounts during startup", error, context = TAG) } @@ -505,7 +553,9 @@ class LightningService internal constructor( } val desiredConfigs = enabledOnchainWalletAccountConfigs(walletRecords, currentWalletIndex) - ServiceQueue.LDK.background(ldkQueue) { + val reconciled = ServiceQueue.LDK.background(ldkQueue) { + // The node may have been stopped and released while this waited for the queue. + if (this@LightningService.node !== node) return@background false val trackedAccounts = node.listOnchainWalletAccounts() val managedKeys = (walletRecords + accountsPendingRemoval).mapNotNull { record -> when (record.addressType) { @@ -523,25 +573,34 @@ class LightningService internal constructor( } } - desiredConfigs.forEach { config -> - val isTracked = trackedAccounts.any { - it.addressType == config.addressType && it.accountIndex == config.accountIndex + // One account the node rejects must not keep the others from loading. A transient failure is rethrown + // ahead of a rejected xpub so the caller retries it. + val failures = desiredConfigs.mapNotNull { config -> + runSuspendCatching { + val isTracked = trackedAccounts.any { + it.addressType == config.addressType && it.accountIndex == config.accountIndex + } + if (!isTracked) { + node.addOnchainWalletAccount(config.addressType, config.accountIndex, config.xpub) + } + node.onchainPayment().revealReceiveAddressesToAccount( + config.addressType, + config.accountIndex, + WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), + ) + }.exceptionOrNull()?.also { + Logger.error("Failed to load Paykit Server account ${config.accountIndex}", it, context = TAG) } - if (!isTracked) { - node.addOnchainWalletAccount(config.addressType, config.accountIndex, config.xpub) - } - node.onchainPayment().revealReceiveAddressesToAccount( - config.addressType, - config.accountIndex, - WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), - ) } + val retryable = failures.firstOrNull { !it.isRejectedPaykitServerAccount() } + (retryable ?: failures.firstOrNull())?.let { throw it } if (syncAfterReconcile && desiredConfigs.isNotEmpty() && node.status().isRunning) { node.syncWallets() } + true } - if (accountsPendingRemoval.isNotEmpty()) { + if (reconciled && accountsPendingRemoval.isNotEmpty()) { watchOnlyAccountStore.completeReconciliation(currentWalletIndex) } } @@ -551,6 +610,7 @@ class LightningService internal constructor( // let the GC free it later on the finalizer thread, racing the next node. This covers the whole // body, including the listener join, so cancellation during listener cleanup cannot skip it. suspend fun stop() = withContext(NonCancellable) { + watchOnlyReconcileRetryJob?.cancelAndJoin() shouldListenForEvents = false // A stop requested from inside an event handler runs on the listener job itself; joining it // here would deadlock, so let the loop exit on shouldListenForEvents instead. @@ -701,7 +761,11 @@ class LightningService internal constructor( suspend fun sync() { val node = this.node ?: throw ServiceError.NodeNotSetup() - reconcileWatchOnlyAccounts(syncAfterReconcile = false) + // A Paykit Server account that fails to load must not fail the wallet sync: sends are gated on it. A transient + // failure is retried on its own schedule; an xpub the node rejects (`InvalidSeedBytes`) stays rejected. + val reconcileFailure = runSuspendCatching { reconcileWatchOnlyAccounts(syncAfterReconcile = false) } + .onFailure { Logger.error("Failed to reconcile Paykit Server accounts before sync", it, context = TAG) } + .exceptionOrNull() Logger.verbose("Syncing LDK…", context = TAG) ServiceQueue.LDK.background(ldkQueue) { @@ -711,6 +775,41 @@ class LightningService internal constructor( _syncStatusChanged.tryEmit(Unit) Logger.debug("LDK synced", context = TAG) + if (reconcileFailure != null && !reconcileFailure.isRejectedPaykitServerAccount()) { + scheduleWatchOnlyReconcileRetry() + } + } + + /** Retries loading Paykit Server accounts until they load, the node stops, or the node rejects one for good. */ + private fun scheduleWatchOnlyReconcileRetry() { + synchronized(watchOnlyReconcileRetryLock) { + if (watchOnlyReconcileRetryJob?.isActive == true) return + watchOnlyReconcileRetryJob = launch { retryWatchOnlyReconcile() } + } + } + + private suspend fun retryWatchOnlyReconcile() { + var retry = true + while (retry && currentCoroutineContext().isActive && node != null) { + delay(WATCH_ONLY_RECONCILE_RETRY_DELAY) + val failure = runSuspendCatching { reconcileWatchOnlyAccounts(syncAfterReconcile = false) } + .exceptionOrNull() + if (failure == null) { + syncWalletsAfterAccountsLoad() + } else { + Logger.warn("Paykit Server account reconcile retry failed", failure, context = TAG) + } + retry = failure != null && !failure.isRejectedPaykitServerAccount() + } + } + + // Outside the watch-only lock, as in sync(): an Electrum round trip must not delay Pubky auth. A failure here is + // a wallet sync failure, which the regular sync retries. + private suspend fun syncWalletsAfterAccountsLoad() { + runSuspendCatching { + ServiceQueue.LDK.background(ldkQueue) { this@LightningService.node?.syncWallets() } + _syncStatusChanged.tryEmit(Unit) + }.onFailure { Logger.warn("Wallet sync after loading Paykit Server accounts failed", it, context = TAG) } } suspend fun sign(message: String): String { diff --git a/app/src/main/java/to/bitkit/services/WatchOnlyAccountXpubDeriver.kt b/app/src/main/java/to/bitkit/services/WatchOnlyAccountXpubDeriver.kt new file mode 100644 index 0000000000..1d888b1e38 --- /dev/null +++ b/app/src/main/java/to/bitkit/services/WatchOnlyAccountXpubDeriver.kt @@ -0,0 +1,92 @@ +package to.bitkit.services + +import com.synonym.bitkitcore.AccountType +import org.lightningdevkit.ldknode.Network +import to.bitkit.data.keychain.Keychain +import to.bitkit.env.Env +import to.bitkit.repositories.WatchOnlyAccountError +import to.bitkit.utils.ServiceError +import java.math.BigInteger +import java.security.MessageDigest +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Derives the BIP84 account xpub (`m/84'/coin'/account'`) for a Paykit Server watch-only account from the wallet + * mnemonic, so a Pubky auth approval does not wait for the LDK node to be built and started. + * + * The result must equal `Node.exportOnchainWalletAccountXpub`, which `Node.addOnchainWalletAccount` compares + * byte for byte: bitkit-core always serializes with mainnet version bytes, while ldk-node uses the configured + * network's, so test networks get the `tpub` version. + */ +@Singleton +class WatchOnlyAccountXpubDeriver @Inject constructor( + private val keychain: Keychain, + private val coreService: CoreService, +) { + suspend fun derive(accountIndex: Int): String { + val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() + val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val descriptor = coreService.onchain.deriveOnchainDescriptor( + mnemonicPhrase = mnemonic, + network = Env.network, + bip39Passphrase = passphrase, + accountType = AccountType.NATIVE_SEGWIT, + accountIndex = accountIndex.toUInt(), + ) + return accountXpubForNetwork(descriptorAccountXpub(descriptor), Env.network) + } +} + +private val DESCRIPTOR_XPUB = Regex("""](xpub[1-9A-HJ-NP-Za-km-z]+)/""") +private const val BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +private const val EXTENDED_KEY_PAYLOAD_LENGTH = 78 +private const val VERSION_LENGTH = 4 +private const val CHECKSUM_LENGTH = 4 +private val TESTNET_XPUB_VERSION = byteArrayOf(0x04, 0x35, 0x87.toByte(), 0xCF.toByte()) + +internal fun descriptorAccountXpub(descriptor: String): String = + DESCRIPTOR_XPUB.find(descriptor)?.groupValues?.get(1) ?: throw WatchOnlyAccountError.InvalidExtendedPublicKey() + +internal fun accountXpubForNetwork(xpub: String, network: Network): String { + if (network == Network.BITCOIN) return xpub + val payload = base58CheckDecode(xpub) + if (payload.size != EXTENDED_KEY_PAYLOAD_LENGTH) throw WatchOnlyAccountError.InvalidExtendedPublicKey() + return base58CheckEncode(TESTNET_XPUB_VERSION + payload.copyOfRange(VERSION_LENGTH, payload.size)) +} + +private fun checksum(payload: ByteArray): ByteArray { + val sha256 = MessageDigest.getInstance("SHA-256") + return sha256.digest(sha256.digest(payload)).copyOfRange(0, CHECKSUM_LENGTH) +} + +private fun base58CheckDecode(text: String): ByteArray { + var value = BigInteger.ZERO + for (char in text) { + val digit = BASE58_ALPHABET.indexOf(char) + if (digit < 0) throw WatchOnlyAccountError.InvalidExtendedPublicKey() + value = value.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(digit.toLong())) + } + val bytes = value.toByteArray().dropWhile { it == 0.toByte() }.toByteArray() + val decoded = ByteArray(text.takeWhile { it == '1' }.length) + bytes + if (decoded.size <= CHECKSUM_LENGTH) throw WatchOnlyAccountError.InvalidExtendedPublicKey() + val payload = decoded.copyOfRange(0, decoded.size - CHECKSUM_LENGTH) + if (!checksum(payload).contentEquals(decoded.copyOfRange(payload.size, decoded.size))) { + throw WatchOnlyAccountError.InvalidExtendedPublicKey() + } + return payload +} + +private fun base58CheckEncode(payload: ByteArray): String { + val bytes = payload + checksum(payload) + var value = BigInteger(1, bytes) + val fiftyEight = BigInteger.valueOf(58) + val encoded = StringBuilder() + while (value > BigInteger.ZERO) { + val (quotient, remainder) = value.divideAndRemainder(fiftyEight) + encoded.append(BASE58_ALPHABET[remainder.toInt()]) + value = quotient + } + repeat(bytes.takeWhile { it == 0.toByte() }.size) { encoded.append('1') } + return encoded.reverse().toString() +} diff --git a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt index cd1b15e547..60078b09dd 100644 --- a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt +++ b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt @@ -34,6 +34,5 @@ private fun Throwable.pubkyAuthMessageResource() = when (this) { is WatchOnlyAccountError.AuthorizationAccountMissing -> R.string.watch_only_accounts__setup_not_finished is WatchOnlyAccountError.InvalidAccountName -> R.string.watch_only_accounts__error_invalid_name is WatchOnlyAccountError.InvalidExtendedPublicKey -> R.string.watch_only_accounts__error_invalid_xpub - is WatchOnlyAccountError.NodeUnavailable -> R.string.watch_only_accounts__error_node_unavailable else -> null } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 519cc21883..9d7a26b519 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1831,7 +1831,6 @@ لا توجد حسابات خوادم أدخل اسم حساب بين 1 و64 حرفًا. تعذر على Bitkit إنشاء xpub صالح للحساب. - يجب أن تكون المحفظة قيد التشغيل قبل إنشاء حساب. الاسم اسم الحساب تم حفظ اسم الحساب diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 2c0359bd0c..b8136aebeb 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1829,7 +1829,6 @@ Sin cuentas de servidor Introduzca un nombre de cuenta de entre 1 y 64 caracteres. Bitkit no pudo crear un xpub de cuenta válido. - La billetera debe estar en funcionamiento para poder crear una cuenta. NOMBRE Nombre de la cuenta Nombre de la cuenta guardado diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 745b66514c..ddac452b83 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1828,7 +1828,6 @@ No hi ha comptes de servidor Introdueix un nom de compte d\'entre 1 i 64 caràcters. Bitkit no ha pogut crear un xpub de compte vàlid. - La cartera ha d\'estar en funcionament abans de poder crear un compte. NOM Nom del compte Nom del compte desat diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 069e3d7aea..8b5b6d551f 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1830,7 +1830,6 @@ Žádné účty serverů Zadejte název účtu o délce 1 až 64 znaků. Bitkit nemohl vytvořit platný xpub účtu. - Před vytvořením účtu musí být peněženka spuštěná. NÁZEV Název účtu Název účtu uložen diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 0529225082..14aa0cf2bd 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1827,7 +1827,6 @@ Keine Serverkonten Gib einen Kontonamen mit 1 bis 64 Zeichen ein. Bitkit konnte keinen gültigen Konto-xpub erstellen. - Das Wallet muss laufen, bevor ein Konto erstellt werden kann. NAME Kontoname Kontoname gespeichert diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4e4484778e..4bff84fae9 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1827,7 +1827,6 @@ Κανένας λογαριασμός διακομιστή Εισήγαγε όνομα λογαριασμού από 1 έως 64 χαρακτήρες. Το Bitkit δεν μπόρεσε να δημιουργήσει έγκυρο xpub λογαριασμού. - Το πορτοφόλι πρέπει να εκτελείται για να δημιουργηθεί λογαριασμός. ΟΝΟΜΑ Όνομα λογαριασμού Το όνομα λογαριασμού αποθηκεύτηκε diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 4cffc2f39f..7202a3d49d 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1828,7 +1828,6 @@ No hay cuentas de servidor Introduce un nombre de cuenta de entre 1 y 64 caracteres. Bitkit no pudo crear un xpub de cuenta válido. - El monedero debe estar en funcionamiento antes de poder crear una cuenta. NOMBRE Nombre de la cuenta Nombre de la cuenta guardado diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 2f69d5c1d2..6b6ad1d662 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1829,7 +1829,6 @@ No hay cuentas de servidor Introduzca un nombre de cuenta de entre 1 y 64 caracteres. Bitkit no pudo crear un xpub de cuenta válido. - El monedero debe estar en funcionamiento antes de poder crear una cuenta. NOMBRE Nombre de la cuenta Nombre de la cuenta guardado diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 2a8923048c..eca283cab5 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1829,7 +1829,6 @@ Aucun compte serveur Saisissez un nom de compte de 1 à 64 caractères. Bitkit n\'a pas pu créer de xpub de compte valide. - Le portefeuille doit être en cours d\'exécution pour pouvoir créer un compte. NOM Nom du compte Nom du compte enregistré diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 88a2ba5341..5b4d26c208 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1829,7 +1829,6 @@ Nessun account server Inserisci un nome account tra 1 e 64 caratteri. Bitkit non è riuscito a creare un xpub valido per l\'account. - Il wallet deve essere in esecuzione prima di poter creare un account. NOME Nome account Nome account salvato diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index ccdab9c374..c2b377f023 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1828,7 +1828,6 @@ Geen serveraccounts Voer een accountnaam in van 1 tot 64 tekens. Bitkit kon geen geldige account-xpub aanmaken. - De wallet moet actief zijn voordat een account kan worden aangemaakt. NAAM Accountnaam Accountnaam opgeslagen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 7e7eb0c1d8..15f3359e64 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1829,7 +1829,6 @@ Brak kont serwerów Wprowadź nazwę konta o długości od 1 do 64 znaków. Bitkit nie mógł utworzyć prawidłowego xpub konta. - Portfel musi być uruchomiony, zanim będzie można utworzyć konto. NAZWA Nazwa konta Nazwa konta zapisana diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index e117e7bcea..6a4b6106a9 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1829,7 +1829,6 @@ Nenhuma conta de servidor Digite um nome de conta entre 1 e 64 caracteres. A Bitkit não conseguiu criar um xpub de conta válido. - A carteira precisa estar em execução antes que uma conta possa ser criada. NOME Nome da conta Nome da conta salvo diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 7f33fb21a6..cad1c5fcd9 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1828,7 +1828,6 @@ Sem contas de servidor Introduza um nome de conta com 1 a 64 caracteres. A Bitkit não conseguiu criar uma xpub de conta válida. - A carteira tem de estar em execução para criar uma conta. NOME Nome da conta Nome da conta guardado diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 4440419aab..56e0e01cbd 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1842,7 +1842,6 @@ Нет аккаунтов серверов Введите название аккаунта длиной от 1 до 64 символов. Bitkit не смог создать действительный xpub аккаунта. - Кошелёк должен быть запущен, прежде чем можно будет создать аккаунт. НАЗВАНИЕ Название аккаунта Название аккаунта сохранено diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index aaf1b64921..d1aad67c41 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1812,7 +1812,6 @@ No server accounts Enter an account name between 1 and 64 characters. Bitkit could not create a valid account xpub. - The wallet must be running before an account can be created. NAME Account name Account name saved diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt index 62a00d182d..305f46686e 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt @@ -29,6 +29,7 @@ import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.services.LightningService import to.bitkit.services.WatchOnlyAccountLifecycleCoordinator +import to.bitkit.services.WatchOnlyAccountXpubDeriver import to.bitkit.test.BaseUnitTest import to.bitkit.utils.LoggerLdk import java.util.concurrent.CountDownLatch @@ -175,6 +176,7 @@ class WatchOnlyAccountLifecycleCoordinatorTest : BaseUnitTest() { lightningService, coordinator, mock(), + mock(), ) private fun account() = WatchOnlyAccountRecord( diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt index 697b64fbc6..20dcdb3150 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt @@ -1,11 +1,16 @@ package to.bitkit.repositories import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.junit.Test import org.lightningdevkit.ldknode.AddressType import org.lightningdevkit.ldknode.Node @@ -19,6 +24,7 @@ import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.async.ServiceQueue import to.bitkit.data.WatchOnlyAccountAllocationState import to.bitkit.data.WatchOnlyAccountData import to.bitkit.data.WatchOnlyAccountStore @@ -31,6 +37,7 @@ import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.services.LightningService import to.bitkit.services.WatchOnlyAccountLifecycleCoordinator +import to.bitkit.services.WatchOnlyAccountXpubDeriver import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -41,6 +48,8 @@ import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) class WatchOnlyAccountRepoTest : BaseUnitTest() { + private val xpubDeriver = mock() + @Test fun `explicit watch-only request allocates a new account instead of reusing an active account`() = test { val active = account() @@ -51,7 +60,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { whenever(store.load()).thenReturn(listOf(active)) whenever(store.reserveAccountIndex(any(), any())).thenReturn(2) whenever(lightningService.node).thenReturn(node) - whenever(node.exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 2u)).thenReturn(TEST_XPUB_ALTERNATE) + whenever(xpubDeriver.derive(2)).thenReturn(TEST_XPUB_ALTERNATE) val prepared = repository(store, lightningService).prepareUnsignedClaim( "pubkyauth://signin?secret=new&x-bitkit-claim=watch-only-account-v1", @@ -175,7 +184,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { } whenever(store.reserveAccountIndex(any(), any())).thenReturn(1) whenever(lightningService.node).thenReturn(node) - whenever(node.exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 1u)).thenReturn(TEST_XPUB) + whenever(xpubDeriver.derive(1)).thenReturn(TEST_XPUB) val sut = repository(store, lightningService) val first = sut.prepareUnsignedClaim( @@ -195,7 +204,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { assertEquals(first.account.xpub, retry.account.xpub) assertEquals("Renamed account", retry.account.name) assertFalse(retry.account.isTrackingEnabled) - verify(node, times(1)).exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 1u) + verify(xpubDeriver, times(1)).derive(1) verify(node, never()).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, TEST_XPUB) } @@ -242,7 +251,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { } whenever(lightningService.currentWalletIndex).thenReturn(0) whenever(lightningService.node).thenReturn(node) - whenever(node.exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 6u)).thenReturn(TEST_XPUB) + whenever(xpubDeriver.derive(6)).thenReturn(TEST_XPUB) val sut = repository(store, lightningService) val prepared = sut.prepareUnsignedClaim(RESTORED_AUTH_URL, "Restored server") @@ -252,8 +261,8 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { assertNotEquals(authorizingAccount.xpub, prepared.account.xpub) assertEquals(6, storedData.pendingAccountIndexByRequest[restoredRequestKey]) assertEquals(listOf(5, 6), storedData.accounts.map(WatchOnlyAccountRecord::accountIndex)) - verify(node).exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 6u) - verify(node, never()).exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 5u) + verify(xpubDeriver).derive(6) + verify(xpubDeriver, never()).derive(5) } @Test @@ -298,7 +307,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { } whenever(lightningService.currentWalletIndex).thenReturn(0) whenever(lightningService.node).thenReturn(node) - whenever(node.exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 6u)).thenReturn(TEST_XPUB) + whenever(xpubDeriver.derive(6)).thenReturn(TEST_XPUB) val sut = repository(store, lightningService) val prepared = sut.prepareUnsignedClaim(RESTORED_AUTH_URL, "Restored server") @@ -309,8 +318,8 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { assertEquals(6, storedData.pendingAccountIndexByRequest[restoredRequestKey]) assertEquals(listOf(6), storedData.accounts.map(WatchOnlyAccountRecord::accountIndex)) assertEquals(listOf(5), storedData.accountsPendingRemoval.map(WatchOnlyAccountRecord::accountIndex)) - verify(node).exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 6u) - verify(node, never()).exportOnchainWalletAccountXpub(AddressType.NATIVE_SEGWIT, 5u) + verify(xpubDeriver).derive(6) + verify(xpubDeriver, never()).derive(5) } @Test @@ -522,6 +531,95 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { verify(node, never()).removeOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u) } + @Test + fun `prepare and begin authorization complete without a node`() = test { + var storedAccounts = emptyList() + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = storedAccounts))) + whenever(store.load()).thenAnswer { storedAccounts } + whenever(store.save(any())).thenAnswer { + storedAccounts = it.getArgument(0) + Unit + } + whenever(store.update(any())).thenAnswer { + val transform = it.getArgument<(List) -> List>(0) + storedAccounts = transform(storedAccounts) + Unit + } + whenever(store.reserveAccountIndex(any(), any())).thenReturn(1) + whenever(lightningService.node).thenReturn(null) + whenever(xpubDeriver.derive(1)).thenReturn(TEST_XPUB) + val sut = repository(store, lightningService) + + val prepared = sut.prepareUnsignedClaim(RESTORED_AUTH_URL, "Creator account") + sut.beginAuthorization(prepared.account.id) + + val stored = storedAccounts.single() + assertEquals(TEST_XPUB, stored.xpub) + assertTrue(stored.isTrackingEnabled) + assertEquals(WatchOnlyAccountSetupState.Authorizing, stored.setupState) + } + + @Test + fun `begin authorization without a node does not wait for the busy LDK queue`() = test { + val account = account().copy(isTrackingEnabled = false, setupState = WatchOnlyAccountSetupState.PendingDelivery) + var storedAccounts = listOf(account) + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = storedAccounts))) + whenever(store.load()).thenAnswer { storedAccounts } + whenever(store.update(any())).thenAnswer { + val transform = it.getArgument<(List) -> List>(0) + storedAccounts = transform(storedAccounts) + Unit + } + whenever(lightningService.node).thenReturn(null) + val sut = repository(store, lightningService) + val buildRunning = CompletableDeferred() + val releaseBuild = CompletableDeferred() + val build = launch(Dispatchers.Default) { + ServiceQueue.LDK.background { + buildRunning.complete(Unit) + runBlocking { releaseBuild.await() } + } + } + + val finishedWhileQueueBusy = withContext(Dispatchers.Default) { + buildRunning.await() + val authorization = async { sut.beginAuthorization(account.id) } + val finished = withTimeoutOrNull(LDK_QUEUE_WAIT_BOUND_MS) { authorization.await() } != null + releaseBuild.complete(Unit) + authorization.await() + finished + } + build.join() + + assertTrue(finishedWhileQueueBusy) + assertTrue(storedAccounts.single().isTrackingEnabled) + assertEquals(WatchOnlyAccountSetupState.Authorizing, storedAccounts.single().setupState) + } + + @Test + fun `cancel without a node resets the store for the next node start`() = test { + val account = account().copy(setupState = WatchOnlyAccountSetupState.Authorizing) + var storedAccounts = listOf(account) + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = storedAccounts))) + whenever(store.load()).thenAnswer { storedAccounts } + whenever(store.save(any())).thenAnswer { + storedAccounts = it.getArgument(0) + Unit + } + whenever(lightningService.node).thenReturn(null) + + repository(store, lightningService).cancelAuthorization(account.id) + + assertFalse(storedAccounts.single().isTrackingEnabled) + assertEquals(WatchOnlyAccountSetupState.PendingDelivery, storedAccounts.single().setupState) + } + @Test fun `new account is removed when address revelation fails and original error is preserved`() = test { val account = account().copy(isTrackingEnabled = false, setupState = WatchOnlyAccountSetupState.PendingDelivery) @@ -614,7 +712,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { ): WatchOnlyAccountRepo { val xpubSerializer = mock() whenever(xpubSerializer.serialize(any())).thenReturn(ByteArray(78)) - return WatchOnlyAccountRepo(testDispatcher, store, lightningService, coordinator, xpubSerializer) + return WatchOnlyAccountRepo(testDispatcher, store, lightningService, coordinator, xpubSerializer, xpubDeriver) } private fun account() = WatchOnlyAccountRecord( @@ -631,6 +729,7 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { ) private companion object { + const val LDK_QUEUE_WAIT_BOUND_MS = 2_000L const val RESTORED_AUTH_URL = "pubkyauth://signin?relay=https%3A%2F%2Frelay.example&secret=backup&" + "caps=%2Fpub%2Fpaykit%2Fv0%2Fbitkit%2Fserver%2F%3Arw&x-bitkit-claim=watch-only-account-v1" diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRestoreTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRestoreTest.kt index c01554ca1d..491a833548 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRestoreTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRestoreTest.kt @@ -25,11 +25,14 @@ import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.services.LightningService import to.bitkit.services.WatchOnlyAccountLifecycleCoordinator +import to.bitkit.services.WatchOnlyAccountXpubDeriver import to.bitkit.test.BaseUnitTest import to.bitkit.utils.LoggerLdk import kotlin.test.assertEquals class WatchOnlyAccountRestoreTest : BaseUnitTest() { + private val xpubDeriver = mock() + @Test fun `retry and reconciliation use the restored incomplete account`() = test { val restoredAccount = account(id = "restored-account", accountIndex = 5, createdAt = 1) @@ -56,7 +59,14 @@ class WatchOnlyAccountRestoreTest : BaseUnitTest() { val lightningService = lightningService(store, node, coordinator) val xpubSerializer = mock() whenever(xpubSerializer.serialize(TEST_XPUB)).thenReturn(ByteArray(78)) - val sut = WatchOnlyAccountRepo(testDispatcher, store, lightningService, coordinator, xpubSerializer) + val sut = WatchOnlyAccountRepo( + testDispatcher, + store, + lightningService, + coordinator, + xpubSerializer, + xpubDeriver, + ) val prepared = sut.prepareUnsignedClaim(AUTH_URL, restoredAccount.name) lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false) @@ -65,7 +75,7 @@ class WatchOnlyAccountRestoreTest : BaseUnitTest() { assertEquals(restoredAccount.id, prepared.account.id) assertEquals(restoredAccount.accountIndex, prepared.account.accountIndex) verify(store, never()).reserveAccountIndex(any(), any()) - verify(node, never()).exportOnchainWalletAccountXpub(any(), any()) + verify(xpubDeriver, never()).derive(any()) verify(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 5u, TEST_XPUB) verify(onchainPayment).revealReceiveAddressesToAccount( AddressType.NATIVE_SEGWIT, diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index 02ea71040b..b581e37190 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -14,9 +14,11 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json import org.junit.Before import org.junit.Rule @@ -26,6 +28,7 @@ import org.lightningdevkit.ldknode.AddressInfo import org.lightningdevkit.ldknode.AddressType import org.lightningdevkit.ldknode.AnchorChannelsConfig import org.lightningdevkit.ldknode.BalanceSource +import org.lightningdevkit.ldknode.BuildException import org.lightningdevkit.ldknode.Config import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.Event @@ -40,6 +43,7 @@ import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.OnchainPayment import org.lightningdevkit.ldknode.OnchainSendResult import org.lightningdevkit.ldknode.OnchainWalletAccount +import org.lightningdevkit.ldknode.OnchainWalletAccountConfig import org.lightningdevkit.ldknode.OutPoint import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection @@ -53,6 +57,7 @@ import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -87,6 +92,7 @@ import to.bitkit.repositories.PaykitPaymentRequestId import to.bitkit.repositories.PreparedOnchainSend import to.bitkit.repositories.PreparedOnchainSendRefused import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.LdkError import to.bitkit.utils.LoggerLdk import to.bitkit.utils.ServiceError import java.io.File @@ -97,9 +103,11 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertSame import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import com.synonym.bitkitcore.AddressType as BitkitAddressType import org.lightningdevkit.ldknode.LogLevel as LdkLogLevel @@ -108,6 +116,7 @@ import org.lightningdevkit.ldknode.PreparedOnchainSend as NativePreparedOnchainS private const val VERIFY_TIMEOUT_MS = 2_000L private const val RELEASE_GATE_PROBE_MS = 200L private const val STOP_BOUND_MS = 5_000L +private const val LOCK_PROBE_TIMEOUT_MS = 200L private val SHORT_GATE_TIMEOUT = 200.milliseconds private val detachingRecord = LogRecord( LdkLogLevel.ERROR, @@ -1189,6 +1198,184 @@ class LightningServiceTest : BaseUnitTest() { verify(watchOnlyAccountStore).completeReconciliation(walletIndex = 0) } + @Test + fun `build without paykit server accounts when the node rejects one`() = test { + val account = OnchainWalletAccountConfig(AddressType.NATIVE_SEGWIT, 1u, "xpub-1") + val built = mock() + val attempts = mutableListOf>() + + val result = buildAcceptingPaykitServerAccounts(buildConfig(listOf(account))) { + attempts += it.onchainWalletAccounts + if (it.onchainWalletAccounts.isNotEmpty()) throw BuildException.InvalidSeedBytes("xpub mismatch") + built + } + + assertSame(built, result) + assertEquals(listOf(listOf(account), emptyList()), attempts) + } + + @Test + fun `build fails without retry when no paykit server account is configured`() = test { + var attempts = 0 + + val error = assertFailsWith { + buildAcceptingPaykitServerAccounts(buildConfig(emptyList())) { + attempts++ + throw BuildException.InvalidSeedBytes("bad seed") + } + } + + assertEquals(1, attempts) + assertEquals("InvalidSeedBytes", error.compactType) + } + + @Test + fun `build fails without retry on other build errors`() = test { + var attempts = 0 + + assertFailsWith { + buildAcceptingPaykitServerAccounts( + buildConfig(listOf(OnchainWalletAccountConfig(AddressType.NATIVE_SEGWIT, 1u, "xpub-1"))), + ) { + attempts++ + throw BuildException.WalletSetupFailed("wallet") + } + } + + assertEquals(1, attempts) + } + + @Test + fun `reconciliation loads the other accounts when the node rejects one`() = test { + val rejected = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + val accepted = watchOnlyAccount(accountIndex = 2, walletIndex = 0, enabled = true) + val onchainPayment = mock() + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState(listOf(rejected, accepted), emptyList()), + ) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(onchainPayment) + doThrow(NodeException.InvalidSeedBytes("xpub mismatch")) + .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, rejected.xpub) + + assertTrue(runCatching { sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false) }.isFailure) + + verify(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 2u, accepted.xpub) + verify(onchainPayment).revealReceiveAddressesToAccount( + AddressType.NATIVE_SEGWIT, + 2u, + WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), + ) + } + + @Test + fun `wallet sync runs when reconciliation fails`() = test { + val rejected = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState(listOf(rejected), emptyList()), + ) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + doThrow(NodeException.InvalidSeedBytes("xpub mismatch")) + .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, rejected.xpub) + + sut.sync() + + verify(node, times(1)).syncWallets() + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `wallet sync succeeds and retries a transient account failure on its own`() = test { + val account = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + val status = mock() + whenever(status.isRunning).thenReturn(true) + whenever(node.status()).thenReturn(status) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState(listOf(account), emptyList()), + ) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + var failAdd = true + doAnswer { if (failAdd) throw NodeException.PersistenceFailed("vss write failed") } + .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + val lockFreeDuringSync = mutableListOf() + doAnswer { lockFreeDuringSync += isWatchOnlyLockFree() }.whenever(node).syncWallets() + + sut.sync() + verify(node, times(1)).syncWallets() + + failAdd = false + advanceTimeBy(16.seconds) + runCurrent() + + verify(node, times(2)).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + verify(node, times(2)).syncWallets() + assertEquals(listOf(true, true), lockFreeDuringSync) + + advanceTimeBy(60.seconds) + runCurrent() + verify(node, times(2)).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `stop ends the account retry before releasing the node`() = test { + val account = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState(listOf(account), emptyList()), + ) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + doThrow(NodeException.PersistenceFailed("vss write failed")) + .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + + sut.sync() + sut.stop() + advanceTimeBy(60.seconds) + runCurrent() + + verify(node, times(1)).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + verify(node, times(1)).syncWallets() + } + + @Test + fun `reconciliation skips a node that was released while it waited`() = test { + val account = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenAnswer { + sut.node = null + WatchOnlyAccountReconciliationState(listOf(account), emptyList()) + } + + sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false) + + verify(node, never()).listOnchainWalletAccounts() + verify(node, never()).addOnchainWalletAccount(any(), any(), any()) + } + + // Mutex.withLock on a free mutex returns without suspending; a held one times out. + private fun isWatchOnlyLockFree(): Boolean = runBlocking { + withTimeoutOrNull(LOCK_PROBE_TIMEOUT_MS) { watchOnlyAccountLifecycleCoordinator.withLock { true } } ?: false + } + + private fun buildConfig(accounts: List) = Config( + storageDirPath = "", + network = Network.REGTEST, + listeningAddresses = null, + announcementAddresses = null, + nodeAlias = null, + trustedPeers0conf = emptyList(), + probingLiquidityLimitMultiplier = 1uL, + anchorChannelsConfig = null, + routeParameters = null, + scoringFeeParams = null, + scoringDecayParams = null, + includeUntrustedPendingInSpendable = false, + addressType = AddressType.NATIVE_SEGWIT, + addressTypesToMonitor = emptyList(), + onchainWalletAccounts = accounts, + ) + private fun watchOnlyAccount(accountIndex: Int, walletIndex: Int, enabled: Boolean) = WatchOnlyAccountRecord( id = "account-$accountIndex", walletIndex = walletIndex, diff --git a/app/src/test/java/to/bitkit/services/WatchOnlyAccountXpubDeriverTest.kt b/app/src/test/java/to/bitkit/services/WatchOnlyAccountXpubDeriverTest.kt new file mode 100644 index 0000000000..8e4583e876 --- /dev/null +++ b/app/src/test/java/to/bitkit/services/WatchOnlyAccountXpubDeriverTest.kt @@ -0,0 +1,53 @@ +package to.bitkit.services + +import org.junit.Test +import org.lightningdevkit.ldknode.Network +import to.bitkit.repositories.WatchOnlyAccountError +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class WatchOnlyAccountXpubDeriverTest { + @Test + fun `reads the account xpub from a bitkit-core descriptor`() { + val descriptor = "wpkh([73c5da0a/84'/0'/0']$BIP84_ACCOUNT_0_XPUB/0/*)" + + assertEquals(BIP84_ACCOUNT_0_XPUB, descriptorAccountXpub(descriptor)) + } + + @Test + fun `rejects a descriptor without an xpub`() { + assertFailsWith { + descriptorAccountXpub("wpkh([73c5da0a/84'/0'/0']tpubABC/0/*)") + } + } + + @Test + fun `keeps mainnet version bytes on bitcoin`() { + assertEquals(BIP84_ACCOUNT_0_XPUB, accountXpubForNetwork(BIP84_ACCOUNT_0_XPUB, Network.BITCOIN)) + } + + @Test + fun `uses tpub version bytes on test networks like ldk-node`() { + assertEquals(BIP84_ACCOUNT_0_TPUB, accountXpubForNetwork(BIP84_ACCOUNT_0_XPUB, Network.REGTEST)) + assertEquals(BIP84_ACCOUNT_0_TPUB, accountXpubForNetwork(BIP84_ACCOUNT_0_XPUB, Network.TESTNET)) + } + + @Test + fun `rejects an xpub with a bad checksum`() { + val corrupted = BIP84_ACCOUNT_0_XPUB.dropLast(1) + "W" + + assertFailsWith { + accountXpubForNetwork(corrupted, Network.REGTEST) + } + } + + private companion object { + // BIP84 test vector ("abandon … about", m/84'/0'/0') with xpub and tpub version bytes. + const val BIP84_ACCOUNT_0_XPUB = + "xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3Xyuv" + + "PEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V" + const val BIP84_ACCOUNT_0_TPUB = + "tpubDCxX2sYFS5bDkSe5GKKYHjBW7tgyN1R3UchpLJvdbf54ohxeGRtd8Mb" + + "DUe1cguVHe4vnK68DsuD5MXjxi9EXx16rb9EnNsaF5KT99CinaJz" + } +} diff --git a/changelog.d/next/2006.fixed.md b/changelog.d/next/2006.fixed.md new file mode 100644 index 0000000000..10d7db308b --- /dev/null +++ b/changelog.d/next/2006.fixed.md @@ -0,0 +1 @@ +Fixed connecting Bitkit to Paykit Server failing with "The wallet must be running" right after returning from the browser. diff --git a/journeys/README.md b/journeys/README.md index 71872a67b1..dfb2fefa6f 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -187,6 +187,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `pubky-profile/ring-choice-rows.xml` | same file, journey name and steps — Android names the rows and their lookup spinners differently (see [Identifiers](#identifiers)), checks that rows are disabled by tapping another row instead of reading the snapshot's Targets, needs no second tap on the profile button, and names the import overview by its "Import" title | | `pubky-profile/contact-import-after-leaving.xml` | same file, journey name and steps — Android names the Ring rows differently and has no identifiers on the import overview's profile and friend count, so those steps name the screen text here; see [Identifiers](#identifiers). synonymdev/bitkit-android#1399 adds `ContactImportOverviewImportAll`, the only contact import testTag the journeys use, under its iOS name | | `pubky-profile/contacts-list-loading.xml` | same file, journey name and steps — only the relaunch commands differ | +| `pubky-marketplace/approval-while-node-restarts.xml` | `pubky-marketplace/approval-before-node-starts.xml`, adapted (synonymdev/bitkit-ios#1402) — iOS keeps the node running in the background, so it never restarts on a browser round trip; its journey approves on a cold start before the node has started instead | | `deeplinks/screen-deeplink.xml`, `deeplinks/sheet-deeplink.xml` | not ported — iOS registers the `bitkit` scheme but has no screen or sheet router | | `backup-restore/restore-keeps-tags-and-closed-channels.xml` | not ported yet — iOS already gates uploads across the whole restore (`AppScene.restoreFromMostRecentBackup` sets `BackupService.setRestoring(true)` before the timestamp probe), but still applies the three activity slices in one block (`BackupService.performFullRestoreFromLatestBackup`), which is the half this journey pins; port it with the iOS slice fix | | `shop/gift-card-category-titles.xml` | not ported — iOS still hardcodes the category names, and its route in has no screen deeplink | diff --git a/journeys/pubky-marketplace/README.md b/journeys/pubky-marketplace/README.md index 5b65e9f074..4f3448fe07 100644 --- a/journeys/pubky-marketplace/README.md +++ b/journeys/pubky-marketplace/README.md @@ -16,6 +16,7 @@ The companion journey is shared with iOS; only platform build instructions diffe - `paykit-only-approval.xml` checks Paykit-only consent and cancellation without account creation. - `paykit-reconnect.xml` checks Paykit-only reconnect consent and cancellation without changing the existing service account. +- `approval-while-node-restarts.xml` checks that a Bitcoin watch-only setup approved while the node is stopped or rebuilding completes on the first Authorize and is tracked once the node starts. These visible consent and cancel checks require valid auth URL fixtures but do not authorize a network session. The reconnect journey additionally needs a known active, tracked account in the diff --git a/journeys/pubky-marketplace/approval-while-node-restarts.xml b/journeys/pubky-marketplace/approval-while-node-restarts.xml new file mode 100644 index 0000000000..232a79c3d8 --- /dev/null +++ b/journeys/pubky-marketplace/approval-while-node-restarts.xml @@ -0,0 +1,23 @@ + + + Verifies that a Bitcoin watch-only Paykit Server setup approved while the Lightning node is stopped or + being rebuilt completes on the first Authorize, and that the node tracks the new account once it starts. + Precondition: an isolated wallet with a Pubky identity, on the integration fixture runtime described in the + suite README, and a fresh setup auth URL with x-bitkit-claim=watch-only-account-v1 from the Shop's + Connect Bitkit dialog or the Paykit Server setup fixture. + + + Record the current wallet's watch-only account names and derivation paths + Send Bitkit to the background with the home button. The stop is debounced by 5 seconds and can take up to 30 seconds more; wait until the app log shows "Node stopped" from LightningService + Hold node setup: stall the fixture's VSS backup endpoint (pause its container, or hold reads at a proxy), so the rebuild cannot finish + Open the fixture setup auth URL in the wallet with adb + Without waiting for the wallet to finish syncing, tap Approve on the receiving-details introduction, then Authorize, and complete PIN or biometrics if asked + Verify the success screen appears and no "The wallet must be running before an account can be created" toast is shown + Verify the app log has "Paykit Server account N tracking stored without a node" from WatchOnlyAccountRepo for the new account, written before the success screen. It is logged only when the approval found no node, so it proves the approval did not wait for the build. If the line is missing, the hold did not take effect: fix it and repeat from the background step + Verify the Shop dialog or the fixture reports the setup as complete, and the app log still has no "LDK node setup" line after the latest "Building node…" line + Release the VSS hold + Wait for the wallet to finish syncing, then open the watch-only accounts list in Settings + Verify exactly one new account was added, named after the requesting service, with tracking on + Verify the app log shows the node loaded that account index ("Registered derived on-chain wallet account" or "Loaded configured wallet for OnchainWalletAccount" with its account_index) and no "Provided xpub does not match the node's master seed" error + +