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
2 changes: 1 addition & 1 deletion Bitkit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1262,7 +1262,7 @@
repositoryURL = "https://github.com/breez/breez-sdk-spark-swift";
requirement = {
kind = exactVersion;
version = 0.28.0;
version = 0.28.2;
};
};
968FE13E2DFB016B0053CD7F /* XCRemoteSwiftPackageReference "ldk-node" */ = {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 33 additions & 8 deletions Bitkit/Services/SparkExit/SparkExitDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,19 @@ struct SparkExitDriver {
// generation stays over a failed-only build, running again with the funding adopted. Once a
// block, like the check's rebuild: the valid generation's retry clock does not pace it.
let tip = try? await chain.tipHeight()
if tip == nil || record.unverifiedRebuiltAtHeight != tip {
let unilateral = (record.recovery?.response.transactions ?? []).filter { $0.kind != .cooperative }
let unreadBefore = Set((before.recovery?.response.transactions ?? []).filter { $0.status == .unverified }.map(\.txid))
if unilateral.contains(where: { $0.status == .ready }) || !unilateral.contains(where: { $0.status == .unverified }) {
// A clean check while the payment came can read the unread step again, and it is then sent:
// a rebuild now would conflict with it at the same fee. The ask ends, and the funding it
// adopted stays for a later rebuild or the leftover sweep.
Logger.info("Spark exit steps read again: the funded unverified rebuild is not needed", context: "SparkExitDriver")
record.phase = .running
record.isUnverifiedAsk = nil
} else if unilateral.contains(where: { step in step.status == .unverified && !unreadBefore.contains(step.txid) }) {
// A step this check just turned unverified may have been sent on an earlier clean check: the
// resume waits for the next check, as the check's own rebuild does.
} else if tip == nil || record.unverifiedRebuiltAtHeight != tip {
record.unverifiedRebuiltAtHeight = tip
var valid = record
valid.phase = .running
Expand Down Expand Up @@ -625,8 +637,11 @@ struct SparkExitDriver {
return
}
// A step the SDK could not read is settled by a fresh build, once a block, unless a step is still to send:
// a build now would conflict with it at the same fee.
if let tip, isUnverifiedRebuildDue(checked.recovery, record: record, tip: tip) {
// a build now would conflict with it at the same fee. A check marks a step unverified when one chain read
// fails and clears it on the next clean check, so only a step that was already unverified before this check
// rebuilds, and one this check just turned unverified holds it, as it may be in flight. A step that stays
// unread rebuilds at the first check, once a block at most, where no other step just turned unverified.
if let tip, isUnverifiedRebuildDue(checked.recovery, stored: stored, record: record, tip: tip) {
Logger.warn("Spark exit has a step the SDK could not read, rebuilding over it", context: "SparkExitDriver")
record.unverifiedRebuiltAtHeight = tip
try save(record)
Expand Down Expand Up @@ -867,10 +882,20 @@ struct SparkExitDriver {
try await rebuild(&record, recovering: recovering)
}

/// A unilateral step the SDK could not read, nothing unilateral ready to send, and no such rebuild at this tip yet.
private func isUnverifiedRebuildDue(_ recovery: RecoverFundsResponse, record: SparkExitRecord, tip: UInt32) -> Bool {
/// Unilateral steps the SDK could not read, each one at this check and the one before, nothing unilateral ready to
/// send, and no such rebuild at this tip yet. A step this check just turned unverified may be in flight, so it holds
/// the rebuild as a ready one does.
private func isUnverifiedRebuildDue(
_ recovery: RecoverFundsResponse,
stored: RecoverFundsResponse,
record: SparkExitRecord,
tip: UInt32
) -> Bool {
let unilateral = recovery.transactions.filter { $0.kind != .cooperative }
return unilateral.contains { $0.status == .unverified } && !unilateral.contains { $0.status == .ready }
let unreadBefore = Set(stored.transactions.filter { $0.status == .unverified }.map(\.txid))
let unread = unilateral.filter { $0.status == .unverified }
return !unread.isEmpty && unread.allSatisfy { unreadBefore.contains($0.txid) }
&& !unilateral.contains { $0.status == .ready }
&& record.unverifiedRebuiltAtHeight != tip
}

Expand Down Expand Up @@ -1316,8 +1341,8 @@ struct SparkExitDriver {

// MARK: Broadcast

/// A unilateral step the SDK could not read is never sent: a rebuild settles it. A cooperative one is, since nodes
/// refuse it if its funds already moved.
/// A unilateral step the SDK could not read is never sent: the next clean check, or a rebuild once it stays unread,
/// settles it. A cooperative one is, since nodes refuse it if its funds already moved.
private func broadcastReady(_ record: inout SparkExitRecord, tip: UInt32? = nil) async throws {
guard let recovery = record.recovery?.response else { return }
let confirmed = Set(recovery.transactions.filter(\.isConfirmed).map(\.txid))
Expand Down
110 changes: 110 additions & 0 deletions BitkitTests/SparkExitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1606,6 +1606,69 @@ final class SparkExitDriverTests: XCTestCase {
XCTAssertEqual(chain.broadcasts.map(\.txid), ["n2b"], "the unverified step is still not sent")
}

/// A ready step that one failed chain read turns unverified may already be sent, so it is not rebuilt over: the
/// exit waits for the next check, which reads it again, and rebuilds only if it stays unread.
func testAStepAFailedReadTurnsUnverifiedWaitsForTheNextCheckInsteadOfRebuilding() async throws {
var record = SparkExitFixtures.record(phase: .running)
let ready = SparkExitFixtures.recovery([
SparkExitFixtures.tx("n1", status: .confirmed(blockHeight: 10)),
SparkExitFixtures.tx("n2", cpfp: "03c", dependsOn: ["n1"]),
])
let unread = SparkExitFixtures.recovery([
SparkExitFixtures.tx("n1", status: .confirmed(blockHeight: 10)),
SparkExitFixtures.tx("n2", cpfp: "03c", dependsOn: ["n1"], status: .unverified),
])
record.adopt(ready, at: clock)
sdk.checks = [CheckRecoverFundsResponse(recovery: unread, verdict: .valid)]

record = try await driver().tick(record)

XCTAssertTrue(sdk.recoverRequests.isEmpty, "rebuilt over a step one failed read turned unverified")
XCTAssertNil(record.unverifiedRebuiltAtHeight)
XCTAssertNil(record.isUnverifiedAsk)
XCTAssertEqual(record.generation, 1)
XCTAssertTrue(chain.broadcasts.isEmpty, "the unverified step was sent")

// Still unread at the next check: now it rebuilds.
sdk.checks = [CheckRecoverFundsResponse(recovery: unread, verdict: .valid)]
sdk.builds = [SparkExitFixtures.recovery([
SparkExitFixtures.tx("n1", status: .confirmed(blockHeight: 10)),
SparkExitFixtures.tx("n2b", cpfp: "03d", dependsOn: ["n1"]),
])]
record = try await driver().tick(record)

XCTAssertEqual(sdk.recoverRequests.count, 1)
XCTAssertEqual(record.unverifiedRebuiltAtHeight, 1000)
XCTAssertEqual(record.generation, 2)
}

/// A step one failed read turns unverified holds the rebuild over another leaf's step that was already unread: the
/// rebuild would replace it while it may be in flight.
func testAStepAFailedReadTurnsUnverifiedHoldsTheRebuildOverAnotherUnreadLeaf() async throws {
var record = SparkExitFixtures.record(phase: .running)
record.leafIds = ["leaf-1", "leaf-2"]
let stored = SparkExitFixtures.recovery([
SparkExitFixtures.tx("n1", status: .confirmed(blockHeight: 900)),
SparkExitFixtures.tx("n2", dependsOn: ["n1"], status: .unverified),
SparkExitFixtures.tx("m1", status: .confirmed(blockHeight: 900)),
SparkExitFixtures.tx("m2", dependsOn: ["m1"]),
])
let checked = SparkExitFixtures.recovery([
SparkExitFixtures.tx("n1", status: .confirmed(blockHeight: 900)),
SparkExitFixtures.tx("n2", dependsOn: ["n1"], status: .unverified),
SparkExitFixtures.tx("m1", status: .confirmed(blockHeight: 900)),
SparkExitFixtures.tx("m2", dependsOn: ["m1"], status: .unverified),
])
record.adopt(stored, at: clock)
sdk.checks = [CheckRecoverFundsResponse(recovery: checked, verdict: .valid)]

record = try await driver().tick(record)

XCTAssertTrue(sdk.recoverRequests.isEmpty, "rebuilt over m2, which one failed read turned unverified")
XCTAssertNil(record.unverifiedRebuiltAtHeight)
XCTAssertEqual(record.generation, 1)
}

/// An unverified rebuild that builds only failed cooperative leaves, beside the leaf it could not read, keeps the
/// valid generation: its signed steps are still sent once the chain reads again.
func testAnUnverifiedRebuildOfOnlyFailedLeavesKeepsTheValidGeneration() async throws {
Expand Down Expand Up @@ -1766,6 +1829,53 @@ final class SparkExitDriverTests: XCTestCase {
return (record, readable, failure)
}

/// A savings payment keeps an unverified rebuild's ask open; a clean check while it confirms reads the unread step
/// as ready, and it is sent. The funded rebuild then never runs: it would conflict with that step at the same fee.
func testAFundedUnverifiedAskWhoseStepReadsAgainEndsWithoutARebuild() async throws {
var (record, readable, _) = try await unverifiedAsk()
let paid = String(repeating: "f", count: 64)
record.fundingPaymentTxid = paid
let builds = sdk.recoverRequests.count
sdk.checks = [CheckRecoverFundsResponse(recovery: readable, verdict: .valid)]
chain.utxosByAddress[record.funding[0].address] = [SparkExitFixtures.utxo(paid, value: 50000)]
chain.tip = 1001

record = try await driver().tick(record)

XCTAssertEqual(sdk.recoverRequests.count, builds, "rebuilt over n2, which the clean check made ready and sent")
XCTAssertEqual(chain.broadcasts.map(\.txid), ["n2"])
XCTAssertEqual(record.phase, .running)
XCTAssertNil(record.isUnverifiedAsk)
XCTAssertEqual(record.generation, 1)
}

/// A step that a clean check sent while the payment was unconfirmed holds the funded rebuild when the tick that adopts
/// the payment fails to read it again: the resume waits for the next check.
func testAFundedUnverifiedAskHoldsItsRebuildOverAStepSentOnAnEarlierCleanCheck() async throws {
var (record, readable, _) = try await unverifiedAsk()
let unread = try XCTUnwrap(record.recovery?.response)
let paid = String(repeating: "f", count: 64)
record.fundingPaymentTxid = paid
let builds = sdk.recoverRequests.count
sdk.checks = [CheckRecoverFundsResponse(recovery: readable, verdict: .valid)]
chain.utxosByAddress[record.funding[0].address] = [SparkExitFixtures.utxo(paid, value: 50000, confirmed: false)]

record = try await driver().tick(record)
XCTAssertEqual(chain.broadcasts.map(\.txid), ["n2"])
XCTAssertEqual(record.isUnverifiedAsk, true)

sdk.checks = [CheckRecoverFundsResponse(recovery: unread, verdict: .valid)]
chain.utxosByAddress[record.funding[0].address] = [SparkExitFixtures.utxo(paid, value: 50000)]
chain.tip = 1001

record = try await driver().tick(record)

XCTAssertTrue(record.funding.contains { $0.txid == paid }, "the payment was not adopted, so the hold never ran")
XCTAssertEqual(sdk.recoverRequests.count, builds, "rebuilt over n2, sent on the previous tick")
XCTAssertEqual(record.isUnverifiedAsk, true)
XCTAssertEqual(record.generation, 1)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}

/// Confirmed funding for an unverified rebuild's fee ask resumes that rebuild with its guard: a build of only failed
/// cooperative leaves beside the waiting leaf is never adopted, and the exit runs on with the valid generation.
func testFundingAnUnverifiedRebuildsAskKeepsTheValidGenerationOverAFailedOnlyBuild() async throws {
Expand Down
Loading