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
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ class PaykitAllowancePayer @Inject constructor(
requestId: PaykitPaymentRequestId,
): Boolean = paymentProofRepo.failLightningPayment(paymentHash, error, requestId)

/** Whether [error] proves the payment never left. */
fun submissionSentNothing(error: Throwable): Boolean = paymentProofRepo.submissionSentNothing(error)

suspend fun discardLightningProof(paymentHash: String, requestId: PaykitPaymentRequestId) =
paymentProofRepo.failLightningPayment(paymentHash, requestId)

Expand Down Expand Up @@ -475,9 +478,12 @@ class PaykitAllowanceExecutor @Inject constructor(
entry?.let { journalOutcome(it) }
?: PaymentOutcome.UNKNOWN.takeIf { attempt.status == PaymentExecutionStatus.SUBMITTED }
}
outcome?.let { record(attempt.attemptId, it, identity) }
// Left open when the proof could not be discarded, so the next recovery tries again.
val settles = outcome != PaymentOutcome.FAILED ||
discardUnsentLightningProof(attempt.attemptId, identity)
if (settles) outcome?.let { record(attempt.attemptId, it, identity) }
// One that paid nothing gives the payee's list back, as a live failure does.
if (outcome == PaymentOutcome.FAILED && entry?.isAutomatic == true) {
if (settles && outcome == PaymentOutcome.FAILED && entry?.isAutomatic == true) {
releasePaymentList(entry, identity)
}
}
Expand Down Expand Up @@ -620,6 +626,17 @@ class PaykitAllowanceExecutor @Inject constructor(
entry.paymentHash != null &&
!payer.canListLightningPayments()

/**
* A failed payment has no proof to deliver, and a started proof left in place hides its request from the pending
* list. Discarded before the outcome is saved, so a kill in between leaves the attempt open for the next recovery.
*/
private suspend fun discardUnsentLightningProof(attemptId: String, identity: String): Boolean {
val entry = localState(identity).journal.firstOrNull { it.attemptId == attemptId } ?: return true
if (entry.stage == Stage.SUCCEEDED || entry.stage == Stage.FAILED) return true
val paymentHash = entry.paymentHash ?: return true
return payer.discardLightningProof(paymentHash, entry.requestId).isSuccess
}

private suspend fun record(attemptId: String, outcome: PaymentOutcome, identity: String) {
paykitSdkService.recordPaymentOutcome(PaymentOutcomeReport(attemptId, outcome))
val stage = when (outcome) {
Expand Down Expand Up @@ -999,6 +1016,13 @@ class PaykitAllowanceExecutor @Inject constructor(
).onFailure {
// Only an error that proves the payment never left releases the reservation; anything else stays open,
// and the node's payment event records its outcome.
if (payer.submissionSentNothing(it)) {
// Saved before the cleanup, so recovery after a kill in between ends the attempt as unsent.
updateJournalEntry(attemptId, identity) {
val settled = it.stage == Stage.SUCCEEDED || it.stage == Stage.FAILED
if (settled) it else it.copy(stage = Stage.SUBMITTED)
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
if (payer.failLightningPayment(paymentHash, it, request.id)) {
failUnsent(attemptId, identity)
throw it
Expand Down Expand Up @@ -1159,6 +1183,19 @@ class PaykitAllowanceExecutor @Inject constructor(
}
}

/**
* Called when the recheck before submission refuses a manual Lightning payment, before its proof is cleared, so
* recovery after a kill reads the attempt as unsent once the node has no payment for it.
*/
suspend fun manualLightningPaymentRefused(attemptId: String) {
val identity = activeIdentity ?: return
withContext(ioDispatcher) {
updateJournalEntry(attemptId, identity) {
if (it.stage == Stage.SUCCEEDED || it.stage == Stage.FAILED) it else it.copy(stage = Stage.SUBMITTED)
}
}
}

suspend fun finishManualPayment(
attemptId: String,
outcome: PaymentOutcome,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,8 @@ class PaykitAllowanceRepo @Inject constructor(
suspend fun manualLightningPaymentSent(attemptId: String, paymentHash: String) =
executor.manualLightningPaymentSent(attemptId, paymentHash)

suspend fun manualLightningPaymentRefused(attemptId: String) = executor.manualLightningPaymentRefused(attemptId)

/** [succeeded] null = outcome unknown (pending). */
suspend fun finishManualPayment(attemptId: String, succeeded: Boolean?, transactionId: String? = null) {
val outcome = when (succeeded) {
Expand Down
14 changes: 10 additions & 4 deletions app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -968,13 +968,20 @@ class PaykitPaymentProofRepo @Inject constructor(
submissionError: Throwable,
requestId: PaykitPaymentRequestId? = null,
): Boolean {
if (!submissionSentNothing(submissionError)) return false
failLightningPayment(paymentHash, requestId)
return true
}

/** Whether [submissionError] proves the payment never left. */
fun submissionSentNothing(submissionError: Throwable): Boolean {
val error = generateSequence(submissionError) { it.cause }
.firstOrNull {
it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused ||
it is ServiceError.PaymentStoppedAtSubmission || it is PaymentAbortedBeforeSend
}
?: submissionError.asNodeException() ?: submissionError
when (error) {
return when (error) {
is SparkError.SendRefused,
is ServiceError.PaymentStoppedAtSubmission,
is PaymentAbortedBeforeSend,
Expand All @@ -986,10 +993,9 @@ class PaykitPaymentProofRepo @Inject constructor(
is NodeException.NotRunning,
is NodeException.InvalidInvoice,
is NodeException.InvalidAmount,
is NodeException.PaymentSendingFailed -> failLightningPayment(paymentHash, requestId)
else -> return false
is NodeException.PaymentSendingFailed -> true
else -> false
}
return true
}

suspend fun retainHardwareOnchainCandidate(
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8376,6 +8376,7 @@ class AppViewModel @Inject constructor(
error.isStoppedAtSubmission()
} == true
authorizationError?.takeIf { sentNothing }?.let {
allowanceAttemptId?.let { paykitAllowanceRepo.manualLightningPaymentRefused(it) }
paykitPaymentProofRepo.failLightningPayment(paymentHash, incomingPaymentRequest?.id)
releasePrivatePaymentListIfNeeded(contactPaymentContext)
cancelPaymentProofPreparation(proofRequest)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() {
payer.payLightning(any(), any(), anyOrNull(), anyOrNull(), any())
).thenReturn(Result.success(PAYMENT_HASH))
whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true)
whenever(payer.discardLightningProof(any(), any())).thenReturn(Result.success(Unit))
whenever(payer.lightningPaymentStatus(any())).thenAnswer { nodeStatuses[it.getArgument<String>(0)] }
whenever(payer.canListLightningPayments()).thenAnswer { nodeListsPayments }
}
Expand Down Expand Up @@ -1093,6 +1094,25 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() {
verify(payer).failLightningPayment(eq(PAYMENT_HASH), any(), eq(secondRequest.id))
}

@Test
fun `a refused lightning payment is journaled unsent before its proof is cleared`() = test {
sut.activate(identity)
whenever(
payer.payLightning(any(), any(), anyOrNull(), anyOrNull(), any())
).thenReturn(Result.failure(TestAllowanceError("refused")))
whenever(payer.submissionSentNothing(any())).thenReturn(true)
var stageAtCleanup: Stage? = null
whenever(payer.failLightningPayment(any(), any(), any())).doSuspendableAnswer {
stageAtCleanup = sut.localState(identity).journal.single().stage
true
}

sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity)

// Recovery after a kill here finds an unsent attempt and fails it.
assertEquals(Stage.SUBMITTED, stageAtCleanup)
}

@Test
fun `a payment list given back by a failed send stays given back after the node's failure event`() = test {
sut.activate(identity)
Expand Down Expand Up @@ -1894,6 +1914,69 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() {
)
}

@Test
fun `recovery fails a refused manual lightning payment whose outcome was not recorded`() = test {
sut.activate(identity)
val attemptId = checkNotNull(
sut.beginManualPayment(fixtures.paymentRequest(), fixtures.lightningIdentifier, PAYMENT_HASH).getOrThrow(),
)
sut.manualLightningPaymentSent(attemptId, PAYMENT_HASH)

// Killed after the refusal cleared the proof, before the failure reached the ledger.
sut.manualLightningPaymentRefused(attemptId)
accountingState = fixtures.accountingState(
occurrences = listOf(occurrence(attemptId, PaymentExecutionStatus.SUBMITTED)),
)
recordedOutcomes.clear()
val restarted = PaykitAllowanceExecutor(
ioDispatcher = testDispatcher,
paykitSdkService = sdk,
store = PaykitAllowanceStore(keychain),
payer = payer,
clock = clock,
accountingAmount = { _, _ -> fixtures.accountingAmount("0.00001") },
)
restarted.recover(identity)

assertEquals(listOf(PaymentOutcomeReport(attemptId, PaymentOutcome.FAILED)), recordedOutcomes)
val order = inOrder(sdk, payer)
order.verify(payer).discardLightningProof(eq(PAYMENT_HASH), any())
order.verify(sdk).recordPaymentOutcome(PaymentOutcomeReport(attemptId, PaymentOutcome.FAILED))
}

@Test
fun `recovery discards the started proof of a refused automatic payment`() = test {
val request = fixtures.paymentRequest()
// Killed after the refusal was journaled as unsent, before its started proof was discarded.
seedJournal(journalEntry(AUTOMATIC_ATTEMPT_ID, request, Stage.SUBMITTED, PAYMENT_HASH))
accountingState = fixtures.accountingState(
occurrences = listOf(occurrence(AUTOMATIC_ATTEMPT_ID, PaymentExecutionStatus.SUBMITTED)),
)

sut.recover(identity)

assertEquals(listOf(PaymentOutcomeReport(AUTOMATIC_ATTEMPT_ID, PaymentOutcome.FAILED)), recordedOutcomes)
val order = inOrder(sdk, payer)
order.verify(payer).discardLightningProof(PAYMENT_HASH, request.id)
order.verify(sdk).recordPaymentOutcome(PaymentOutcomeReport(AUTOMATIC_ATTEMPT_ID, PaymentOutcome.FAILED))
}

@Test
fun `recovery leaves a refused payment open when its proof cannot be discarded`() = test {
val request = fixtures.paymentRequest()
seedJournal(journalEntry(AUTOMATIC_ATTEMPT_ID, request, Stage.SUBMITTED, PAYMENT_HASH))
accountingState = fixtures.accountingState(
occurrences = listOf(occurrence(AUTOMATIC_ATTEMPT_ID, PaymentExecutionStatus.SUBMITTED)),
)
whenever(payer.discardLightningProof(any(), any())).thenReturn(Result.failure(TestAllowanceError("store")))

sut.recover(identity)

// The next recovery discards the proof and fails the attempt.
assertEquals(emptyList(), recordedOutcomes)
assertEquals(listOf(Stage.SUBMITTED), sut.localState(identity).journal.map { it.stage })
}

@Test
fun `recovery settles a manual lightning payment restored from a backup taken before the send`() = test {
sut.activate(identity)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24367,6 +24367,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() {
verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext)
verify(lightningRepo, never()).payInvoice(any(), anyOrNull())
verify(paykitAllowanceRepo).finishManualPayment("refused-attempt", false, null)
// Journaled unsent before the cleanup, so recovery after a kill in between fails the attempt.
val order = inOrder(paykitAllowanceRepo, paykitPaymentProofRepo)
order.verify(paykitAllowanceRepo).manualLightningPaymentRefused("refused-attempt")
order.verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id)
}

@Test
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2176.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A contact payment request refused just before sending is no longer left open if the app closes before the refusal is saved.
Loading