diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index bced21a4c..5f2b166b5 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,32 @@ 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. + 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 +742,7 @@ class LightningService: NodeLifecycleService { } #if !BITKIT_NOTIFICATION_EXTENSION - try await reconcileWatchOnlyAccounts() + try await Self.reconcileBeforeSync { try await self.reconcileWatchOnlyAccounts() } #endif Logger.debug("Syncing LDK...") @@ -734,14 +766,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 +798,12 @@ 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) + // 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 } try await ServiceQueue.background(.ldk) { @@ -821,22 +873,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/Bitkit/Services/WatchOnlyAccountService.swift b/Bitkit/Services/WatchOnlyAccountService.swift index e99eb1536..b85f1a676 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/LightningServiceConfigTests.swift b/BitkitTests/LightningServiceConfigTests.swift index 5dae72e5d..145a36009 100644 --- a/BitkitTests/LightningServiceConfigTests.swift +++ b/BitkitTests/LightningServiceConfigTests.swift @@ -3,6 +3,65 @@ import LDKNode 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")] + 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) diff --git a/BitkitTests/WatchOnlyAccountServiceTests.swift b/BitkitTests/WatchOnlyAccountServiceTests.swift index 5dac84a6a..efba0884f 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,65 @@ 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" + /// 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" + + 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: 1 + ) + + XCTAssertEqual(try WatchOnlyAccountClaimCodec.accountXpub(fromDescriptor: descriptor, network: .bitcoin), mainnetAccount1Xpub) + } + // MARK: - serializedXpub /// Vectors below are bitkit-core's own, from `src/modules/onchain/extended_pubkey.rs` @ v0.4.2, diff --git a/changelog.d/next/1402.fixed.md b/changelog.d/next/1402.fixed.md new file mode 100644 index 000000000..bbac9671b --- /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. diff --git a/journeys/pubky-marketplace/README.md b/journeys/pubky-marketplace/README.md index d50fa37ee..dce0af642 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 000000000..4db1776cc --- /dev/null +++ b/journeys/pubky-marketplace/approval-before-node-starts.xml @@ -0,0 +1,24 @@ + + + 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 + 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 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 + +