Skip to content

fix: bind send approval to the prepared mining fee - #1350

Merged
ovitrif merged 6 commits into
masterfrom
fix/bind-send-approval-to-prepared-fee
Nov 17, 2026
Merged

ovitrif merged 6 commits into
masterfrom
fix/bind-send-approval-to-prepared-fee

Conversation

@jvsena42

@jvsena42 jvsena42 commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Fixes #1079
Twin: synonymdev/bitkit-android#1952

This PR binds an on-chain send's approval to the mining fee of the transaction that is actually broadcast. Reproduced on regtest: Confirm showed 1,000 + 203 sats fee and the send spent 1,000 + 212 sats at an unchanged 1 sat/vB, because preparation after the swipe picked different inputs than the estimate.

Description

  • OnchainSendAttemptService.send takes the reviewed fee. After preparation and before the attempt is saved or any Paykit hook runs, a fee at or below it sends as before. A higher fee keeps the prepared transaction in the actor and throws OnchainSendFeeIncreased; nothing is broadcast and the existing pre-dispatch cleanup runs.
  • SendConfirmationView captures the fee the warnings were evaluated on, and on a refusal shows the actual fee and amount, re-runs the fee warnings, resets the swipe and requires PIN/biometric again. The next swipe sends that kept transaction once, matched by txid and payment (wallet, address, amount, rate, inputs, max flag, request, identity, deadline). Automatic payments drop to manual confirmation.
  • A kept transaction is refused before admission if its inputs were spent, its node stopped or changed, the deadline passed, or the payment changed. It is dropped before the node stops (LightningService.beforeNodeStop), because the Rust PreparedOnchainSend drop calls cancel_tx through that node's wallet. A refusal for a closed or replaced sheet is ignored.
  • Three new strings: wallet__send_fee_increased_title, wallet__send_fee_increased, wallet__send_fee_candidate_unavailable.

Out of Scope

  • Hardware-wallet sends: HwSendCoordinator composes again at sign time without an in-app fee comparison; the device confirms the signed transaction. Left out because fix: keep held hardware sends until resolved #1210 is reworking that path.
  • A send already broadcasting when the node stops still releases its prepared transaction after the stop. Closing that needs stop() to wait for the in-flight send; master has the same window for every unsubmitted prepared send.
  • Spark funding already refuses a higher fee before broadcast and re-prepares; unchanged.

Design

N/A — no design available. Reuses the existing Confirm screen and toasts.

Preview

N/A — not run on a device yet.

QA Notes

Setup

Debug build on an iPhone 17 simulator against staging regtest, fresh wallet funded with ../bitkit-android/lsp deposits, PIN 1234 with "Also require for payments" on. No device fixture makes the prepared fee exceed the estimate on current master; prepared-fee-recovery.md ("Initial send fee approval") records why and the simulator driving notes.

Journeys

  • J1: updated prepared-fee-recovery.md — a higher prepared fee is shown for re-approval, then sent once; cancel sends nothing; records the device findings and driving notes

Manual Tests

N/A

Automated Checks

  • added OnchainSendAttemptServiceTests.swift — higher fee refused with no broadcast or hooks, reapproval sends that transaction once; equal/lower fee sends directly; cancel frees later sends; coins spent, expiry, node change, wallet/amount/request change refuse before any save; node stop drops the kept transaction
  • added SendConfirmationViewTests.swift — fee warnings use the prepared fee; reapproval covers only its payment; refusals for a closed sheet are ignored

Evidence

  • Full unit suite at 45e0765 on iPhone 17 simulator: 4084 passed, 0 failed, 5 skipped (CI skips).
  • OnchainSendAttemptServiceTests, SendConfirmationViewTests, SendConfirmationLifecycleTests at 64d3be6: 111 passed, 0 failed. swiftformat --lint, translation validation and git diff --check clean.
  • Two independent review rounds; all findings fixed in 45e0765 and 64d3be6.
  • Device run on simulator at 64d3be6, 2026-11-17 (recordings kept locally):
    • Ordinary send: Confirm 143 sats, paid 143, one PIN prompt, one broadcast (b0b8acd7…0efb); PIN → txid 1.1 s.
    • Max send: Confirm 181, paid 181, no second prompt (670fa8cc…6d05); PIN → txid 0.8 s.
    • Deposit while Confirm is open, then swipe: fee stayed 231, sent with the stored coins (dedbbfc4…51bb). Max after a deposit: Ignoring stale max, fixed amount at the shown 181 (b00963e1…e53e). Swipe before the new coin synced: shown 181, paid 181 (968c575c…c2ff).
    • Manual coin selection, near-balance amounts and BIP21 amounts: every prepared fee equalled the estimate; exceeds the reviewed never logged.

Review round 1 (fixes at f2915cf):

  • After a fee refusal, both stay-on-Confirm branches put the Paykit request back through paymentRequestForRetry, so the second swipe consumes the private payment list again before broadcast (ben-kaufman). PaykitPaymentRequestServiceTests.testFeeRefusalOnConfirmConsumesThePaymentListAgainBeforeTheReapprovedSend failed before the fix.
  • f2915cf re-checks that the refused send still owns the sheet after that restore awaits the SDK, and discards the old transaction without writing its fee or amount otherwise (Greptile). testFeeRefusalIsDroppedWhenAnotherSendStartsWhileItsRequestIsRestored failed before the fix.
  • PaykitPaymentRequestServiceTests, OnchainSendAttemptServiceTests, SendConfirmationViewTests, SendConfirmationLifecycleTests: 424 passed.

Gaps

  • ⚠️ Not verified on a device: the higher-fee review, re-approval and cancel (J1 cases 1–3). No fixture on current master makes the prepared fee exceed the estimate on iOS (see the journey note); these rest on OnchainSendAttemptServiceTests and SendConfirmationViewTests. The same flow reproduced and passed on Android (fix: bind send approval to the prepared mining fee bitkit-android#1952).
  • View-level refusal handling (swipe reset, toast, second PIN) is covered only through static helpers and service tests; the real LightningService.stop() hook call is not unit-tested.
  • Full suite not re-run on 64d3be6; 64d3be6 itself was not independently re-reviewed.
  • New string translations are machine-written, not reviewed by native speakers.

Models used

  • Planning/scoping: Claude Opus 5.5 (reasoning: Not exposed)
  • Implementation: Claude Fable 5.2 (reasoning: Not exposed)
  • Review: Claude Fable 5.2 (reasoning: Not exposed)
  • Review rounds: 2

🤖 Generated with Claude Code

jvsena42 and others added 3 commits November 17, 2026 07:45
The confirmation showed a dry-run fee estimate, and the transaction prepared
after the swipe could pay more without another review (#1079).

The send now passes the reviewed fee to OnchainSendAttemptService. A prepared
transaction paying more is kept, the attempt is released and the send is
refused before any broadcast side effect. Confirm then shows the actual fee
and amount, and the next swipe runs the fee warnings and authentication again
and sends that same transaction. A kept transaction that no longer matches
the payment, or whose coins are gone, fails instead of being rebuilt.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A kept transaction whose node changed or whose request expired is now
refused before an attempt is saved or the request's payment is started.
It is dropped before its node stops, as dropping it persists through the
wallet that prepared it.

The reviewed fee is captured where the fee warnings are evaluated, and a
fee refusal that returns after its send flow was closed is ignored and
its transaction dropped.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A send still preparing when its node starts to stop no longer keeps its
transaction for a renewed approval, and the stop hook is read and written
under a lock. A reapproval whose transaction is gone stays on the review
with its message instead of opening the failure screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42
jvsena42 marked this pull request as ready for review November 17, 2026 13:22
@jvsena42
jvsena42 requested review from a team, ben-kaufman and ovitrif and removed request for a team November 17, 2026 13:22
@greptile-apps

greptile-apps Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The latest changes appear safe to merge.

Summary

Binds an on-chain send’s approval to its prepared mining fee. A higher fee requires another confirmation before broadcast.

  • On-chain sends ask again when the prepared transaction costs more than the reviewed fee.

Reviews (3) · Last reviewed commit: "fix: recheck the send flow after restori..." · Reviewed by Greptile

@ovitrif

ovitrif commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Triage: this PR goes in the 3.2.0 milestone under #1079. Twin: synonymdev/bitkit-android#1952.

@talosmachina talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings. Binds an initial on-chain send to the mining fee the user reviewed: a prepared transaction that pays more is kept in the actor and refused before admission side effects, and the next swipe sends exactly that transaction after warnings and authentication run again. Reviewed 9b8d6e9, static review: per this repo's Bitkit rules the iOS branch was not built or run here, so this rests on reading the code and on CI.

What I checked, and 6 candidates I ruled out

Read: the full diff of OnchainSendAttemptService.swift, SendConfirmationView.swift, LightningService.swift, WalletViewModel.swift; send(...) and retrySamePayment in full; performPayment, submitPayment, validatePayment and calculateTransactionFee around the changed lines; the new tests' names and the en/de/ar strings.
Cross-repo: PreparedOnchainSend and Wallet::cancel_tx in synonymdev/ldk-node at the pinned b6335ec (0.7.0-rc.80).
CI at review time: SwiftFormat, validate, detect-changes green; Run Tests, Run Integration Tests and build-local still pending.

Ruled out

  • Kept transaction outliving a later spend of its coins: every send(...) takes and clears heldCandidate before anything else, including the Transfer and Spark callers of OnchainSendAttemptService.shared.send, and reapproval re-checks the inputs against listSpendableOutputs() before sending.
  • Change reservation leaked by the kept handle: PreparedOnchainSend::drop calls cancel_tx only while submission_started is false, and the handle is dropped on resetSendState, on any later send, and in beforeNodeStop before node.stop(), so the cancel runs against a live wallet.
  • A send preparing while the node stops keeping a dead candidate: nodeStopping records the node weakly and the fee-refusal branch refuses to keep a candidate from that node or from a node that is no longer current.
  • Paykit request side effects on the refused swipe: the refusal is thrown before beforeBroadcastAttempt, so markOnchainPaymentStarted and the allowance check never ran; the attempt is cleared through the existing pre-dispatch path and the private list outcome stays definitePreBroadcastFailure.
  • Reapproval applied to a changed payment: the view's covers check and the actor's Payment equality (wallet, address, amount, rate, inputs, max flag, request, identity, deadline) plus held.node === dispatchNode both have to match, and a mismatch fails before admission.
  • Fee estimate overwriting the actual fee on screen: reviewIncreasedFee bumps feeCalculationId, and calculateTransactionFee returns the kept fee while the reapproval covers the payment.

Merge confidence: 4/5, the LightningService.stop() hook that drops the kept transaction has no test (the PR says so) and the unit and integration runs had not finished at review time.

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the run metadata available to this reviewer does not report an effort setting)

@ben-kaufman ben-kaufman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fee reapproval path can leave a paid private payment list available for reuse.

Reviewer model: gpt-6.1-sol
Reasoning effort: xhigh

@jvsena42
jvsena42 marked this pull request as draft November 17, 2026 14:49

@ovi-reviewer ovi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: ⚠️ Not verified — draft PR.

Findings: No new findings reported; this review was stopped before completion. The existing private payment list finding remains open and is not duplicated here.

QA for 9b8d6e9:

Review and approve a higher mining fee ⏭️ J1.1: not driven while the PR is draft.

The base repository rules require AI reviewers to skip drafts until ready for review.

Cancel or edit a higher-fee payment ⏭️ J1.2: not driven while the PR is draft.

The base repository rules require AI reviewers to skip drafts until ready for review.

Refuse a stale higher-fee approval ⏭️ J1.3: not driven while the PR is draft.

The base repository rules require AI reviewers to skip drafts until ready for review.

Send at or below the reviewed fee ⏭️ J1.4: not driven while the PR is draft.

The base repository rules require AI reviewers to skip drafts until ready for review.

Coverage: full review of 192815e7..9b8d6e9 was started but not completed. The build was interrupted after confirming draft status; no unit or device tests ran. All changed runtime behavior remains unverified by this run.

Twin: synonymdev/bitkit-android#1952 targets the same fee-approval behavior; implementation parity was not fully reviewed.


Reviewed by gpt-6.1-sol-high

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@jvsena42
jvsena42 marked this pull request as ready for review November 17, 2026 15:02
@jvsena42
jvsena42 requested a review from ben-kaufman November 17, 2026 15:02
@jvsena42
jvsena42 marked this pull request as draft November 17, 2026 15:06
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@jvsena42
jvsena42 marked this pull request as ready for review November 17, 2026 15:11

@ovi-reviewer ovi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: ✅ Approve

Findings: No new findings in the delta. I verified both prior fixes in the code and focused regressions:

QA for f2915cf:

Built and tested on iPhone 17 Pro simulators, iOS 27.0, against staging regtest. Higher-fee cases use the unpublished debug hooks below; the ordinary-send control uses the unmodified head. Recordings are 2× speed.

Review and approve a higher mining fee ✅ J1.1: 1 → 562 sats required another swipe, the 50% warning and a second PIN; backend checks confirmed the original candidate sent once.

The native candidate d166619b…3011c5c9 was created before refusal and sent after reapproval. Backend history was empty before reapproval and contained that transaction afterward. Its 100,000-sat input paid 1,000 sats to the recipient and 98,438 sats in change: 562 sats fee, matching Sent details.

J1.1-2x.2x.mp4

Higher-fee review, renewed authentication and Sent details.

Cancel or edit a higher-fee payment ✅ J1.2: closing sent nothing; changing the rate required a new review, with backend history unchanged.

Closing the 143-sat review sent nothing. In a separate review, changing Normal to Fast replaced candidate 63f7cb1f…11b843f35 with 1463d6f3…7e777b3a, whose 422-sat fee required review again. Neither candidate reached the backend. After the close leg, the pristine-head control below confirmed that sending remained available.

Close the review Edit the fee rate
J1.2-2x.2x.mp4
J1.2-edit-2x.2x.mp4
Refuse a stale higher-fee approval ✅ J1.3: after a real node restart, another swipe and PIN refused the retained transaction; logs and backend checks confirmed no send or replacement.

The hook calls the same LightningService.restart() used by the debug screen. The real stop/start completed while Confirm remained open. Reapproval then reported “The transaction you reviewed can no longer be sent”; the recipient's transaction history stayed unchanged.

J1.3-2x.2x.mp4

Refusal after the node backing the prepared transaction was replaced.

Send at or below the reviewed fee ✅ J1.4: the unmodified head sent 5,000 sats at the displayed 143-sat fee on the first swipe and PIN, confirmed by backend history.

Transaction e98945d1…32e61353e was the single new backend entry, with a 143-sat fee. No fee-change notice or second authorization appeared. The lower-fee variant passed the focused service tests.

J1.4-2x.2x.mp4

Ordinary send after cancelling a higher-fee review.

Check: Restore the private payment list before another swipe ✅ C1: the focused XCTest suites passed at the unmodified head, including both new regression tests.

Ran PaykitPaymentRequestServiceTests, OnchainSendAttemptServiceTests, SendConfirmationViewTests and SendConfirmationLifecycleTests. The new tests verified that a second swipe consumes the list before broadcasting the same candidate once, and that replacing the payment context during SDK restoration preserves the new context and rejects the stale refusal.

Device coverage is the Initial send fee approval section of J1. Live Paykit request/list delivery was not driven on a device. The SDK-restoration race, spent inputs, request expiry, wallet/amount/request changes, the over-$10 warning selection and a lower prepared fee were covered by focused tests. Payer-identity replacement was checked statically. Hardware-wallet sends remain outside this PR's stated scope.

Coverage: delta 9b8d6e9..f2915cf, both prior findings and the reached send/restoration paths. The unchanged recovery-fault sections of prepared-fee-recovery.md were not rerun.

Twin: bitkit-android#1952 fix: bind send approval to the prepared mining fee matches the fee-approval behavior. Android retains list consumption while its send is suspended; iOS restores the request and consumes the list on the next swipe.

Estimate hook — unpublished test patch

Only the displayed normal-send estimate is lowered to one sat when the debug argument is present. Native preparation, fee comparison, warnings, authentication and broadcast are unchanged. Used for J1.1 and the close leg of J1.2.

diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift
index 0dccb132..79ea5136 100644
--- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift
+++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift
@@ -2725,7 +2725,16 @@ struct SendConfirmationView: View {
                 satsPerVByte: feeRate,
                 utxosToSpend: wallet.selectedUtxos
             )
-            apply(normalFee)
+            #if DEBUG // test hook
+                if ProcessInfo.processInfo.arguments.contains("-review-test-low-estimate") { // test hook
+                    Logger.info("TESTHOOK native estimate \(normalFee); displayed estimate 1", context: "FeeReviewQA") // test hook
+                    apply(1) // test hook
+                } else { // test hook
+                    apply(normalFee) // test hook
+                } // test hook
+            #else // test hook
+                apply(normalFee) // test hook
+            #endif // test hook
         } catch {
             guard isCurrentSend(), !(error is CancellationError) else { return }
             Logger.error("Failed to calculate actual fee: \(error)")
Created new transaction d166619b…3011c5c9 sending 1000sats
Prepared on-chain fee 562 sats exceeds the reviewed 1 sats; asking again
Onchain send result txid: d166619b…3011c5c9
Node-restart hook — unpublished test patch

Adds an explicit marker-controlled call to the real node restart, without replacing an SDK result or changing the approval decision. Used for J1.3 and the fee-edit leg of J1.2; no restart was triggered during the fee-edit leg.

diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift
index 0dccb132..7c300180 100644
--- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift
+++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift
@@ -546,6 +546,21 @@ struct SendConfirmationView: View {
                 // PIN navigation can cancel the view task while authorization is awaiting its result.
                 Task { @MainActor in await startAutomaticPaymentIfNeeded() }
             }
+            .task { // test hook
+                #if DEBUG // test hook
+                    guard ProcessInfo.processInfo.arguments.contains("-review-test-node-restart") else { return } // test hook
+                    let marker = Env.appStorageUrl.appendingPathComponent("qa-restart") // test hook
+                    while !Task.isCancelled { // test hook
+                        if FileManager.default.fileExists(atPath: marker.path) { // test hook
+                            try? FileManager.default.removeItem(at: marker) // test hook
+                            Logger.info("TESTHOOK restarting real node", context: "FeeReviewQA") // test hook
+                            try? await LightningService.shared.restart() // test hook
+                            Logger.info("TESTHOOK real node restart complete", context: "FeeReviewQA") // test hook
+                        } // test hook
+                        do { try await Task.sleep(for: .milliseconds(250)) } catch { return } // test hook
+                    } // test hook
+                #endif // test hook
+            } // test hook
             .onChange(of: isSetupPending) { _, isPending in
                 guard !isPending, preparingRequest == nil, app.contactPaymentContext?.incomingPaymentRequest == nil else { return }
                 Task { @MainActor in
@@ -2725,7 +2740,16 @@ struct SendConfirmationView: View {
                 satsPerVByte: feeRate,
                 utxosToSpend: wallet.selectedUtxos
             )
-            apply(normalFee)
+            #if DEBUG // test hook
+                if ProcessInfo.processInfo.arguments.contains("-review-test-low-estimate") { // test hook
+                    Logger.info("TESTHOOK native estimate \(normalFee); displayed estimate 1", context: "FeeReviewQA") // test hook
+                    apply(1) // test hook
+                } else { // test hook
+                    apply(normalFee) // test hook
+                } // test hook
+            #else // test hook
+                apply(normalFee) // test hook
+            #endif // test hook
         } catch {
             guard isCurrentSend(), !(error is CancellationError) else { return }
             Logger.error("Failed to calculate actual fee: \(error)")
TESTHOOK restarting real node
Node restarted successfully
TESTHOOK real node restart complete
Payment failed: The transaction you reviewed can no longer be sent. Nothing was sent. Review the payment and try again.

Reviewed by gpt-6.1-sol-high

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utAck

@ovitrif

ovitrif commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Merged, as it was approved and green.

@ovitrif
ovitrif merged commit dbb5edb into master Nov 17, 2026
36 of 43 checks passed
@ovitrif
ovitrif deleted the fix/bind-send-approval-to-prepared-fee branch November 17, 2026 16:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: initial send can exceed the reviewed mining fee

4 participants