Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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"
}
}
34 changes: 28 additions & 6 deletions app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,7 +41,6 @@ sealed class WatchOnlyAccountError : AppError() {
class AuthorizationAccountMissing : WatchOnlyAccountError()
class InvalidAccountName : WatchOnlyAccountError()
class InvalidExtendedPublicKey : WatchOnlyAccountError()
class NodeUnavailable : WatchOnlyAccountError()
}

class WatchOnlyAccountAuthorizationStartError(
Expand All @@ -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<List<WatchOnlyAccountRecord>> = store.data.map { it.accounts }
val currentWalletAccounts: Flow<List<WatchOnlyAccountRecord>> = accounts.map { accounts ->
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -313,6 +334,7 @@ class WatchOnlyAccountRepo @Inject constructor(
}

companion object {
private const val TAG = "WatchOnlyAccountRepo"
private const val MAX_NAME_LENGTH = 64
}
}
Expand Down
135 changes: 117 additions & 18 deletions app/src/main/java/to/bitkit/services/LightningService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand All @@ -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) {
Expand All @@ -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)
}
}
Expand All @@ -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.
Expand Down Expand Up @@ -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) {
Expand All @@ -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 {
Expand Down
Loading
Loading