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
58 changes: 29 additions & 29 deletions Bitkit/Managers/SparkExitManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -1224,23 +1226,21 @@ 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)
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved

/// 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
Expand All @@ -1257,28 +1257,28 @@ 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
Comment thread
ovitrif marked this conversation as resolved.
Resolved
let isUsed = try await chain.isAddressUsed(address: funding(index).address)
if isUsed {
used.append(index)
}
return isUsed
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
let candidates = kept.map { Array(0 ..< UInt32(clamping: max(0, $0))) } ?? used
let watched = Set(((try? recovery.earlierAddressStore.load()) ?? []).map(\.address) + (recovery.record?.funding.map(\.address) ?? []))
let candidates = restored.map { Array(0 ..< $0) + used } ?? used
// 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 }
let sats = try await chain.utxos(address: address).reduce(0) { $0 + $1.value }
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
}
Expand Down
20 changes: 12 additions & 8 deletions Bitkit/Services/SparkExit/SparkExitFunding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -582,15 +582,18 @@ 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 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
while index < next + fundingScanGapLimit, index < fundingScanMaxAddresses {
/// 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
Comment thread
ovitrif marked this conversation as resolved.
Resolved
// 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
}
Expand Down Expand Up @@ -745,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))
}
}
Expand Down
78 changes: 75 additions & 3 deletions BitkitTests/SparkExitFundingIndexTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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() {
Expand Down Expand Up @@ -156,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

Expand Down Expand Up @@ -220,11 +254,49 @@ 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 {
Comment thread
ovitrif marked this conversation as resolved.
Resolved
// 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 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)]
Expand Down
Loading