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
3 changes: 3 additions & 0 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2585,6 +2585,9 @@ class LightningRepo @Inject constructor(

suspend fun currentOnchainSendAttempt(): OnchainSendAttempt? = onchainSendAttemptStore.current()

/** The wallet whose send journal [currentOnchainSendAttempt] reads. */
val currentWalletIndex: Int get() = lightningService.currentWalletIndex

/** Syncs the on-chain wallet, then checks that none of the attempt's candidates reached the mempool or chain. */
override suspend fun onchainCandidatesNeverReachedNetwork(attempt: OnchainSendAttempt): Boolean =
onchainCandidatesNeverReachedNetwork(attempt, ABANDON_SYNC_TIMEOUT)
Expand Down
46 changes: 41 additions & 5 deletions app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ class SparkExitRepo @Inject constructor(
@Volatile
private var walletIndex = 0

/** The last read of a funding address and what it held, so an ask a held payment hid can show again. */
@Volatile
private var lastFundingRead: Pair<String, List<EsploraUtxo>>? = null

@Volatile
private var isLoaded = false

Expand Down Expand Up @@ -128,6 +132,7 @@ class SparkExitRepo @Inject constructor(
.onFailure { e -> Logger.warn("Failed to delete the wiped exit addresses", e, context = TAG) }
work.cancelAll()
_state.update { SparkExitState() }
lastFundingRead = null
isLoaded = false
// A later exit, of a new or restored wallet, writes again.
isWriteClosed = false
Expand Down Expand Up @@ -456,6 +461,8 @@ class SparkExitRepo @Inject constructor(
val seen = utxos?.let { SparkExitMath.newFunding(it, record) }?.fold(0uL) { sum, utxo ->
sum.safe() + utxo.value.safe()
}
val address = record.funding.firstOrNull()?.address
if (utxos != null && address != null) lastFundingRead = address to utxos
_state.update {
it.copy(
fundingSeenSats = seen ?: it.fundingSeenSats,
Expand Down Expand Up @@ -495,7 +502,9 @@ class SparkExitRepo @Inject constructor(
deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds
)
}
if (SparkExitAlerts.isFundingAskBack(record, previous)) work.notify(SparkExitAlert.Funding)
// Funding at the address that covers the fees only waits to confirm: there is nothing to ask for.
val isCovered = _state.value.fundingState == SparkExitFundingState.Seen
if (SparkExitAlerts.isFundingAskBack(record, previous) && !isCovered) work.notify(SparkExitAlert.Funding)
if (SparkExitAlerts.isFundingAskWithdrawn(record, previous)) work.dismissFundingAsk()
when (record.phase) {
// Waiting on the operators for a week needs nothing from the user, so nothing reminds them.
Expand Down Expand Up @@ -780,6 +789,7 @@ class SparkExitRepo @Inject constructor(
val chain = requireNotNull(chain) { "No chain host for this network" }
val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" }
val utxos = chain.utxos(address)
lastFundingRead = address to utxos
val seen = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() }
_state.update { it.copy(fundingSeenSats = seen, fundingSeenCount = utxos.size) }
seen
Expand Down Expand Up @@ -1008,18 +1018,23 @@ class SparkExitRepo @Inject constructor(
val started = SparkExitRecord.SavingsSendStarted(address, atHeight = null, earlierAttemptId)
val marked = record.copy(savingsSendStarted = started)
saveRecord(marked)
_state.update { it.copy(record = marked, fundingState = SparkExitMath.fundingState(marked, utxos = null)) }
_state.update { it.copy(record = marked, fundingState = SparkExitMath.fundingState(marked, lastRead(marked))) }
}

private fun lastRead(record: SparkExitRecord): List<EsploraUtxo>? =
lastFundingRead?.takeIf { it.first == record.funding.firstOrNull()?.address }?.second

private fun clearSavingsSend() {
val record = _state.value.record?.takeIf { it.savingsSendStarted != null } ?: return
val cleared = record.copy(savingsSendStarted = null)
// Kept in memory even when the save fails; a later tick saves it.
runCatching { saveRecord(cleared) }
.onFailure { Logger.warn("Failed to clear the started Spark exit savings payment", it, context = TAG) }
// The hold ends: the ask shows until the next read of the address.
// The hold ends: the ask the last read of the address found shows again, reduced by a partial payment, or the
// full ask until the next read when there was none.
val isHeld = _state.value.fundingState == SparkExitFundingState.Paid && !cleared.isAwaitingOwnPayment
_state.update { it.copy(record = cleared, fundingState = it.fundingState.takeUnless { isHeld }) }
val asked = lastRead(cleared)?.let { SparkExitMath.fundingState(cleared, it) }
_state.update { it.copy(record = cleared, fundingState = if (isHeld) asked else it.fundingState) }
}

/**
Expand Down Expand Up @@ -1147,10 +1162,30 @@ class SparkExitRepo @Inject constructor(
private suspend fun keepAcceptedSavingsSend(record: SparkExitRecord): SparkExitRecord {
if (!canKeepAcceptedSavingsSend(record)) return record
// The journal's attempt to any address: one elsewhere says the journal moved on, not that nothing went out.
val journalWallet = lightningRepo.currentWalletIndex
val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrElse { return record }
if (attempt == null && journalWallet == walletIndex && isStartedSendNeverSent(record)) {
Logger.info("Forgetting the started Spark exit savings payment the journal never sent", context = TAG)
clearSavingsSend()
return _state.value.record ?: record
}
return keepAcceptedSavingsSend(record, attempt)
}

/**
* Whether the started savings payment of [record] never went out, once the send journal holds no attempt: the
* journal is the exit wallet's, which saves a send before it goes out, and no transaction ever reached the started
* payment's address. The address read covers a payment the journal no longer holds: one a later send replaced
* before that send was dropped, or one from a journal a restore did not bring back. Called under the tick lock,
* so it never runs between marking a payment and its admission to the journal.
*/
private suspend fun isStartedSendNeverSent(record: SparkExitRecord): Boolean {
val address = record.savingsSendStarted?.address ?: return false
if (lightningRepo.currentWalletIndex != walletIndex) return false
val chain = chain ?: return false
return runSuspendCatching { !chain.isAddressUsed(address) }.getOrDefault(false)
}

private fun canKeepAcceptedSavingsSend(record: SparkExitRecord): Boolean =
record.isActive && record.phase is SparkExitRecord.Phase.AwaitingFunding &&
record.fundingPaymentTxid == null && (record.savingsRefusal != null || record.savingsSendStarted != null)
Expand All @@ -1165,7 +1200,8 @@ class SparkExitRepo @Inject constructor(
val txid = own?.takeIf { it.hasPositiveEvidence || (started != null && isNoAnswer) }?.txid
if (txid == null) {
// Only the earlier attempt: nothing was admitted, so nothing went out. One a node refused is paid again by
// its own retry. No attempt at all proves nothing: the journal may be another wallet's.
// its own retry. No attempt at all proves nothing here: the journal may be another wallet's, which only
// the journal's wallet and an unused address rule out.
val isNotSent = (attempt != null && attempt.attemptId == started?.earlierAttemptId) ||
own?.evidence == OnchainSendEvidence.Rejected
if (started != null && isNotSent) {
Expand Down
86 changes: 84 additions & 2 deletions app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -747,14 +747,18 @@ class SparkExitRepoTest : BaseUnitTest() {
}

// On the test's own dispatcher, so no tick a start or payment launches runs on after the test.
private fun fundingChain(utxos: String? = "[]", readUtxos: () -> String? = { utxos }) = HttpClient(
private fun fundingChain(
utxos: String? = "[]",
txCount: Int = 0,
readUtxos: () -> String? = { utxos },
) = HttpClient(
MockEngine.create {
dispatcher = testDispatcher
addHandler { request ->
val url = request.url.toString()
when {
url.endsWith("/address/$funding/utxo") && readUtxos() != null -> respond(readUtxos().orEmpty())
url.endsWith("/address/$funding") -> respond(addressStats(txCount = 0))
url.endsWith("/address/$funding") -> respond(addressStats(txCount))
url.endsWith("/blocks/tip/height") -> respond("1000")
url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""")
else -> throw IOException("unreachable '$url'")
Expand Down Expand Up @@ -2015,6 +2019,84 @@ class SparkExitRepoTest : BaseUnitTest() {
assertIs<SparkExitFundingState.Ask>(sut.state.value.fundingState)
}

@Test
fun `a started savings payment the journal never sent frees the ask once its address shows nothing`() = test {
// Stopped before the payment was admitted, or restart dropped an attempt that never went out: no attempt.
val store = SparkExitStore(File(Env.sparkExitRecordPath(0)))
store.save(startedRecord(earlierAttemptId = null))
whenever(lightning.currentOnchainSendAttempt()).thenReturn(null)
val used = quotedSut(FakeSparkExitRecovering(), fundingChain(txCount = 1))
used.load().getOrThrow()
used.tick().getOrThrow()
used.onAppBackgrounded()
assertNotNull(assertNotNull(store.load()).savingsSendStarted, "a transaction reached the address")

whenever(lightning.currentWalletIndex).thenReturn(1)
val elsewhere = quotedSut(FakeSparkExitRecovering(), fundingChain())
elsewhere.load().getOrThrow()
elsewhere.tick().getOrThrow()
elsewhere.onAppBackgrounded()
assertNotNull(assertNotNull(store.load()).savingsSendStarted, "the journal read is another wallet's")

whenever(lightning.currentWalletIndex).thenReturn(0)
val sut = quotedSut(FakeSparkExitRecovering(), fundingChain())
sut.load().getOrThrow()
sut.tick().getOrThrow()
sut.onAppBackgrounded()

assertNull(assertNotNull(store.load()).savingsSendStarted)
assertIs<SparkExitFundingState.Ask>(sut.state.value.fundingState)
assertTrue(sut.canCancel)
}

@Test
fun `a started savings payment that expires sends no fee request while covering funding confirms`() = test {
val store = SparkExitStore(File(Env.sparkExitRecordPath(0)))
val elsewhere = refusedSavingsPayment().copy(
address = "bcrt1qelsewhere",
evidence = OnchainSendEvidence.Accepted,
)
whenever(lightning.currentOnchainSendAttempt()).thenReturn(elsewhere)
// The chain's tip is 1000.
store.save(startedRecord(atHeight = 1000u - SparkExitRecord.OWN_PAYMENT_TIMEOUT_BLOCKS))
val covering = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":100000,"status":{"confirmed":false}}]"""
val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = covering))
sut.load().getOrThrow()
sut.tick().getOrThrow()
sut.onAppBackgrounded()

assertNull(assertNotNull(store.load()).savingsSendStarted)
assertIs<SparkExitFundingState.Seen>(sut.state.value.fundingState)
verify(work, never()).notify(eq(SparkExitAlert.Funding), anyOrNull(), anyOrNull(), anyOrNull())
}

@Test
fun `a savings payment that fails keeps the fee request another wallet's payment reduced`() = test {
var heldAtSend: SparkExitFundingState? = null
lateinit var sut: SparkExitRepo
stubFunding {
heldAtSend = sut.state.value.fundingState
Result.failure(OnchainSendNotDispatchedError(IOException("journal write failed")))
}
val paid = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":8000,"status":{"confirmed":false}}]"""
sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = paid))
sut.loadQuote().getOrThrow()
sut.refreshFundingAddress().getOrThrow()
whenever(lightning.getFeeRates()).thenReturn(Result.success(FeeRates(fast = 7u, mid = 4u, slow = 1u)))
whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any()))
.thenReturn(Result.success(300uL))
whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL)))
sut.savingsFundingFee().getOrThrow()

assertTrue(sut.start(fundFromSavings = true).isFailure)
sut.onAppBackgrounded()

assertIs<SparkExitFundingState.Paid>(heldAtSend, "the ask is held while the payment goes out")
assertNull(sut.state.value.record?.savingsSendStarted)
val ask = assertIs<SparkExitFundingState.Ask>(sut.state.value.fundingState)
assertEquals(8000uL, ask.receivedSats, "the partial payment still counts")
}

@Test
fun `a start's savings payment is saved on the exit before it goes out`() = test {
val store = SparkExitStore(File(Env.sparkExitRecordPath(0)))
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2151.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed the force transfer's fee request staying hidden or too large after a savings payment that never went out or failed, and a fee reminder sent while funding already covered the fees.