From b421014d3828fd00cbc32dca91afc5df6fceec55 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 09:10:45 -0300 Subject: [PATCH 1/8] fix: approve pubky watch-only setup without the node Co-Authored-By: Claude Opus 5.5 --- Bitkit/Services/LightningService.swift | 28 +++++++-- Bitkit/Services/WatchOnlyAccountService.swift | 48 ++++++++++++++++ .../WatchOnlyAccountServiceTests.swift | 57 +++++++++++++++++++ journeys/pubky-marketplace/README.md | 3 + .../approval-before-node-starts.xml | 20 +++++++ 5 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 journeys/pubky-marketplace/approval-before-node-starts.xml diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index bced21a4cf..0784ef3593 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -734,14 +734,30 @@ class LightningService: NodeLifecycleService { } } + /// Derives the account xpub from the wallet mnemonic instead of asking the node, so a Pubky auth approval does not + /// depend on the node being built and started. The result must equal `Node.exportOnchainWalletAccountXpub`, which + /// `Node.addOnchainWalletAccount` compares as a string; see `WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor:network:)`. func exportWatchOnlyAccountXpub(accountIndex: UInt32, addressType: LDKNode.AddressType) async throws -> String { - guard let node else { - throw AppError(serviceError: .nodeNotSetup) + guard addressType == .nativeSegwit else { + throw WatchOnlyAccountError.invalidExtendedPublicKey } + let walletIndex = currentWalletIndex + guard let mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: walletIndex)) else { + throw CustomServiceError.mnemonicNotFound + } + let passphraseRaw = try Keychain.loadString(key: .bip39Passphrase(index: walletIndex)) + let passphrase = passphraseRaw?.isEmpty == true ? nil : passphraseRaw - return try await ServiceQueue.background(.ldk) { - try node.exportOnchainWalletAccountXpub(addressType: addressType, accountIndex: accountIndex) + let descriptor = try await ServiceQueue.background(.core) { + try BitkitCore.deriveOnchainDescriptor( + mnemonicPhrase: mnemonic, + network: Env.bitkitCoreNetwork, + bip39Passphrase: passphrase, + accountType: .nativeSegwit, + accountIndex: accountIndex + ) } + return try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: Env.network) } func setWatchOnlyAccountTracking( @@ -750,8 +766,10 @@ class LightningService: NodeLifecycleService { xpub: String, enabled: Bool ) async throws { + // Without a node (not built yet, or stopped) only the caller's store changes: the next build loads tracked + // accounts from the store, and `reconcileWatchOnlyAccounts` on start adds or removes any it missed. guard let node else { - throw AppError(serviceError: .nodeNotSetup) + return } try await ServiceQueue.background(.ldk) { diff --git a/Bitkit/Services/WatchOnlyAccountService.swift b/Bitkit/Services/WatchOnlyAccountService.swift index e99eb15364..b85f1a6768 100644 --- a/Bitkit/Services/WatchOnlyAccountService.swift +++ b/Bitkit/Services/WatchOnlyAccountService.swift @@ -950,6 +950,54 @@ enum WatchOnlyAccountClaimCodec { [0x04, 0x35, 0x87, 0xCF], ] + private static let testnetXpubVersion: [UInt8] = [0x04, 0x35, 0x87, 0xCF] + + /// The account xpub in a bitkit-core `deriveOnchainDescriptor` result, with the version bytes ldk-node uses for + /// `network`. bitkit-core always serializes with mainnet `xpub` bytes; ldk-node's + /// `exportOnchainWalletAccountXpub` uses `tpub` on every test network, and `addOnchainWalletAccount` compares + /// the strings exactly. + static func accountXpub(fromDescriptor descriptor: String, network: LDKNode.Network) throws -> String { + guard let start = descriptor.firstIndex(of: "]") else { + throw WatchOnlyAccountError.invalidExtendedPublicKey + } + let key = descriptor[descriptor.index(after: start)...].prefix { $0 != "/" } + guard key.hasPrefix("xpub") else { + throw WatchOnlyAccountError.invalidExtendedPublicKey + } + let xpub = String(key) + guard network != .bitcoin else { + return xpub + } + + let payload = try base58CheckDecode(xpub) + guard payload.count == serializedXpubLength else { + throw WatchOnlyAccountError.invalidExtendedPublicKey + } + return base58CheckEncode(Data(testnetXpubVersion) + payload.dropFirst(4)) + } + + private static func base58CheckEncode(_ payload: Data) -> String { + let checksum = Data(SHA256.hash(data: Data(SHA256.hash(data: payload)))).prefix(4) + let bytes = [UInt8](payload + checksum) + var digits: [UInt8] = [0] + for byte in bytes { + var carry = Int(byte) + for index in digits.indices.reversed() { + carry += Int(digits[index]) << 8 + digits[index] = UInt8(carry % 58) + carry /= 58 + } + while carry > 0 { + digits.insert(UInt8(carry % 58), at: 0) + carry /= 58 + } + } + let leadingZeros = bytes.prefix { $0 == 0 }.count + let significant = digits.drop { $0 == 0 } + let encoded = [UInt8](repeating: base58Alphabet[0], count: leadingZeros) + significant.map { base58Alphabet[Int($0)] } + return String(decoding: encoded, as: UTF8.self) + } + private static let base58Alphabet = Array("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".utf8) private static func base58CheckDecode(_ string: String) throws -> Data { diff --git a/BitkitTests/WatchOnlyAccountServiceTests.swift b/BitkitTests/WatchOnlyAccountServiceTests.swift index 5dac84a6a7..6f9e604e8f 100644 --- a/BitkitTests/WatchOnlyAccountServiceTests.swift +++ b/BitkitTests/WatchOnlyAccountServiceTests.swift @@ -1,4 +1,5 @@ @testable import Bitkit +import BitkitCore import CryptoKit import LDKNode import Paykit @@ -88,6 +89,62 @@ final class WatchOnlyAccountServiceTests: XCTestCase { } } + // MARK: - accountXpub(fromDescriptor:network:) + + /// BIP84 test vector ("abandon … about", m/84'/0'/0') with xpub and tpub version bytes. + private let bip84Account0Xpub = + "xpub6CatWdiZiodmUeTDp8LT5or8nmbKNcuyvz7WyksVFkKB4RHwCD3XyuvPEbvqAQY3rAPshWcMLoP2fMFMKHPJ4ZeZXYVUhLv1VMrjPC7PW6V" + private let bip84Account0Tpub = + "tpubDCxX2sYFS5bDkSe5GKKYHjBW7tgyN1R3UchpLJvdbf54ohxeGRtd8MbDUe1cguVHe4vnK68DsuD5MXjxi9EXx16rb9EnNsaF5KT99CinaJz" + /// m/84'/1'/1' of the same mnemonic with tpub version bytes, as ldk-node exports it on regtest; derived independently of bitkit-core. + private let regtestAccount1Tpub = + "tpubDC8msFGeGuwnP2xwTZBBZSie1BLgRAkJhgzpFYTdpGgZNzguXQhNDVWp7mJbHJUjQQvV2myLU9dkx67a7VAUnzY7yT7nvhHj7FgS4oNivvq" + private let abandonMnemonic = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" + + func testAccountXpubKeepsMainnetVersionOnBitcoin() throws { + let descriptor = "wpkh([73c5da0a/84'/0'/0']\(bip84Account0Xpub)/0/*)" + + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .bitcoin), bip84Account0Xpub) + } + + func testAccountXpubUsesTpubVersionOnTestNetworks() throws { + let descriptor = "wpkh([73c5da0a/84'/1'/0']\(bip84Account0Xpub)/0/*)" + + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .regtest), bip84Account0Tpub) + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .testnet), bip84Account0Tpub) + } + + func testAccountXpubRejectsDescriptorWithoutXpub() { + XCTAssertThrowsError(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: "wpkh(tpubABC/0/*)", network: .regtest)) { + XCTAssertEqual($0 as? WatchOnlyAccountError, .invalidExtendedPublicKey) + } + } + + func testCoreDerivationMatchesTheRegtestAccountXpubLdkNodeExports() throws { + let descriptor = try BitkitCore.deriveOnchainDescriptor( + mnemonicPhrase: abandonMnemonic, + network: .regtest, + bip39Passphrase: nil, + accountType: .nativeSegwit, + accountIndex: 1 + ) + + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .regtest), regtestAccount1Tpub) + } + + func testCoreDerivationMatchesTheMainnetAccountXpub() throws { + let descriptor = try BitkitCore.deriveOnchainDescriptor( + mnemonicPhrase: abandonMnemonic, + network: .bitcoin, + bip39Passphrase: nil, + accountType: .nativeSegwit, + accountIndex: 0 + ) + + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .bitcoin), bip84Account0Xpub) + } + // MARK: - serializedXpub /// Vectors below are bitkit-core's own, from `src/modules/onchain/extended_pubkey.rs` @ v0.4.2, diff --git a/journeys/pubky-marketplace/README.md b/journeys/pubky-marketplace/README.md index d50fa37eea..dce0af6428 100644 --- a/journeys/pubky-marketplace/README.md +++ b/journeys/pubky-marketplace/README.md @@ -80,6 +80,9 @@ receive the request. without delivering secrets. Open the fixture's `bitkit://pubky-auth/setup` URL with `xcrun simctl openurl ""`. +`approval-before-node-starts.xml` checks that a Bitcoin watch-only setup approved on a cold start, before the +node has started, completes on the first Authorize and is tracked once the node starts. + For successful delivery, use a controlled live relay. Verify a Paykit-only recipient receives the current Paykit key/generation but no account material, and that no account is allocated. For reconnect, the server requests only Paykit access for the existing diff --git a/journeys/pubky-marketplace/approval-before-node-starts.xml b/journeys/pubky-marketplace/approval-before-node-starts.xml new file mode 100644 index 0000000000..e1ec40eb19 --- /dev/null +++ b/journeys/pubky-marketplace/approval-before-node-starts.xml @@ -0,0 +1,20 @@ + + + Verifies that a Bitcoin watch-only Paykit Server setup approved before the Lightning node has started 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 this + 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. iOS keeps the node running in the background, so the window is a cold start. + + + Record the current wallet's watch-only account names and derivation paths + Terminate Bitkit + Open the fixture's bitkit://pubky-auth/setup URL with `xcrun simctl openurl <simulator-id> "<url>"` so it cold-starts the app, and unlock it + Before the app log shows "Node started", tap Approve on the receiving-details introduction + Tap Authorize and complete PIN or biometrics if asked + Verify the success screen appears and no node or wallet error toast is shown + Verify the Shop dialog or the fixture reports the setup as complete + 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 + + From 8566cba9d3eb26150b65ac2d65e876fd3ef4075f Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 09:11:22 -0300 Subject: [PATCH 2/8] chore: add changelog fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/1402.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1402.fixed.md diff --git a/changelog.d/next/1402.fixed.md b/changelog.d/next/1402.fixed.md new file mode 100644 index 0000000000..bbac9671b5 --- /dev/null +++ b/changelog.d/next/1402.fixed.md @@ -0,0 +1 @@ +Fixed connecting Bitkit to Paykit Server failing when approved before the wallet finished starting. From 7e9609d93b35f1173a7b3a041af842a088f795a6 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 09:16:38 -0300 Subject: [PATCH 3/8] test: pin derivation at the first watch-only account Co-Authored-By: Claude Opus 5.5 --- BitkitTests/WatchOnlyAccountServiceTests.swift | 7 +++++-- journeys/pubky-marketplace/approval-before-node-starts.xml | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/BitkitTests/WatchOnlyAccountServiceTests.swift b/BitkitTests/WatchOnlyAccountServiceTests.swift index 6f9e604e8f..efba0884f6 100644 --- a/BitkitTests/WatchOnlyAccountServiceTests.swift +++ b/BitkitTests/WatchOnlyAccountServiceTests.swift @@ -99,6 +99,9 @@ final class WatchOnlyAccountServiceTests: XCTestCase { /// m/84'/1'/1' of the same mnemonic with tpub version bytes, as ldk-node exports it on regtest; derived independently of bitkit-core. private let regtestAccount1Tpub = "tpubDC8msFGeGuwnP2xwTZBBZSie1BLgRAkJhgzpFYTdpGgZNzguXQhNDVWp7mJbHJUjQQvV2myLU9dkx67a7VAUnzY7yT7nvhHj7FgS4oNivvq" + /// m/84'/0'/1' of the same mnemonic; ldk-node only accepts watch-only accounts from index 1. Derived independently of bitkit-core. + private let mainnetAccount1Xpub = + "xpub6CatWdiZiodmYVtWLtEQsAg1H9ooS1bmsJUBwQ83FE1Fyk386FWcyicJgEZv3quZSJKA5dh5Lo2PbubMGxCfZtRthV6ST2qquL9w3HSzcUn" private let abandonMnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" @@ -139,10 +142,10 @@ final class WatchOnlyAccountServiceTests: XCTestCase { network: .bitcoin, bip39Passphrase: nil, accountType: .nativeSegwit, - accountIndex: 0 + accountIndex: 1 ) - XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .bitcoin), bip84Account0Xpub) + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .bitcoin), mainnetAccount1Xpub) } // MARK: - serializedXpub diff --git a/journeys/pubky-marketplace/approval-before-node-starts.xml b/journeys/pubky-marketplace/approval-before-node-starts.xml index e1ec40eb19..1da3205df4 100644 --- a/journeys/pubky-marketplace/approval-before-node-starts.xml +++ b/journeys/pubky-marketplace/approval-before-node-starts.xml @@ -16,5 +16,6 @@ Verify the Shop dialog or the fixture reports the setup as complete 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 From 33a52664cadb55dda868a18efbe42443a86549a7 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 09:33:41 -0300 Subject: [PATCH 4/8] fix: start the node when it rejects a paykit account Co-Authored-By: Claude Opus 5.5 --- Bitkit/Services/LightningService.swift | 132 +++++++++++------- BitkitTests/LightningServiceConfigTests.swift | 46 ++++++ 2 files changed, 130 insertions(+), 48 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 0784ef3593..453edf5dab 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -302,35 +302,8 @@ class LightningService: NodeLifecycleService { config.onchainWalletAccounts = try Self.watchOnlyAccountConfigs(walletIndex: walletIndex) #endif - let builder = Builder.fromConfig(config: config) - builder.setCustomLogger(logWriter: LdkLogWriter()) - let resolvedElectrumServerUrl = electrumServerUrl ?? Env.electrumServerUrl - let electrumConfig = ElectrumSyncConfig( - backgroundSyncConfig: .init( - onchainWalletSyncIntervalSecs: Env.walletSyncIntervalSecs, - lightningWalletSyncIntervalSecs: Env.walletSyncIntervalSecs, - feeRateCacheUpdateIntervalSecs: Env.walletSyncIntervalSecs - ), - connectionTimeoutSecs: 10, - additionalWalletFullScanBatchSize: 100, - additionalWalletFullScanStopGap: 1000 - ) - Logger.info("Using Electrum server: \(resolvedElectrumServerUrl)") - builder.setChainSourceElectrum(serverUrl: resolvedElectrumServerUrl, config: electrumConfig) - - // Set pathfinding scores source from external scorer - if let scorerUrl = Env.ldkScorerUrl { - Logger.info("Setting pathfinding scores source from scorer url: \(scorerUrl)") - builder.setPathfindingScoresSource(url: scorerUrl) - } - - builder.setScoringFeeParams(params: Self.scoringFeeParameters(config: config)) - - // Configure gossip source from current settings - configureGossipSource(builder: builder, rgsServerUrl: rgsServerUrl) - Logger.debug("Building node...") let storeId = try await VssStoreIdProvider.shared.getVssStoreId(walletIndex: walletIndex) @@ -339,24 +312,57 @@ class LightningService: NodeLifecycleService { Logger.debug("Building ldk-node with vssUrl: '\(vssUrl)'") Logger.debug("Building ldk-node with lnurlAuthServerUrl: '\(lnurlAuthServerUrl)'") - if let channelMigration { - builder.setChannelDataMigration(migration: channelMigration) - Logger.info("Applied channel migration: \(channelMigration.channelMonitors.count) monitors", context: "Migration") - } - - builder.setEntropyBip39Mnemonic(mnemonic: mnemonic, passphrase: passphrase) - guard !lnurlAuthServerUrl.isEmpty else { throw CustomServiceError.vssAuthRequired } - try await ServiceQueue.background(.ldk) { - let node = try builder.buildWithVssStore( + let entropyMnemonic = mnemonic + let entropyPassphrase = passphrase + let buildNode = { (config: Config) throws -> Node in + let builder = Builder.fromConfig(config: config) + builder.setCustomLogger(logWriter: LdkLogWriter()) + + let electrumConfig = ElectrumSyncConfig( + backgroundSyncConfig: .init( + onchainWalletSyncIntervalSecs: Env.walletSyncIntervalSecs, + lightningWalletSyncIntervalSecs: Env.walletSyncIntervalSecs, + feeRateCacheUpdateIntervalSecs: Env.walletSyncIntervalSecs + ), + connectionTimeoutSecs: 10, + additionalWalletFullScanBatchSize: 100, + additionalWalletFullScanStopGap: 1000 + ) + Logger.info("Using Electrum server: \(resolvedElectrumServerUrl)") + builder.setChainSourceElectrum(serverUrl: resolvedElectrumServerUrl, config: electrumConfig) + + // Set pathfinding scores source from external scorer + if let scorerUrl = Env.ldkScorerUrl { + Logger.info("Setting pathfinding scores source from scorer url: \(scorerUrl)") + builder.setPathfindingScoresSource(url: scorerUrl) + } + + builder.setScoringFeeParams(params: Self.scoringFeeParameters(config: config)) + + // Configure gossip source from current settings + self.configureGossipSource(builder: builder, rgsServerUrl: rgsServerUrl) + + if let channelMigration { + builder.setChannelDataMigration(migration: channelMigration) + Logger.info("Applied channel migration: \(channelMigration.channelMonitors.count) monitors", context: "Migration") + } + + builder.setEntropyBip39Mnemonic(mnemonic: entropyMnemonic, passphrase: entropyPassphrase) + + return try builder.buildWithVssStore( vssUrl: vssUrl, storeId: storeId, lnurlAuthServerUrl: lnurlAuthServerUrl, fixedHeaders: [:] ) + } + + try await ServiceQueue.background(.ldk) { + let node = try Self.buildAcceptingPaykitServerAccounts(config: config, build: buildNode) self.setupLock.withLock { self.configuredNode = (node, resolvedElectrumServerUrl) } } shouldReleaseLightningLock = false @@ -368,6 +374,20 @@ class LightningService: NodeLifecycleService { passphrase = nil } + /// 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. + static func buildAcceptingPaykitServerAccounts(config: Config, build: (Config) throws -> Node) throws -> Node { + do { + return try build(config) + } catch let BuildError.InvalidSeedBytes(message) where !config.onchainWalletAccounts.isEmpty { + Logger.error("Node rejected Paykit Server accounts at build, building without them: \(message)", context: "LightningService") + var fallback = config + fallback.onchainWalletAccounts = [] + return try build(fallback) + } + } + /// Runs after any restart already in progress, so overlapping restarts cannot stop or replace each other's node midway. func restart(electrumServerUrl: String? = nil, rgsServerUrl: String? = nil) async throws { let restart: Task = restartLock.withLock { @@ -710,7 +730,12 @@ class LightningService: NodeLifecycleService { } #if !BITKIT_NOTIFICATION_EXTENSION - try await reconcileWatchOnlyAccounts() + // A Paykit Server account the node rejects must not stop the wallet from syncing; the next sync retries it. + do { + try await reconcileWatchOnlyAccounts() + } catch { + Logger.error(error, context: "Failed to reconcile Paykit Server accounts before sync") + } #endif Logger.debug("Syncing LDK...") @@ -839,22 +864,33 @@ class LightningService: NodeLifecycleService { } } + // One account the node rejects must not keep the others from loading; the first failure is + // rethrown so the reconciliation is retried. + var firstFailure: Error? for config in desiredConfigs { - let isTracked = trackedAccounts.contains { - $0.addressType == config.addressType && $0.accountIndex == config.accountIndex - } - if !isTracked { - try node.addOnchainWalletAccount( + do { + let isTracked = trackedAccounts.contains { + $0.addressType == config.addressType && $0.accountIndex == config.accountIndex + } + if !isTracked { + try node.addOnchainWalletAccount( + addressType: config.addressType, + accountIndex: config.accountIndex, + xpub: config.xpub + ) + } + try node.onchainPayment().revealReceiveAddressesToAccount( addressType: config.addressType, accountIndex: config.accountIndex, - xpub: config.xpub + index: Self.watchOnlyAccountHighestPreRevealedAddressIndex ) + } catch { + Logger.error(error, context: "Failed to load Paykit Server account \(config.accountIndex)") + firstFailure = firstFailure ?? error } - try node.onchainPayment().revealReceiveAddressesToAccount( - addressType: config.addressType, - accountIndex: config.accountIndex, - index: Self.watchOnlyAccountHighestPreRevealedAddressIndex - ) + } + if let firstFailure { + throw firstFailure } } } diff --git a/BitkitTests/LightningServiceConfigTests.swift b/BitkitTests/LightningServiceConfigTests.swift index 5dae72e5d2..4a1d18e381 100644 --- a/BitkitTests/LightningServiceConfigTests.swift +++ b/BitkitTests/LightningServiceConfigTests.swift @@ -3,6 +3,52 @@ import LDKNode import XCTest final class LightningServiceConfigTests: XCTestCase { + private struct BuildAttemptEnded: Error {} + + func testBuildRetriesWithoutPaykitServerAccountsWhenTheNodeRejectsOne() { + var config = LightningService.nodeConfig(walletIndex: 0) + config.onchainWalletAccounts = [OnchainWalletAccountConfig(addressType: .nativeSegwit, accountIndex: 1, xpub: "xpub-1")] + var attempts: [[OnchainWalletAccountConfig]] = [] + + XCTAssertThrowsError(try LightningService.buildAcceptingPaykitServerAccounts(config: config) { config in + attempts.append(config.onchainWalletAccounts) + if !config.onchainWalletAccounts.isEmpty { + throw BuildError.InvalidSeedBytes(message: "xpub mismatch") + } + throw BuildAttemptEnded() + }) { + XCTAssertTrue($0 is BuildAttemptEnded) + } + + XCTAssertEqual(attempts.map(\.count), [1, 0]) + } + + func testBuildDoesNotRetryWithoutPaykitServerAccounts() { + var config = LightningService.nodeConfig(walletIndex: 0) + config.onchainWalletAccounts = [] + var attempts = 0 + + XCTAssertThrowsError(try LightningService.buildAcceptingPaykitServerAccounts(config: config) { _ in + attempts += 1 + throw BuildError.InvalidSeedBytes(message: "bad seed") + }) + + XCTAssertEqual(attempts, 1) + } + + func testBuildDoesNotRetryOnOtherBuildErrors() { + var config = LightningService.nodeConfig(walletIndex: 0) + config.onchainWalletAccounts = [OnchainWalletAccountConfig(addressType: .nativeSegwit, accountIndex: 1, xpub: "xpub-1")] + var attempts = 0 + + XCTAssertThrowsError(try LightningService.buildAcceptingPaykitServerAccounts(config: config) { _ in + attempts += 1 + throw BuildError.WalletSetupFailed(message: "wallet") + }) + + XCTAssertEqual(attempts, 1) + } + func testNodeConfigTrustsNoPeer() { let config = LightningService.nodeConfig(walletIndex: 0) From 00b2de3eb3d6069743ad78b5c6375ab190b22cb5 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 11:56:06 -0300 Subject: [PATCH 5/8] fix: stop a cancelled sync before the wallet sync Co-Authored-By: Claude Opus 5.5 --- Bitkit/Services/LightningService.swift | 19 +++++++++++++------ BitkitTests/LightningServiceConfigTests.swift | 13 +++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 453edf5dab..f43502bbbd 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -374,6 +374,18 @@ class LightningService: NodeLifecycleService { passphrase = nil } + /// Runs `reconcile` before a wallet sync. A Paykit Server account that fails to load must not stop the wallet from + /// syncing, so its error is logged and the next sync retries it; a cancelled caller still stops here. + static func reconcileBeforeSync(_ reconcile: () async throws -> Void) async throws { + do { + try await reconcile() + } catch is CancellationError { + throw CancellationError() + } catch { + Logger.error(error, context: "Failed to reconcile Paykit Server accounts before sync") + } + } + /// 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. @@ -730,12 +742,7 @@ class LightningService: NodeLifecycleService { } #if !BITKIT_NOTIFICATION_EXTENSION - // A Paykit Server account the node rejects must not stop the wallet from syncing; the next sync retries it. - do { - try await reconcileWatchOnlyAccounts() - } catch { - Logger.error(error, context: "Failed to reconcile Paykit Server accounts before sync") - } + try await Self.reconcileBeforeSync { try await self.reconcileWatchOnlyAccounts() } #endif Logger.debug("Syncing LDK...") diff --git a/BitkitTests/LightningServiceConfigTests.swift b/BitkitTests/LightningServiceConfigTests.swift index 4a1d18e381..145a360092 100644 --- a/BitkitTests/LightningServiceConfigTests.swift +++ b/BitkitTests/LightningServiceConfigTests.swift @@ -5,6 +5,19 @@ import XCTest final class LightningServiceConfigTests: XCTestCase { private struct BuildAttemptEnded: Error {} + func testReconcileBeforeSyncContinuesAfterAnAccountFailure() async throws { + try await LightningService.reconcileBeforeSync { throw BuildAttemptEnded() } + } + + func testReconcileBeforeSyncStopsWhenCancelled() async { + do { + try await LightningService.reconcileBeforeSync { throw CancellationError() } + XCTFail("Expected cancellation to propagate") + } catch { + XCTAssertTrue(error is CancellationError) + } + } + func testBuildRetriesWithoutPaykitServerAccountsWhenTheNodeRejectsOne() { var config = LightningService.nodeConfig(walletIndex: 0) config.onchainWalletAccounts = [OnchainWalletAccountConfig(addressType: .nativeSegwit, accountIndex: 1, xpub: "xpub-1")] From e8fac52d82a76aca1e5115cebc68c38f8e8af2d5 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 11:56:07 -0300 Subject: [PATCH 6/8] docs: require the approval to finish before node setup Co-Authored-By: Claude Opus 5.5 --- journeys/pubky-marketplace/approval-before-node-starts.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/journeys/pubky-marketplace/approval-before-node-starts.xml b/journeys/pubky-marketplace/approval-before-node-starts.xml index 1da3205df4..b7d03f7d7d 100644 --- a/journeys/pubky-marketplace/approval-before-node-starts.xml +++ b/journeys/pubky-marketplace/approval-before-node-starts.xml @@ -13,6 +13,7 @@ Before the app log shows "Node started", tap Approve on the receiving-details introduction Tap Authorize and complete PIN or biometrics if asked Verify the success screen appears and no node or wallet error toast is shown + Right after the success screen appears, verify the app log for this launch has no "LDK node setup" line yet, so the approval completed before the node existed. If the node was set up first, the run is inconclusive: repeat it from the terminate step Verify the Shop dialog or the fixture reports the setup as complete 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 From 823dc2934a93fa13ec861cb3897bbef242946066 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 24 Nov 2026 14:01:52 -0300 Subject: [PATCH 7/8] test: prove approval without a node from a direct log line Co-Authored-By: Claude Opus 5.5 --- Bitkit/Services/LightningService.swift | 2 ++ journeys/pubky-marketplace/approval-before-node-starts.xml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index f43502bbbd..5f2b166b51 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -801,6 +801,8 @@ class LightningService: NodeLifecycleService { // Without a node (not built yet, or stopped) only the caller's store changes: the next build loads tracked // accounts from the store, and `reconcileWatchOnlyAccounts` on start adds or removes any it missed. guard let node else { + // Journeys read this line to prove an approval finished before the node was built. + Logger.info("Paykit Server account \(accountIndex) tracking stored without a node; it loads when the node starts") return } diff --git a/journeys/pubky-marketplace/approval-before-node-starts.xml b/journeys/pubky-marketplace/approval-before-node-starts.xml index b7d03f7d7d..1f1e1467ff 100644 --- a/journeys/pubky-marketplace/approval-before-node-starts.xml +++ b/journeys/pubky-marketplace/approval-before-node-starts.xml @@ -13,7 +13,7 @@ Before the app log shows "Node started", tap Approve on the receiving-details introduction Tap Authorize and complete PIN or biometrics if asked Verify the success screen appears and no node or wallet error toast is shown - Right after the success screen appears, verify the app log for this launch has no "LDK node setup" line yet, so the approval completed before the node existed. If the node was set up first, the run is inconclusive: repeat it from the terminate step + Verify the app log for this launch has "Paykit Server account N tracking stored without a node" 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 node setup. If the line is missing, the node was set up first and the run is inconclusive: repeat it from the terminate step Verify the Shop dialog or the fixture reports the setup as complete 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 From 12186986647c121630fc67653dd0157fb16d2fbd Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 05:36:56 -0300 Subject: [PATCH 8/8] docs: hold node setup through approval in the j1 journey Co-Authored-By: Claude Opus 5.5 --- journeys/pubky-marketplace/approval-before-node-starts.xml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/journeys/pubky-marketplace/approval-before-node-starts.xml b/journeys/pubky-marketplace/approval-before-node-starts.xml index 1f1e1467ff..4db1776cc8 100644 --- a/journeys/pubky-marketplace/approval-before-node-starts.xml +++ b/journeys/pubky-marketplace/approval-before-node-starts.xml @@ -9,12 +9,14 @@ Record the current wallet's watch-only account names and derivation paths Terminate Bitkit + Hold node setup: stall the fixture's VSS backup endpoint (pause its container, or hold reads at a proxy), so the node build cannot finish Open the fixture's bitkit://pubky-auth/setup URL with `xcrun simctl openurl <simulator-id> "<url>"` so it cold-starts the app, and unlock it Before the app log shows "Node started", tap Approve on the receiving-details introduction Tap Authorize and complete PIN or biometrics if asked Verify the success screen appears and no node or wallet error toast is shown - Verify the app log for this launch has "Paykit Server account N tracking stored without a node" 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 node setup. If the line is missing, the node was set up first and the run is inconclusive: repeat it from the terminate step - Verify the Shop dialog or the fixture reports the setup as complete + Verify the app log for this launch has "Paykit Server account N tracking stored without a node" 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 node setup. If the line is missing, the hold did not take effect: fix it and repeat from the terminate step + Verify the Shop dialog or the fixture reports the setup as complete, and the app log still has no "LDK node setup" line for this launch + 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