From f53eb9dd9211b889b98de96596b5745dbcb90275 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 10:58:03 +0100 Subject: [PATCH 1/3] fix: find a restored wallet's exit funding past its backed-up index --- Bitkit/Managers/SparkExitManager.swift | 32 +++++++++---------- .../Services/SparkExit/SparkExitFunding.swift | 11 ++++--- BitkitTests/SparkExitFundingIndexTests.swift | 15 ++++++++- 3 files changed, 35 insertions(+), 23 deletions(-) diff --git a/Bitkit/Managers/SparkExitManager.swift b/Bitkit/Managers/SparkExitManager.swift index a9bf5c3c0..5f944853c 100644 --- a/Bitkit/Managers/SparkExitManager.swift +++ b/Bitkit/Managers/SparkExitManager.swift @@ -1235,12 +1235,13 @@ final class SparkExitManager { return try await recoverFunding(recovery, now: now) ?? 0 } - /// Finds earlier exits' funding after a restore. With no counter kept and no record, scans for the next index and - /// keeps it; with a counter a restore brought back, reads each funding address below it, once. Each funding address - /// that still holds coins and nothing watches is listed as kept change, so it is watched for good. Throws when a - /// read fails, keeping no counter and the restore pending, so it runs again on the next start. + /// Finds earlier exits' funding after a restore. Scans for the next index and keeps it: from 0 with no counter kept + /// and no record, else from the counter a restore brought back, reading each funding address below it once too. + /// Each funding address that still holds coins and nothing watches is listed as kept change, so it is watched for + /// good. Throws when a read or that listing fails, keeping no counter and the restore pending, so it runs again on + /// the next start. /// - /// Returns the index a scan found, nil when there was nothing to scan. + /// Returns the index the scan found, nil when no restore was pending. @discardableResult static func recoverFunding(_ recovery: FundingRecovery, now: Date) async throws -> UInt32? { let defaults = recovery.defaults @@ -1257,17 +1258,16 @@ final class SparkExitManager { return found } var used: [UInt32] = [] - var scanned: UInt32? - if kept == nil { - scanned = try await SparkExitMath.scanNextFundingIndex { index in - let isUsed = try await chain.isAddressUsed(address: funding(index).address) - if isUsed { - used.append(index) - } - return isUsed + let restored = kept.map { UInt32(clamping: max(0, $0)) } + // A restored index can predate the last exit's funding, when its backup didn't land, so the scan goes on from it. + let scanned = try await SparkExitMath.scanNextFundingIndex(from: restored ?? 0) { index in + let isUsed = try await chain.isAddressUsed(address: funding(index).address) + if isUsed { + used.append(index) } + return isUsed } - let candidates = kept.map { Array(0 ..< UInt32(clamping: max(0, $0))) } ?? used + let candidates = restored.map { Array(0 ..< $0) + used } ?? used let watched = Set(((try? recovery.earlierAddressStore.load()) ?? []).map(\.address) + (recovery.record?.funding.map(\.address) ?? [])) for index in candidates { let (address, path) = try funding(index) @@ -1276,9 +1276,7 @@ final class SparkExitManager { guard sats > 0 else { continue } try recovery.earlierAddressStore.add(SparkExitEarlierAddress(address: address, path: path, kind: .keptChange, sats: sats, date: now)) } - if let scanned { - defaults.set(max(defaults.integer(forKey: recovery.key), Int(scanned)), forKey: recovery.key) - } + defaults.set(max(defaults.integer(forKey: recovery.key), Int(scanned)), forKey: recovery.key) defaults.removeObject(forKey: recovery.pendingKey) return scanned } diff --git a/Bitkit/Services/SparkExit/SparkExitFunding.swift b/Bitkit/Services/SparkExit/SparkExitFunding.swift index a287b0c44..ad72c6b23 100644 --- a/Bitkit/Services/SparkExit/SparkExitFunding.swift +++ b/Bitkit/Services/SparkExit/SparkExitFunding.swift @@ -585,11 +585,12 @@ enum SparkExitMath { /// The most funding addresses one scan reads, even when a host reports every one used. static let fundingScanMaxAddresses: UInt32 = 1000 - /// The funding index past the last one `isUsed` reports used, read from 0 until `fundingScanGapLimit` unused ones - /// follow it, for a wallet that kept no index, such as one restored from the phrase or an older backup. - static func scanNextFundingIndex(isUsed: (UInt32) async throws -> Bool) async rethrows -> UInt32 { - var next: UInt32 = 0 - var index: UInt32 = 0 + /// The funding index past the last one `isUsed` reports used, read from `start` until `fundingScanGapLimit` unused + /// ones follow it: from 0 for a wallet that kept no index, such as one restored from the phrase or an older backup, + /// and from a restored index, which can predate the last exit's funding. + static func scanNextFundingIndex(from start: UInt32 = 0, isUsed: (UInt32) async throws -> Bool) async rethrows -> UInt32 { + var next = start + var index = start while index < next + fundingScanGapLimit, index < fundingScanMaxAddresses { if try await isUsed(index) { next = index + 1 diff --git a/BitkitTests/SparkExitFundingIndexTests.swift b/BitkitTests/SparkExitFundingIndexTests.swift index a77c690cb..0e96bd12b 100644 --- a/BitkitTests/SparkExitFundingIndexTests.swift +++ b/BitkitTests/SparkExitFundingIndexTests.swift @@ -220,11 +220,24 @@ final class SparkExitFundingIndexTests: XCTestCase { try await SparkExitManager.recoverFunding(recovery, now: now) XCTAssertEqual(try earlierAddressStore.load(), [keptCoins(2, sats: 5000)], "the lost funding goes unwatched") - XCTAssertTrue(chain.addressReads.isEmpty, "a restored counter needs no scan for the next index") + XCTAssertEqual(chain.addressReads, (3 ..< 23).map(address), "a restored counter is scanned forward from, once") XCTAssertNil(defaults.object(forKey: pendingKey), "every start reads the funding addresses again") XCTAssertEqual(defaults.integer(forKey: key), 3) } + func testARestoredCounterThatPredatesTheLastExitsFundingFindsItsCoins() async throws { + // The backup carrying counter 4 never landed: the exit that funded address 3 is lost with it. + SparkExitFundingIndexes.restore(["regtest/wallet0": 3], into: defaults) + chain.usedAddresses = [address(0), address(1), address(2), address(3)] + chain.utxosByAddress[address(3)] = [SparkExitFixtures.utxo("lost", value: 7000)] + + let next = try await SparkExitManager.recoverFunding(recovery, now: now) + + XCTAssertEqual(next, 4) + XCTAssertEqual(try earlierAddressStore.load(), [keptCoins(3, sats: 7000)], "address 3's coins stay hidden") + XCTAssertEqual(defaults.integer(forKey: key), 4, "the next exit reuses address 3") + } + func testAKeptCounterWithNoRestorePendingReadsNoFundingAddress() async throws { defaults.set(3, forKey: key) chain.utxosByAddress[address(2)] = [SparkExitFixtures.utxo("lost", value: 5000)] From 38447fb021865bac2031a5afa31b5976c6911483 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 12:33:03 +0100 Subject: [PATCH 2/3] fix: scan a pending restore before quoting and past a forgotten exit's address --- Bitkit/Managers/SparkExitManager.swift | 26 +++++---- .../Services/SparkExit/SparkExitFunding.swift | 9 ++- BitkitTests/SparkExitFundingIndexTests.swift | 55 ++++++++++++++++++- 3 files changed, 73 insertions(+), 17 deletions(-) diff --git a/Bitkit/Managers/SparkExitManager.swift b/Bitkit/Managers/SparkExitManager.swift index 5f944853c..b4dcd3d7a 100644 --- a/Bitkit/Managers/SparkExitManager.swift +++ b/Bitkit/Managers/SparkExitManager.swift @@ -976,7 +976,8 @@ final class SparkExitManager { markSettled: { try? await transfers.markSettled(id: $0) } ) UserDefaults.standard.set(walletIndex, forKey: Self.walletIndexKey) - UserDefaults.standard.set(Int(fundingIndex) + 1, forKey: fundingIndexKey) + // Never lowers a counter a restore's scan moved past this quote's index. + UserDefaults.standard.set(max(UserDefaults.standard.integer(forKey: fundingIndexKey), Int(fundingIndex) + 1), forKey: fundingIndexKey) SettingsViewModel.shared.notifyAppStateChanged() pendingFundingIndex = nil startingCreatedAt = record.createdAt @@ -1188,8 +1189,9 @@ final class SparkExitManager { /// The funding key index of the next exit: one no exit of this wallet used, so leftover of an earlier exit never /// mixes into a new one. A scan's result rides the next metadata backup. private func nextFundingIndex() async throws -> UInt32 { - let wasKept = UserDefaults.standard.object(forKey: fundingIndexKey) != nil - let index = try await Self.nextFundingIndex(fundingRecovery, now: Date()) + let recovery = fundingRecovery + let wasKept = recovery.defaults.object(forKey: recovery.key) != nil && !recovery.defaults.bool(forKey: recovery.pendingKey) + let index = try await Self.nextFundingIndex(recovery, now: Date()) if !wasKept { SettingsViewModel.shared.notifyAppStateChanged() } @@ -1224,15 +1226,12 @@ final class SparkExitManager { ) } - /// From the counter the last start left and the stored record. With neither, as after a restore from the phrase or - /// from a backup older than the counter, from a scan of the funding addresses first. A scan the chain fails keeps - /// nothing. + /// From the counter the last start left and the stored record. While a restore is pending, as after a restore from + /// the phrase or from a backup, from a scan of the funding addresses first: a restored counter can predate the last + /// exit's funding. A scan the chain fails throws and keeps nothing, so no quote reuses that funding address. static func nextFundingIndex(_ recovery: FundingRecovery, now: Date) async throws -> UInt32 { - let defaults = recovery.defaults - if defaults.object(forKey: recovery.key) != nil || recovery.record != nil { - return SparkExitMath.nextFundingIndex(counter: defaults.integer(forKey: recovery.key), record: recovery.record) - } - return try await recoverFunding(recovery, now: now) ?? 0 + try await recoverFunding(recovery, now: now) + return SparkExitMath.nextFundingIndex(counter: recovery.defaults.integer(forKey: recovery.key), record: recovery.record) } /// Finds earlier exits' funding after a restore. Scans for the next index and keeps it: from 0 with no counter kept @@ -1268,7 +1267,10 @@ final class SparkExitManager { return isUsed } let candidates = restored.map { Array(0 ..< $0) + used } ?? used - let watched = Set(((try? recovery.earlierAddressStore.load()) ?? []).map(\.address) + (recovery.record?.funding.map(\.address) ?? [])) + // A forgotten exit's funding address is no longer watched once the scan moves the counter past it, so one that + // holds coins is listed again, as kept change. + let listed = ((try? recovery.earlierAddressStore.load()) ?? []).filter { $0.kind != .cancelledFunding } + let watched = Set(listed.map(\.address) + (recovery.record?.funding.map(\.address) ?? [])) for index in candidates { let (address, path) = try funding(index) guard !watched.contains(address) else { continue } diff --git a/Bitkit/Services/SparkExit/SparkExitFunding.swift b/Bitkit/Services/SparkExit/SparkExitFunding.swift index ad72c6b23..709e5bf0b 100644 --- a/Bitkit/Services/SparkExit/SparkExitFunding.swift +++ b/Bitkit/Services/SparkExit/SparkExitFunding.swift @@ -582,7 +582,7 @@ enum SparkExitMath { /// Unused funding addresses a scan reads past the last used one before it stops. static let fundingScanGapLimit: UInt32 = 20 - /// The most funding addresses one scan reads, even when a host reports every one used. + /// The most funding addresses one scan reads from where it starts, even when a host reports every one used. static let fundingScanMaxAddresses: UInt32 = 1000 /// The funding index past the last one `isUsed` reports used, read from `start` until `fundingScanGapLimit` unused @@ -591,7 +591,9 @@ enum SparkExitMath { static func scanNextFundingIndex(from start: UInt32 = 0, isUsed: (UInt32) async throws -> Bool) async rethrows -> UInt32 { var next = start var index = start - while index < next + fundingScanGapLimit, index < fundingScanMaxAddresses { + let end = start.addingReportingOverflow(fundingScanMaxAddresses) + let limit = end.overflow ? UInt32.max : end.partialValue + while index < next + fundingScanGapLimit, index < limit { if try await isUsed(index) { next = index + 1 } @@ -746,7 +748,8 @@ enum SparkExitFundingIndexes { let defaultsKey = defaultsKey(network: String(parts[0]), walletIndex: wallet) let local = defaults.object(forKey: defaultsKey) as? Int ?? 0 defaults.set(max(local, index), forKey: defaultsKey) - // The exit then looks once for funding addresses below it that still hold coins and nothing watches. + // The exit then looks once for funding addresses that still hold coins and nothing watches: each one below + // it, and those a scan forward from it finds used, which also moves the counter past them. defaults.set(true, forKey: recoveryPendingKey(network: String(parts[0]), walletIndex: wallet)) } } diff --git a/BitkitTests/SparkExitFundingIndexTests.swift b/BitkitTests/SparkExitFundingIndexTests.swift index 0e96bd12b..7bfe609e6 100644 --- a/BitkitTests/SparkExitFundingIndexTests.swift +++ b/BitkitTests/SparkExitFundingIndexTests.swift @@ -102,7 +102,7 @@ final class SparkExitFundingIndexTests: XCTestCase { XCTAssertEqual(defaults.object(forKey: key) as? Int, 3, "the next quote scans again") } - func testAFundingIndexRestoredFromTheBackupIsUsedWithoutAScan() async throws { + func testAFundingIndexRestoredFromTheBackupIsOnlyScannedForwardFrom() async throws { defaults.set(3, forKey: key) let backup = try roundTrip(cache(sparkExitNextFundingIndexes: SparkExitFundingIndexes.backup(defaults))) restore(backup) @@ -112,7 +112,33 @@ final class SparkExitFundingIndexTests: XCTestCase { XCTAssertEqual(backup.sparkExitNextFundingIndexes, ["regtest/wallet0": 3], "keyed as bitkit-android keys it") XCTAssertEqual(next, 3) - XCTAssertTrue(chain.addressReads.isEmpty, "a backed-up index needs no scan") + XCTAssertEqual(chain.addressReads, (3 ..< 3 + SparkExitMath.fundingScanGapLimit).map(address), "a backed-up index needs no scan below it") + } + + func testAQuoteWhileARestoreIsPendingScansPastTheRestoredCounterFirst() async throws { + // The backup carrying counter 4 never landed: address 3 still holds the lost exit's coins. + SparkExitFundingIndexes.restore(["regtest/wallet0": 3], into: defaults) + chain.usedAddresses = [address(0), address(1), address(2), address(3)] + chain.utxosByAddress[address(3)] = [SparkExitFixtures.utxo("lost", value: 7000)] + + let next = try await nextFundingIndex() + + XCTAssertEqual(next, 4, "the next exit funds from the lost exit's address") + XCTAssertEqual(try earlierAddressStore.load(), [keptCoins(3, sats: 7000)]) + XCTAssertFalse(defaults.bool(forKey: pendingKey)) + } + + func testAQuoteWhileARestoreIsPendingFailsWhenTheScanFails() async { + SparkExitFundingIndexes.restore(["regtest/wallet0": 3], into: defaults) + chain.isAddressReadUnreadable = true + + do { + _ = try await nextFundingIndex() + XCTFail("a quote could fund from the address a lost exit used") + } catch {} + + XCTAssertEqual(defaults.integer(forKey: key), 3) + XCTAssertTrue(defaults.bool(forKey: pendingKey), "the restore no longer runs again") } func testARestoreKeepsTheHigherIndexOfTheDeviceAndTheBackup() { @@ -238,6 +264,31 @@ final class SparkExitFundingIndexTests: XCTestCase { XCTAssertEqual(defaults.integer(forKey: key), 4, "the next exit reuses address 3") } + func testARestoredCounterAtAForgottenExitsAddressListsItsLatePaymentAsKeptChange() async throws { + // The exit at address 3 was forgotten before funding, so the counter went back to 3; a payment came late. + try earlierAddressStore.add(SparkExitEarlierAddress(address: address(3), path: path(3), kind: .cancelledFunding, sats: nil, date: now)) + SparkExitFundingIndexes.restore(["regtest/wallet0": 3], into: defaults) + chain.usedAddresses = [address(0), address(1), address(2), address(3)] + chain.utxosByAddress[address(3)] = [SparkExitFixtures.utxo("late", value: 4000)] + + let next = try await SparkExitManager.recoverFunding(recovery, now: now) + + XCTAssertEqual(next, 4) + XCTAssertEqual(try earlierAddressStore.load(), [keptCoins(3, sats: 4000)], "the late payment is watched only until its cancel expires") + } + + func testARestoredCounterPastTheScanCeilingStillScansForward() async throws { + let ceiling = Int(SparkExitMath.fundingScanMaxAddresses) + SparkExitFundingIndexes.restore(["regtest/wallet0": ceiling], into: defaults) + chain.usedAddresses = [address(UInt32(ceiling))] + chain.utxosByAddress[address(UInt32(ceiling))] = [SparkExitFixtures.utxo("lost", value: 7000)] + + let next = try await SparkExitManager.recoverFunding(recovery, now: now) + + XCTAssertEqual(next, UInt32(ceiling) + 1) + XCTAssertEqual(try earlierAddressStore.load(), [keptCoins(UInt32(ceiling), sats: 7000)]) + } + func testAKeptCounterWithNoRestorePendingReadsNoFundingAddress() async throws { defaults.set(3, forKey: key) chain.utxosByAddress[address(2)] = [SparkExitFixtures.utxo("lost", value: 5000)] From 0f9f29c1821ba16d5b9b1a9ccd32d1e704cd0253 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 13:01:25 +0100 Subject: [PATCH 3/3] fix: end the exit funding scan at the top of the index range --- Bitkit/Services/SparkExit/SparkExitFunding.swift | 6 +++--- BitkitTests/SparkExitFundingIndexTests.swift | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/SparkExit/SparkExitFunding.swift b/Bitkit/Services/SparkExit/SparkExitFunding.swift index 709e5bf0b..7657d0139 100644 --- a/Bitkit/Services/SparkExit/SparkExitFunding.swift +++ b/Bitkit/Services/SparkExit/SparkExitFunding.swift @@ -591,9 +591,9 @@ enum SparkExitMath { static func scanNextFundingIndex(from start: UInt32 = 0, isUsed: (UInt32) async throws -> Bool) async rethrows -> UInt32 { var next = start var index = start - let end = start.addingReportingOverflow(fundingScanMaxAddresses) - let limit = end.overflow ? UInt32.max : end.partialValue - while index < next + fundingScanGapLimit, index < limit { + // In 64 bits, so a counter near the top of the index range ends the scan instead of overflowing. + let limit = min(UInt64(start) + UInt64(fundingScanMaxAddresses), UInt64(UInt32.max)) + while UInt64(index) < UInt64(next) + UInt64(fundingScanGapLimit), UInt64(index) < limit { if try await isUsed(index) { next = index + 1 } diff --git a/BitkitTests/SparkExitFundingIndexTests.swift b/BitkitTests/SparkExitFundingIndexTests.swift index 7bfe609e6..a3535d4f6 100644 --- a/BitkitTests/SparkExitFundingIndexTests.swift +++ b/BitkitTests/SparkExitFundingIndexTests.swift @@ -182,6 +182,14 @@ final class SparkExitFundingIndexTests: XCTestCase { XCTAssertEqual(reads, Array(0 ... 5 + SparkExitMath.fundingScanGapLimit)) } + func testAFundingScanFromTheTopOfTheIndexRangeEndsInsteadOfOverflowing() async { + let start = UInt32.max - 5 + + let next = await SparkExitMath.scanNextFundingIndex(from: start) { _ in true } + + XCTAssertEqual(next, UInt32.max) + } + func testAFundingScanStopsAtItsCeilingWhenEveryAddressReadsAsUsed() async { var reads: UInt32 = 0