From a499942c49087f7bdc525bef37280016b411fae3 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 17 Nov 2026 07:45:57 -0300 Subject: [PATCH 1/6] fix: bind send approval to the prepared mining fee 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 --- .../Localization/ar.lproj/Localizable.strings | 3 + .../Localization/ca.lproj/Localizable.strings | 3 + .../Localization/cs.lproj/Localizable.strings | 3 + .../Localization/de.lproj/Localizable.strings | 3 + .../Localization/el.lproj/Localizable.strings | 3 + .../Localization/en.lproj/Localizable.strings | 3 + .../es-419.lproj/Localizable.strings | 3 + .../Localization/es.lproj/Localizable.strings | 3 + .../Localization/fr.lproj/Localizable.strings | 3 + .../Localization/it.lproj/Localizable.strings | 3 + .../Localization/nl.lproj/Localizable.strings | 3 + .../Localization/pl.lproj/Localizable.strings | 3 + .../pt-BR.lproj/Localizable.strings | 3 + .../Localization/pt.lproj/Localizable.strings | 3 + .../Localization/ru.lproj/Localizable.strings | 3 + .../Services/OnchainSendAttemptService.swift | 104 +++++++++- Bitkit/ViewModels/WalletViewModel.swift | 5 + .../Wallets/Send/SendConfirmationView.swift | 116 ++++++++++- .../OnchainSendAttemptServiceTests.swift | 188 ++++++++++++++++++ BitkitTests/SendConfirmationViewTests.swift | 47 +++++ changelog.d/next/1079.fixed.md | 1 + journeys/send/prepared-fee-recovery.md | 9 + 22 files changed, 499 insertions(+), 16 deletions(-) create mode 100644 changelog.d/next/1079.fixed.md diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index a9bf5f528e..eb92bb8a8f 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1314,6 +1314,9 @@ "wallet__onchain_retry_note" = "إعادة محاولة إرسال {amount} sats إلى {address} باستخدام العملات الأصلية نفسها. يبقى مبلغ المستلم دون تغيير. أدخل معدل رسوم الشبكة بوحدة sat/vB. لا يمكن أن ينشئ هذا دفعة منفصلة."; "wallet__onchain_retry_construction" = "لا يمكن دفع هذه الرسوم من العملات الأصلية مع إبقاء مبلغ المستلم دون تغيير، أو أن تلك العملات لم تعد متاحة. اختر معدل رسوم أقل أو انتظر حتى يتم التعرف على الدفعة الأصلية. لم يتم إرسال دفعة منفصلة."; "wallet__onchain_retry_unavailable" = "تعذر تجهيز إعادة المحاولة الآن. ربما وصلت الدفعة الأصلية إلى الشبكة بالفعل. تحقق من اتصالك وأعد محاولة هذه الدفعة الأصلية فقط."; +"wallet__send_fee_increased_title" = "تغيّرت رسوم الشبكة"; +"wallet__send_fee_increased" = "رسوم الشبكة الآن {amount}، وهي أعلى مما عُرض أولاً. لم يُرسل شيء. اسحب مرة أخرى للتأكيد."; +"wallet__send_fee_candidate_unavailable" = "لم يعد من الممكن إرسال المعاملة التي راجعتها. لم يُرسل شيء. راجع الدفعة وحاول مرة أخرى."; "wallet__onchain_retry_invalid_fee" = "أدخل معدل رسوم بعدد صحيح من 1 إلى 4,294,967,295 sat/vB."; "wallet__onchain_retry_max_note" = "إعادة محاولة إرسال {amount} sats إلى {address} باستخدام العملات الأصلية نفسها ومعدل الرسوم الأصلي {fee} sat/vB. إرسال الكل لا يترك عملات لرسوم أعلى دون تقليل مبلغ المستلم. يبقى المبلغ دون تغيير. لا يمكن أن ينشئ هذا دفعة منفصلة."; "usdt__address" = "عنوان المستلم"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index cab3b9b8c6..5a2d5f2e35 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1735,6 +1735,9 @@ "wallet__onchain_retry_note" = "Reintentar {amount} sats a {address} amb les mateixes monedes originals. L'import del destinatari no canvia. Introdueix la taxa de tarifa de xarxa en sat/vB. Això no pot crear un pagament separat."; "wallet__onchain_retry_construction" = "Aquesta tarifa no es pot pagar amb les monedes originals mantenint l'import del destinatari, o aquestes monedes ja no estan disponibles. Tria una taxa de tarifa més baixa o espera que es reconegui el pagament original. No s'ha enviat cap pagament separat."; "wallet__onchain_retry_unavailable" = "Ara mateix no s'ha pogut preparar el reintent. És possible que el pagament original ja hagi arribat a la xarxa. Comprova la connexió i reintenta només aquest pagament original."; +"wallet__send_fee_increased_title" = "La tarifa de xarxa ha canviat"; +"wallet__send_fee_increased" = "La tarifa de xarxa ara és de {amount}, més alta que la mostrada inicialment. No s'ha enviat res. Torna a desplaçar per confirmar."; +"wallet__send_fee_candidate_unavailable" = "La transacció que has revisat ja no es pot enviar. No s'ha enviat res. Revisa el pagament i torna-ho a provar."; "wallet__onchain_retry_invalid_fee" = "Introdueix una taxa de tarifa sencera entre 1 i 4.294.967.295 sat/vB."; "wallet__onchain_retry_max_note" = "Reintentar {amount} sats a {address} amb les mateixes monedes originals i la taxa de tarifa original de {fee} sat/vB. Enviar-ho tot no deixa monedes per a una tarifa més alta sense reduir l'import del destinatari. L'import no canvia. Això no pot crear un pagament separat."; "usdt__address" = "Adreça del destinatari"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 2c0e23fbaf..5dbb5c7825 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1875,6 +1875,9 @@ "wallet__onchain_retry_note" = "Zopakovat {amount} sats na {address} se stejnými původními mincemi. Částka pro příjemce zůstane beze změny. Zadejte sazbu síťového poplatku v sat/vB. Tímto nelze vytvořit samostatnou platbu."; "wallet__onchain_retry_construction" = "Tento poplatek nelze zaplatit z původních mincí bez změny částky pro příjemce, nebo tyto mince již nejsou k dispozici. Zvolte nižší sazbu poplatku nebo počkejte, až bude původní platba rozpoznána. Žádná samostatná platba nebyla odeslána."; "wallet__onchain_retry_unavailable" = "Opakování se teď nepodařilo připravit. Původní platba se už mohla dostat do sítě. Zkontrolujte připojení a opakujte pouze tuto původní platbu."; +"wallet__send_fee_increased_title" = "Síťový poplatek se změnil"; +"wallet__send_fee_increased" = "Síťový poplatek je nyní {amount}, tedy vyšší, než bylo původně zobrazeno. Nic nebylo odesláno. Pro potvrzení přejeďte znovu."; +"wallet__send_fee_candidate_unavailable" = "Transakci, kterou jste zkontrolovali, už nelze odeslat. Nic nebylo odesláno. Zkontrolujte platbu a zkuste to znovu."; "wallet__onchain_retry_invalid_fee" = "Zadejte sazbu poplatku jako celé číslo od 1 do 4 294 967 295 sat/vB."; "wallet__onchain_retry_max_note" = "Zopakovat {amount} sats na {address} se stejnými původními mincemi a původní sazbou poplatku {fee} sat/vB. Odeslání všeho nenechává žádné mince na vyšší poplatek bez snížení částky pro příjemce. Částka zůstane beze změny. Tímto nelze vytvořit samostatnou platbu."; "usdt__address" = "Adresa příjemce"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 63a28d949d..d738f724a9 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1872,6 +1872,9 @@ "wallet__onchain_retry_note" = "Sende {amount} sats erneut an {address} mit denselben ursprünglichen Coins. Der Empfängerbetrag bleibt unverändert. Gib den Netzwerkgebührensatz in sat/vB ein. Dadurch kann keine separate Zahlung entstehen."; "wallet__onchain_retry_construction" = "Diese Gebühr kann nicht aus den ursprünglichen Coins bezahlt werden, ohne den Empfängerbetrag zu ändern, oder diese Coins sind nicht mehr verfügbar. Wähle einen niedrigeren Gebührensatz oder warte, bis die ursprüngliche Zahlung erkannt wird. Es wurde keine separate Zahlung gesendet."; "wallet__onchain_retry_unavailable" = "Die Wiederholung konnte gerade nicht vorbereitet werden. Die ursprüngliche Zahlung hat das Netzwerk möglicherweise bereits erreicht. Überprüfe deine Verbindung und wiederhole nur diese ursprüngliche Zahlung."; +"wallet__send_fee_increased_title" = "Netzwerkgebühr geändert"; +"wallet__send_fee_increased" = "Die Netzwerkgebühr beträgt jetzt {amount} und ist höher als zuerst angezeigt. Es wurde nichts gesendet. Wische erneut, um zu bestätigen."; +"wallet__send_fee_candidate_unavailable" = "Die geprüfte Transaktion kann nicht mehr gesendet werden. Es wurde nichts gesendet. Überprüfe die Zahlung und versuche es erneut."; "wallet__onchain_retry_invalid_fee" = "Gib einen ganzzahligen Gebührensatz von 1 bis 4.294.967.295 sat/vB ein."; "wallet__onchain_retry_max_note" = "Sende {amount} sats erneut an {address} mit denselben ursprünglichen Coins und dem ursprünglichen Gebührensatz von {fee} sat/vB. „Alles senden“ lässt keine Coins für eine höhere Gebühr übrig, ohne den Empfängerbetrag zu verringern. Der Betrag bleibt unverändert. Dadurch kann keine separate Zahlung entstehen."; "usdt__address" = "Empfängeradresse"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 0fe2e3b2f1..99b308f49a 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1606,6 +1606,9 @@ "wallet__onchain_retry_note" = "Επανάληψη {amount} sats προς {address} με τα ίδια αρχικά νομίσματα. Το ποσό του παραλήπτη παραμένει ίδιο. Εισαγάγετε το ποσοστό τέλους δικτύου σε sat/vB. Αυτό δεν μπορεί να δημιουργήσει ξεχωριστή πληρωμή."; "wallet__onchain_retry_construction" = "Αυτό το τέλος δεν μπορεί να πληρωθεί από τα αρχικά νομίσματα χωρίς να αλλάξει το ποσό του παραλήπτη ή αυτά τα νομίσματα δεν είναι πλέον διαθέσιμα. Επιλέξτε χαμηλότερο ποσοστό τέλους ή περιμένετε να αναγνωριστεί η αρχική πληρωμή. Δεν στάλθηκε ξεχωριστή πληρωμή."; "wallet__onchain_retry_unavailable" = "Δεν ήταν δυνατή η προετοιμασία της επανάληψης αυτή τη στιγμή. Η αρχική πληρωμή μπορεί να έχει ήδη φτάσει στο δίκτυο. Ελέγξτε τη σύνδεσή σας και επαναλάβετε μόνο αυτή την αρχική πληρωμή."; +"wallet__send_fee_increased_title" = "Το τέλος δικτύου άλλαξε"; +"wallet__send_fee_increased" = "Το τέλος δικτύου είναι τώρα {amount}, υψηλότερο από αυτό που εμφανίστηκε αρχικά. Δεν στάλθηκε τίποτα. Σύρε ξανά για επιβεβαίωση."; +"wallet__send_fee_candidate_unavailable" = "Η συναλλαγή που έλεγξες δεν μπορεί πλέον να σταλεί. Δεν στάλθηκε τίποτα. Έλεγξε την πληρωμή και δοκίμασε ξανά."; "wallet__onchain_retry_invalid_fee" = "Εισαγάγετε ακέραιο ποσοστό τέλους από 1 έως 4.294.967.295 sat/vB."; "wallet__onchain_retry_max_note" = "Επανάληψη {amount} sats προς {address} με τα ίδια αρχικά νομίσματα και το αρχικό ποσοστό τέλους {fee} sat/vB. Η αποστολή όλων δεν αφήνει νομίσματα για υψηλότερο τέλος χωρίς μείωση του ποσού του παραλήπτη. Το ποσό παραμένει ίδιο. Αυτό δεν μπορεί να δημιουργήσει ξεχωριστή πληρωμή."; "usdt__address" = "Διεύθυνση παραλήπτη"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 482c38cc65..8805f4ec74 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1999,6 +1999,9 @@ "wallet__onchain_retry_note" = "Retry {amount} sats to {address} using the same original coins. The recipient amount stays unchanged. Enter the network fee rate in sat/vB. This cannot create a separate payment."; "wallet__onchain_retry_construction" = "This fee cannot be paid from the original coins while keeping the recipient amount unchanged, or those coins are no longer available. Choose a lower fee rate or wait for the original payment to be recognized. No separate payment was sent."; "wallet__onchain_retry_unavailable" = "The retry could not be prepared right now. The original payment may already have reached the network. Check your connection and retry only this original payment."; +"wallet__send_fee_increased_title" = "Network fee changed"; +"wallet__send_fee_increased" = "The network fee is now {amount}, higher than first shown. Nothing was sent. Swipe again to confirm."; +"wallet__send_fee_candidate_unavailable" = "The transaction you reviewed can no longer be sent. Nothing was sent. Review the payment and try again."; "wallet__onchain_retry_invalid_fee" = "Enter a whole-number fee rate from 1 to 4,294,967,295 sat/vB."; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 630318c607..dfffdb4a19 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1878,6 +1878,9 @@ "wallet__onchain_retry_note" = "Reintentar {amount} sats a {address} con las mismas monedas originales. El monto del destinatario no cambia. Introduzca la tarifa de red en sat/vB. Esto no puede crear un pago aparte."; "wallet__onchain_retry_construction" = "Esta comisión no se puede pagar con las monedas originales sin cambiar el monto del destinatario, o esas monedas ya no están disponibles. Elija una tarifa menor o espere a que se reconozca el pago original. No se envió ningún pago aparte."; "wallet__onchain_retry_unavailable" = "No se pudo preparar el reintento en este momento. Es posible que el pago original ya haya llegado a la red. Revise su conexión y reintente solo este pago original."; +"wallet__send_fee_increased_title" = "La comisión de red cambió"; +"wallet__send_fee_increased" = "La comisión de red ahora es de {amount}, más alta que la mostrada al principio. No se envió nada. Deslice de nuevo para confirmar."; +"wallet__send_fee_candidate_unavailable" = "La transacción que revisó ya no se puede enviar. No se envió nada. Revise el pago e inténtelo de nuevo."; "wallet__onchain_retry_invalid_fee" = "Introduzca una tarifa en número entero de 1 a 4,294,967,295 sat/vB."; "wallet__onchain_retry_max_note" = "Reintentar {amount} sats a {address} con las mismas monedas originales y la tarifa original de {fee} sat/vB. Enviar todo no deja monedas para una comisión mayor sin reducir el monto del destinatario. El monto no cambia. Esto no puede crear un pago aparte."; "usdt__address" = "Dirección de destino"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index c366b9d40b..dc9e68b9df 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1756,6 +1756,9 @@ "wallet__onchain_retry_note" = "Reintentar {amount} sats a {address} con las mismas monedas originales. La cantidad del destinatario no cambia. Introduzca la tasa de comisión de red en sat/vB. Esto no puede crear un pago aparte."; "wallet__onchain_retry_construction" = "Esta comisión no se puede pagar con las monedas originales sin cambiar la cantidad del destinatario, o esas monedas ya no están disponibles. Elija una tasa de comisión más baja o espere a que se reconozca el pago original. No se envió ningún pago aparte."; "wallet__onchain_retry_unavailable" = "No se pudo preparar el reintento en este momento. Es posible que el pago original ya haya llegado a la red. Compruebe su conexión y reintente solo este pago original."; +"wallet__send_fee_increased_title" = "La comisión de red ha cambiado"; +"wallet__send_fee_increased" = "La comisión de red es ahora de {amount}, más alta que la mostrada al principio. No se ha enviado nada. Deslice de nuevo para confirmar."; +"wallet__send_fee_candidate_unavailable" = "La transacción que revisó ya no se puede enviar. No se ha enviado nada. Revise el pago e inténtelo de nuevo."; "wallet__onchain_retry_invalid_fee" = "Introduzca una tasa de comisión entera de 1 a 4.294.967.295 sat/vB."; "wallet__onchain_retry_max_note" = "Reintentar {amount} sats a {address} con las mismas monedas originales y la tasa de comisión original de {fee} sat/vB. Enviar todo no deja monedas para una comisión más alta sin reducir la cantidad del destinatario. La cantidad no cambia. Esto no puede crear un pago aparte."; "usdt__address" = "Dirección de destino"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 11573cba94..3f95ea571b 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1886,6 +1886,9 @@ "wallet__onchain_retry_note" = "Réessayer l'envoi de {amount} sats à {address} avec les mêmes UTXO d'origine. Le montant du destinataire reste inchangé. Saisissez le taux de frais de réseau en sat/vB. Cela ne peut pas créer de paiement séparé."; "wallet__onchain_retry_construction" = "Ces frais ne peuvent pas être payés à partir des UTXO d'origine sans modifier le montant du destinataire, ou ces UTXO ne sont plus disponibles. Choisissez un taux de frais plus bas ou attendez que le paiement d'origine soit reconnu. Aucun paiement séparé n'a été envoyé."; "wallet__onchain_retry_unavailable" = "La nouvelle tentative n'a pas pu être préparée pour le moment. Le paiement d'origine a peut-être déjà atteint le réseau. Vérifiez votre connexion et ne réessayez que ce paiement d'origine."; +"wallet__send_fee_increased_title" = "Frais de réseau modifiés"; +"wallet__send_fee_increased" = "Les frais de réseau sont maintenant de {amount}, plus élevés que ceux affichés au départ. Rien n'a été envoyé. Glissez à nouveau pour confirmer."; +"wallet__send_fee_candidate_unavailable" = "La transaction que vous avez vérifiée ne peut plus être envoyée. Rien n'a été envoyé. Vérifiez le paiement et réessayez."; "wallet__onchain_retry_invalid_fee" = "Saisissez un taux de frais entier compris entre 1 et 4 294 967 295 sat/vB."; "wallet__onchain_retry_max_note" = "Réessayer l'envoi de {amount} sats à {address} avec les mêmes UTXO d'origine et le taux de frais d'origine de {fee} sat/vB. Un envoi total ne laisse aucun UTXO pour des frais plus élevés sans réduire le montant du destinataire. Le montant reste inchangé. Cela ne peut pas créer de paiement séparé."; "usdt__address" = "Adresse du destinataire"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index c8e9af9ad0..cfe3e0090d 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1845,6 +1845,9 @@ "wallet__onchain_retry_note" = "Riprova a inviare {amount} sats a {address} usando gli stessi coin originali. L'importo per il destinatario resta invariato. Inserisci il tasso di commissione di rete in sat/vB. Questo non può creare un pagamento separato."; "wallet__onchain_retry_construction" = "Questa commissione non può essere pagata con i coin originali mantenendo invariato l'importo per il destinatario, oppure quei coin non sono più disponibili. Scegli un tasso di commissione più basso o attendi che il pagamento originale venga riconosciuto. Nessun pagamento separato è stato inviato."; "wallet__onchain_retry_unavailable" = "Non è stato possibile preparare il nuovo tentativo in questo momento. Il pagamento originale potrebbe aver già raggiunto la rete. Controlla la connessione e riprova solo questo pagamento originale."; +"wallet__send_fee_increased_title" = "Commissione di rete cambiata"; +"wallet__send_fee_increased" = "La commissione di rete ora è di {amount}, più alta di quella mostrata all'inizio. Non è stato inviato nulla. Scorri di nuovo per confermare."; +"wallet__send_fee_candidate_unavailable" = "La transazione che hai verificato non può più essere inviata. Non è stato inviato nulla. Controlla il pagamento e riprova."; "wallet__onchain_retry_invalid_fee" = "Inserisci un tasso di commissione intero da 1 a 4.294.967.295 sat/vB."; "wallet__onchain_retry_max_note" = "Riprova a inviare {amount} sats a {address} usando gli stessi coin originali e il tasso di commissione originale di {fee} sat/vB. Inviando tutto non restano coin per una commissione più alta senza ridurre l'importo per il destinatario. L'importo resta invariato. Questo non può creare un pagamento separato."; "usdt__address" = "Indirizzo destinatario"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 5008eb1f11..0e95b13390 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1880,6 +1880,9 @@ "wallet__onchain_retry_note" = "Probeer {amount} sats naar {address} opnieuw met dezelfde oorspronkelijke coins. Het bedrag voor de ontvanger blijft ongewijzigd. Voer het netwerkvergoedingstarief in sat/vB in. Dit kan geen aparte betaling aanmaken."; "wallet__onchain_retry_construction" = "Deze vergoeding kan niet uit de oorspronkelijke coins worden betaald zonder het bedrag voor de ontvanger te wijzigen, of die coins zijn niet meer beschikbaar. Kies een lager vergoedingstarief of wacht tot de oorspronkelijke betaling wordt herkend. Er is geen aparte betaling verzonden."; "wallet__onchain_retry_unavailable" = "De nieuwe poging kon nu niet worden voorbereid. De oorspronkelijke betaling heeft het netwerk mogelijk al bereikt. Controleer uw verbinding en probeer alleen deze oorspronkelijke betaling opnieuw."; +"wallet__send_fee_increased_title" = "Netwerkvergoeding gewijzigd"; +"wallet__send_fee_increased" = "De netwerkvergoeding is nu {amount}, hoger dan eerst werd getoond. Er is niets verzonden. Veeg opnieuw om te bevestigen."; +"wallet__send_fee_candidate_unavailable" = "De transactie die u hebt gecontroleerd, kan niet meer worden verzonden. Er is niets verzonden. Controleer de betaling en probeer het opnieuw."; "wallet__onchain_retry_invalid_fee" = "Voer een vergoedingstarief in als geheel getal van 1 tot 4.294.967.295 sat/vB."; "wallet__onchain_retry_max_note" = "Probeer {amount} sats naar {address} opnieuw met dezelfde oorspronkelijke coins en het oorspronkelijke vergoedingstarief van {fee} sat/vB. Bij alles versturen blijven er geen coins over voor een hogere vergoeding zonder het bedrag voor de ontvanger te verlagen. Het bedrag blijft ongewijzigd. Dit kan geen aparte betaling aanmaken."; "usdt__address" = "Adres ontvanger"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index de45358138..93e0bf6045 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1885,6 +1885,9 @@ "wallet__onchain_retry_note" = "Ponów wysłanie {amount} sats na {address} przy użyciu tych samych oryginalnych monet. Kwota dla odbiorcy pozostaje bez zmian. Wprowadź stawkę opłaty sieciowej w sat/vB. Nie może to utworzyć osobnej płatności."; "wallet__onchain_retry_construction" = "Tej opłaty nie można pokryć z oryginalnych monet bez zmiany kwoty dla odbiorcy lub te monety nie są już dostępne. Wybierz niższą stawkę opłaty lub poczekaj, aż oryginalna płatność zostanie rozpoznana. Nie wysłano osobnej płatności."; "wallet__onchain_retry_unavailable" = "Nie udało się teraz przygotować ponowienia. Oryginalna płatność mogła już dotrzeć do sieci. Sprawdź połączenie i ponów tylko tę oryginalną płatność."; +"wallet__send_fee_increased_title" = "Opłata sieciowa się zmieniła"; +"wallet__send_fee_increased" = "Opłata sieciowa wynosi teraz {amount} i jest wyższa niż pokazana na początku. Nic nie zostało wysłane. Przesuń ponownie, aby potwierdzić."; +"wallet__send_fee_candidate_unavailable" = "Sprawdzonej transakcji nie można już wysłać. Nic nie zostało wysłane. Sprawdź płatność i spróbuj ponownie."; "wallet__onchain_retry_invalid_fee" = "Wprowadź stawkę opłaty jako liczbę całkowitą od 1 do 4 294 967 295 sat/vB."; "wallet__onchain_retry_max_note" = "Ponów wysłanie {amount} sats na {address} przy użyciu tych samych oryginalnych monet i oryginalnej stawki opłaty {fee} sat/vB. Wysłanie wszystkiego nie zostawia monet na wyższą opłatę bez zmniejszenia kwoty dla odbiorcy. Kwota pozostaje bez zmian. Nie może to utworzyć osobnej płatności."; "usdt__address" = "Adres odbiorcy"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 11b3dc6cca..3bf8888663 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1886,6 +1886,9 @@ "wallet__onchain_retry_note" = "Tentar novamente {amount} sats para {address} usando as mesmas moedas originais. O valor do destinatário permanece inalterado. Digite a taxa de rede em sat/vB. Isso não pode criar um pagamento separado."; "wallet__onchain_retry_construction" = "Esta taxa não pode ser paga com as moedas originais mantendo o valor do destinatário inalterado, ou essas moedas não estão mais disponíveis. Escolha uma taxa menor ou aguarde o pagamento original ser reconhecido. Nenhum pagamento separado foi enviado."; "wallet__onchain_retry_unavailable" = "Não foi possível preparar a nova tentativa agora. O pagamento original pode já ter chegado à rede. Verifique sua conexão e tente novamente apenas este pagamento original."; +"wallet__send_fee_increased_title" = "Taxa de rede alterada"; +"wallet__send_fee_increased" = "A taxa de rede agora é de {amount}, mais alta do que a exibida inicialmente. Nada foi enviado. Deslize novamente para confirmar."; +"wallet__send_fee_candidate_unavailable" = "A transação que você revisou não pode mais ser enviada. Nada foi enviado. Revise o pagamento e tente novamente."; "wallet__onchain_retry_invalid_fee" = "Digite uma taxa em número inteiro de 1 a 4.294.967.295 sat/vB."; "wallet__onchain_retry_max_note" = "Tentar novamente {amount} sats para {address} usando as mesmas moedas originais e a taxa original de {fee} sat/vB. Enviar tudo não deixa moedas para uma taxa maior sem reduzir o valor do destinatário. O valor permanece inalterado. Isso não pode criar um pagamento separado."; "usdt__address" = "Endereço do destinatário"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index f8dccee67c..60f8ed70a2 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1532,6 +1532,9 @@ "wallet__onchain_retry_note" = "Repetir {amount} sats para {address} com as mesmas moedas originais. O montante do destinatário mantém-se. Introduza a taxa de rede em sat/vB. Isto não pode criar um pagamento separado."; "wallet__onchain_retry_construction" = "Esta taxa não pode ser paga com as moedas originais sem alterar o montante do destinatário, ou essas moedas já não estão disponíveis. Escolha uma taxa mais baixa ou aguarde que o pagamento original seja reconhecido. Não foi enviado nenhum pagamento separado."; "wallet__onchain_retry_unavailable" = "Não foi possível preparar a repetição neste momento. O pagamento original pode já ter chegado à rede. Verifique a ligação e repita apenas este pagamento original."; +"wallet__send_fee_increased_title" = "A taxa de rede mudou"; +"wallet__send_fee_increased" = "A taxa de rede é agora de {amount}, mais alta do que a apresentada inicialmente. Nada foi enviado. Deslize novamente para confirmar."; +"wallet__send_fee_candidate_unavailable" = "A transação que reviu já não pode ser enviada. Nada foi enviado. Reveja o pagamento e tente novamente."; "wallet__onchain_retry_invalid_fee" = "Introduza uma taxa em número inteiro entre 1 e 4 294 967 295 sat/vB."; "wallet__onchain_retry_max_note" = "Repetir {amount} sats para {address} com as mesmas moedas originais e a taxa original de {fee} sat/vB. Enviar tudo não deixa moedas para uma taxa mais alta sem reduzir o montante do destinatário. O montante mantém-se. Isto não pode criar um pagamento separado."; "usdt__address" = "Endereço do destinatário"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index f5eaecbf12..6228bc88c3 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1866,6 +1866,9 @@ "wallet__onchain_retry_note" = "Повторить {amount} sats на {address} с теми же исходными монетами. Сумма получателя не изменится. Введите ставку сетевой комиссии в sat/vB. Это не может создать отдельный платёж."; "wallet__onchain_retry_construction" = "Эту комиссию нельзя оплатить из исходных монет, не изменив сумму получателя, или эти монеты больше недоступны. Выберите меньшую ставку комиссии или дождитесь, пока исходный платёж будет обнаружен. Отдельный платёж не отправлялся."; "wallet__onchain_retry_unavailable" = "Сейчас не удалось подготовить повтор. Исходный платёж, возможно, уже попал в сеть. Проверьте подключение и повторяйте только этот исходный платёж."; +"wallet__send_fee_increased_title" = "Комиссия сети изменилась"; +"wallet__send_fee_increased" = "Комиссия сети теперь {amount} — выше, чем было показано сначала. Ничего не отправлено. Проведите ещё раз для подтверждения."; +"wallet__send_fee_candidate_unavailable" = "Проверенную транзакцию больше нельзя отправить. Ничего не отправлено. Проверьте платёж и попробуйте снова."; "wallet__onchain_retry_invalid_fee" = "Введите целую ставку комиссии от 1 до 4 294 967 295 sat/vB."; "wallet__onchain_retry_max_note" = "Повторить {amount} sats на {address} с теми же исходными монетами и исходной ставкой комиссии {fee} sat/vB. При отправке всех средств не остаётся монет на более высокую комиссию без уменьшения суммы получателя. Сумма не изменится. Это не может создать отдельный платёж."; "usdt__address" = "Адрес получателя"; diff --git a/Bitkit/Services/OnchainSendAttemptService.swift b/Bitkit/Services/OnchainSendAttemptService.swift index e802537afe..964fd59276 100644 --- a/Bitkit/Services/OnchainSendAttemptService.swift +++ b/Bitkit/Services/OnchainSendAttemptService.swift @@ -6,13 +6,25 @@ import LDKNode protocol OnchainSending { var currentWalletIndex: Int { get } var onchainDispatchNode: AnyObject? { get } + /// The coins the wallet can spend now, nil when the sender cannot tell. + func spendableOnchainInputs() async throws -> Set? func prepareOnchainSend(address: String, sats: UInt64, satsPerVbyte: UInt32, utxosToSpend: [SpendableUtxo]?, isMaxAmount: Bool, expectedWalletIndex: Int, expectedNode: AnyObject?, paymentDeadline: PaykitPreciseInstant?) async throws -> PreparedOnchainSendDispatch } +extension OnchainSending { + func spendableOnchainInputs() async throws -> Set? { + nil + } +} + extension LightningService: OnchainSending { + func spendableOnchainInputs() async throws -> Set? { + try await Set(listSpendableOutputs().map { OnchainSendInput(txid: $0.outpoint.txid, vout: $0.outpoint.vout) }) + } + func prepareOnchainSend( address: String, sats: UInt64, satsPerVbyte: UInt32, utxosToSpend: [SpendableUtxo]?, isMaxAmount: Bool, @@ -357,6 +369,22 @@ struct SparkFundingChanged: Error { var preparedFeeSats: UInt64? } +/// An initial send refused before broadcast because its prepared transaction pays a higher mining fee than the user +/// reviewed. The service keeps that transaction, so the approval of this fee sends it and not another one. +struct OnchainSendFeeIncreased: Error, Equatable { + let candidateTxid: String + let miningFeeSats: UInt64 + let recipientAmountSats: UInt64 +} + +/// The transaction kept for a renewed approval is gone, belongs to another payment, or spends coins the wallet no +/// longer has. Nothing was sent, and nothing is prepared in its place. +struct OnchainSendCandidateUnavailable: LocalizedError { + var errorDescription: String? { + t("wallet__send_fee_candidate_unavailable") + } +} + struct OnchainSendTransferContext: Codable, Equatable { let clientBalanceSats: UInt64 let txTotalSats: UInt64 @@ -537,6 +565,7 @@ actor OnchainSendAttemptService { private let winningFee: (OnchainSendAttempt) async throws -> UInt64? private let store: any OnchainSendAttemptStoring private var knownAttempt: OnchainSendAttempt? + private var heldCandidate: HeldCandidate? private var nativeDispatchInProgress: UUID? private var requestFollowupInProgress: UUID? private var ordinaryFollowupInProgress: UUID? @@ -594,6 +623,34 @@ actor OnchainSendAttemptService { knownAttempt = restored } + /// A prepared transaction refused for its higher fee, with the payment it was prepared for. + private struct HeldCandidate { + let prepared: PreparedOnchainSendDispatch + let payment: Payment + + struct Payment: Equatable { + let walletIndex: Int + let address: String + let amountSats: UInt64 + let satsPerVbyte: UInt32 + let inputs: Set? + let isMaxAmount: Bool + let requestId: PaykitPaymentRequest.ID? + let paymentIdentity: String? + let paymentDeadline: PaykitPreciseInstant? + } + } + + /// Drops the transaction kept for a renewed approval, as when its send flow is left. + func discardHeldCandidate() { + heldCandidate = nil + } + + /// - Parameters: + /// - reviewedMiningFeeSats: The mining fee the user approved. A prepared transaction paying more is kept and + /// refused with `OnchainSendFeeIncreased` before any broadcast side effect. + /// - reapprovedCandidateTxid: The kept transaction the user approved at its actual fee. Only that transaction is + /// sent; when it cannot be, the send fails with `OnchainSendCandidateUnavailable`. func send( using lightningService: any OnchainSending, address: String, @@ -608,6 +665,8 @@ actor OnchainSendAttemptService { transferContext: OnchainSendTransferContext? = nil, isSparkFunding: Bool = false, approvedMiningFeeSats: UInt64? = nil, + reviewedMiningFeeSats: UInt64? = nil, + reapprovedCandidateTxid: String? = nil, paymentDeadline: PaykitPreciseInstant? = nil, beforeBroadcastAttempt: () async throws -> Void = {}, onPreDispatchFailure: (Error) async throws -> Void = { _ in throw OnchainSendAttemptError.preDispatchCleanupFailed } @@ -615,6 +674,9 @@ actor OnchainSendAttemptService { guard nativeDispatchInProgress == nil else { throw OnchainSendAttemptError.blocked(try? currentAttempt()) } let walletIndex = lightningService.currentWalletIndex let dispatchNode = lightningService.onchainDispatchNode + // Every send either sends the kept transaction or drops it, so it never outlives a later spend of its coins. + let held = heldCandidate + heldCandidate = nil if let prior = try currentAdmissionAttempt(), prior.status == .accepted, let txid = prior.txid, prior.walletId == Self.walletId(index: walletIndex), prior.recoveryContext?.paymentIdentity == nil || prior.recoveryContext?.paymentIdentity == paymentIdentity, @@ -622,6 +684,18 @@ actor OnchainSendAttemptService { { return .accepted(txid: txid) } + let payment = HeldCandidate.Payment( + walletIndex: walletIndex, address: address, amountSats: amountSats, satsPerVbyte: satsPerVbyte, + inputs: utxosToSpend.map { Set($0.map { OnchainSendInput(txid: $0.outpoint.txid, vout: $0.outpoint.vout) }) }, + isMaxAmount: isMaxAmount, requestId: requestId, paymentIdentity: paymentIdentity, paymentDeadline: paymentDeadline + ) + var reapproved: PreparedOnchainSendDispatch? + if let reapprovedCandidateTxid { + guard let held, held.prepared.txid == reapprovedCandidateTxid, held.payment == payment else { + throw OnchainSendAttemptError.preDispatch(OnchainSendCandidateUnavailable()) + } + reapproved = held.prepared + } let attemptId = try admit( walletId: Self.walletId(index: walletIndex), requestId: requestId, @@ -637,11 +711,22 @@ actor OnchainSendAttemptService { defer { nativeDispatchInProgress = nil } let prepared: PreparedOnchainSendDispatch do { - prepared = try await lightningService.prepareOnchainSend( - address: address, sats: amountSats, satsPerVbyte: satsPerVbyte, - utxosToSpend: utxosToSpend, isMaxAmount: isMaxAmount, - expectedWalletIndex: walletIndex, expectedNode: dispatchNode, paymentDeadline: paymentDeadline - ) + if let reapproved { + // The approved transaction is sent as it is, or not at all. + try checkWallet(lightningService, index: walletIndex, node: dispatchNode) + if let spendable = try await lightningService.spendableOnchainInputs(), + !Set(reapproved.inputs).isSubset(of: spendable) + { + throw OnchainSendCandidateUnavailable() + } + prepared = reapproved + } else { + prepared = try await lightningService.prepareOnchainSend( + address: address, sats: amountSats, satsPerVbyte: satsPerVbyte, + utxosToSpend: utxosToSpend, isMaxAmount: isMaxAmount, + expectedWalletIndex: walletIndex, expectedNode: dispatchNode, paymentDeadline: paymentDeadline + ) + } do { try validateReceipt(prepared, amount: isMaxAmount && requestId == nil ? nil : amountSats, inputs: isMaxAmount ? nil : utxosToSpend? @@ -662,6 +747,15 @@ actor OnchainSendAttemptService { let approvedFee = approvedMiningFeeSats ?? followupContext?.feeSats, miningFee <= approvedFee else { throw SparkFundingChanged(preparedFeeSats: prepared.miningFeeSats) } } + if let reviewedMiningFeeSats { + guard let miningFee = prepared.miningFeeSats else { throw OnchainSendAttemptError.unresolved } + if miningFee > reviewedMiningFeeSats { + heldCandidate = HeldCandidate(prepared: prepared, payment: payment) + throw OnchainSendFeeIncreased( + candidateTxid: prepared.txid, miningFeeSats: miningFee, recipientAmountSats: prepared.recipientAmountSats + ) + } + } attempt.amountSats = prepared.recipientAmountSats attempt.txid = prepared.txid if let miningFee = prepared.miningFeeSats { diff --git a/Bitkit/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift index be9e3d75db..9c33fd8fe3 100644 --- a/Bitkit/ViewModels/WalletViewModel.swift +++ b/Bitkit/ViewModels/WalletViewModel.swift @@ -812,6 +812,8 @@ class WalletViewModel: ObservableObject { requestId: PaykitPaymentRequest.ID? = nil, paymentIdentity: String? = nil, followupContext: OnchainSendFollowupContext? = nil, + reviewedMiningFeeSats: UInt64? = nil, + reapprovedCandidateTxid: String? = nil, paymentDeadline: PaykitPreciseInstant? = nil, beforeBroadcastAttempt: () async throws -> Void = {}, onPreDispatchFailure: (Error) async throws -> Void = { _ in throw OnchainSendAttemptError.preDispatchCleanupFailed } @@ -836,6 +838,8 @@ class WalletViewModel: ObservableObject { requestId: requestId, paymentIdentity: paymentIdentity, followupContext: followupContext, + reviewedMiningFeeSats: reviewedMiningFeeSats, + reapprovedCandidateTxid: reapprovedCandidateTxid, paymentDeadline: paymentDeadline, beforeBroadcastAttempt: beforeBroadcastAttempt, onPreDispatchFailure: onPreDispatchFailure @@ -2180,6 +2184,7 @@ class WalletViewModel: ObservableObject { selectedSpeed = speed isMaxAmountSend = false routingFeeEstimateSats = 0 + Task { await OnchainSendAttemptService.shared.discardHeldCandidate() } } func refreshAfterChannelClosed(channelId: LDKNode.ChannelId, reason: LDKNode.ClosureReason?) async { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 7e9f632d8a..e15021550b 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -51,6 +51,38 @@ struct SendConfirmationView: View { @State private var savingsFallbackWalletId: String? @State private var onchainFeeCalculationId: Int? @State private var presentationID: UUID? + @State private var feeReapproval: FeeReapproval? + + /// The prepared transaction a swipe was refused for because it pays a higher mining fee than was shown, with the + /// payment it was prepared for. The next swipe approves its actual fee and sends that same transaction. + struct FeeReapproval: Equatable { + let candidateTxid: String + let address: String + let requestedSats: UInt64 + let isMaxAmount: Bool + let feeRate: UInt32 + let utxos: [SpendableUtxo]? + let recipientAmountSats: UInt64 + let miningFeeSats: UInt64 + + init(_ increased: OnchainSendFeeIncreased, address: String, requestedSats: UInt64, isMaxAmount: Bool, feeRate: UInt32, + utxos: [SpendableUtxo]?) + { + candidateTxid = increased.candidateTxid + self.address = address + self.requestedSats = requestedSats + self.isMaxAmount = isMaxAmount + self.feeRate = feeRate + self.utxos = utxos + recipientAmountSats = increased.recipientAmountSats + miningFeeSats = increased.miningFeeSats + } + + /// Whether the payment on screen is still the one this transaction was prepared for. + func covers(address: String, amountSats: UInt64, feeRate: UInt32?, utxos: [SpendableUtxo]?) -> Bool { + self.address == address && recipientAmountSats == amountSats && self.feeRate == feeRate && self.utxos == utxos + } + } private struct WalletSwitchRun { let id: UUID @@ -259,7 +291,7 @@ struct SendConfirmationView: View { } /// Warning system - private enum WarningType: String, CaseIterable { + enum WarningType: String, CaseIterable { case amount case balance case fee @@ -1687,6 +1719,7 @@ struct SendConfirmationView: View { var originalPaymentIdentity: String? var privatePaymentListOutcome = PrivatePaymentListSendOutcome.definitePreBroadcastFailure var manualAllowanceAttemptId: String? + var onchainSend: (address: String, requestedSats: UInt64, isMaxAmount: Bool)? do { try validateIncomingPaymentRequestContext(contactPaymentContext) @@ -1821,7 +1854,18 @@ struct SendConfirmationView: View { } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { let amount = wallet.sendAmountSats ?? invoice.amountSatoshis wallet.sendAmountSats = amount - let useMaxAmount = await shouldUseMaxOnchainSend(address: invoice.address, amountSats: amount) + let reapproval = feeReapproval.flatMap { + $0.covers(address: invoice.address, amountSats: amount, feeRate: wallet.selectedFeeRateSatsPerVByte, utxos: wallet.selectedUtxos) + ? $0 : nil + } + feeReapproval = nil + let useMaxAmount = if let reapproval { + reapproval.isMaxAmount + } else { + await shouldUseMaxOnchainSend(address: invoice.address, amountSats: amount) + } + let requestedSats = reapproval?.requestedSats ?? amount + onchainSend = (invoice.address, requestedSats, useMaxAmount) let result = try await Self.sendOnchainPayment( request: incomingPaymentRequest, prepareBroadcast: { @@ -1847,7 +1891,7 @@ struct SendConfirmationView: View { send: { beforeBroadcastAttempt in try await wallet.send( address: invoice.address, - sats: amount, + sats: requestedSats, isMaxAmount: useMaxAmount, requestId: incomingPaymentRequest?.id, paymentIdentity: originalPaymentIdentity, followupContext: OnchainSendFollowupContext( @@ -1855,6 +1899,8 @@ struct SendConfirmationView: View { tags: tagManager.selectedTagsArray, contact: contactPublicKey, createdAt: UInt64(Date().timeIntervalSince1970) ), + reviewedMiningFeeSats: UInt64(max(0, transactionFee)), + reapprovedCandidateTxid: reapproval?.candidateTxid, paymentDeadline: incomingPaymentRequest?.submissionDeadline(quoteId: app.paykitPaymentTerms?.quoteId), beforeBroadcastAttempt: beforeBroadcastAttempt, onPreDispatchFailure: { _ in @@ -2026,6 +2072,21 @@ struct SendConfirmationView: View { try? await CoreService.shared.activity.deletePreActivityMetadata(paymentId: paymentId) } + if case let OnchainSendAttemptError.preDispatch(refused) = error, let increased = refused as? OnchainSendFeeIncreased, + let onchainSend, let feeRate = wallet.selectedFeeRateSatsPerVByte + { + reviewIncreasedFee(FeeReapproval( + increased, address: onchainSend.address, requestedSats: onchainSend.requestedSats, + isMaxAmount: onchainSend.isMaxAmount, feeRate: feeRate, utxos: wallet.selectedUtxos + )) + if isAutomatic { + showManualConfirmation(reason: "mining fee increased") + return + } + // Resets the swipe, so the actual fee gets its own swipe, warnings and authentication. + throw CancellationError() + } + navigationPath.append(.failure(SendFailureContext( error: error, retryRoute: .confirm, @@ -2036,6 +2097,28 @@ struct SendConfirmationView: View { } } + /// Shows the fee and amount of the prepared transaction in place of the estimate the refused swipe approved. + private func reviewIncreasedFee(_ reapproval: FeeReapproval) { + Logger.warn( + "Prepared on-chain fee \(reapproval.miningFeeSats) sats exceeds the reviewed \(transactionFee) sats; asking again", + context: "SendConfirmation" + ) + // A fee estimate still running must not replace the actual fee. + feeCalculationId += 1 + feeReapproval = reapproval + transactionFee = Int(clamping: reapproval.miningFeeSats) + if wallet.sendAmountSats != reapproval.recipientAmountSats { + wallet.sendAmountSats = reapproval.recipientAmountSats + } + showDetails = true + app.toast( + type: .info, + title: t("wallet__send_fee_increased_title"), + description: t("wallet__send_fee_increased", variables: ["amount": currency.primaryAmountText(sats: reapproval.miningFeeSats)]), + accessibilityIdentifier: "SendFeeIncreasedToast" + ) + } + private func paymentProofPreparation() throws -> (endpointIdentifier: String, kind: PaykitPaymentProofKind) { switch app.selectedWalletToPayFrom { case .lightning: @@ -2134,14 +2217,8 @@ struct SendConfirmationView: View { // Check if fee > $10 (only for onchain) if leg != nil || app.selectedWalletToPayFrom == .onchain { let fee = leg.map { $0.debitSat.saturatingSub($0.deliveredSat) } ?? UInt64(max(0, transactionFee)) - if let feeUsd = currency.convert(sats: fee, to: "USD"), feeUsd.value > 10.0 { - warnings.append(.fee) - } - - // Check if fee > 50% of send amount - if fee > 0 && fee > amount / 2 { - warnings.append(.feePercentage) - } + let feeUsd = currency.convert(sats: fee, to: "USD") + warnings += Self.feeWarnings(feeSats: fee, amountSats: amount, isOverUsdLimit: feeUsd.map { $0.value > 10.0 } == true) // TODO: add minimum fee warning // Check minimum fee warning @@ -2155,6 +2232,18 @@ struct SendConfirmationView: View { return warnings } + /// The warnings for a fee over $10 or over half of the amount sent. + static func feeWarnings(feeSats: UInt64, amountSats: UInt64, isOverUsdLimit: Bool) -> [WarningType] { + var warnings: [WarningType] = [] + if isOverUsdLimit { + warnings.append(.fee) + } + if feeSats > 0, feeSats > amountSats / 2 { + warnings.append(.feePercentage) + } + return warnings + } + private func showWarnings(_ warnings: [WarningType]) async throws -> Bool { pendingWarnings = warnings @@ -2552,6 +2641,11 @@ struct SendConfirmationView: View { return } + if let feeReapproval, feeReapproval.covers(address: address, amountSats: amountSats, feeRate: feeRate, utxos: wallet.selectedUtxos) { + apply(feeReapproval.miningFeeSats) + return + } + // A swipe before the fee is known would skip the fee warnings and record a zero fee. onchainFeeCalculationId = requestId defer { diff --git a/BitkitTests/OnchainSendAttemptServiceTests.swift b/BitkitTests/OnchainSendAttemptServiceTests.swift index 1bd24052a0..6a49a88350 100644 --- a/BitkitTests/OnchainSendAttemptServiceTests.swift +++ b/BitkitTests/OnchainSendAttemptServiceTests.swift @@ -404,6 +404,189 @@ final class OnchainSendAttemptServiceTests: XCTestCase { } } + /// Sends the reviewed payment of the fee tests below, whose prepared transaction pays a 212 sat mining fee. + private func sendReviewed( + _ service: OnchainSendAttemptService, sender: PreparedAttemptNodeMock, reviewedFee: UInt64, + reapproved: String? = nil, amountSats: UInt64 = 1000, requestId: PaykitPaymentRequest.ID? = nil, + paymentDeadline: PaykitPreciseInstant? = nil, + beforeBroadcastAttempt: () async throws -> Void = {}, + onPreDispatchFailure: (Error) async throws -> Void = { _ in } + ) async throws -> OnchainSendResult { + try await service.send( + using: sender, address: "bcrt1qexample", amountSats: amountSats, satsPerVbyte: 1, utxosToSpend: nil, + isMaxAmount: false, requestId: requestId, paymentIdentity: requestId == nil ? nil : "payer", + followupContext: .init(feeSats: reviewedFee, feeRate: 1, tags: [], contact: nil, createdAt: 1), + reviewedMiningFeeSats: reviewedFee, reapprovedCandidateTxid: reapproved, paymentDeadline: paymentDeadline, + beforeBroadcastAttempt: beforeBroadcastAttempt, onPreDispatchFailure: onPreDispatchFailure + ) + } + + private func reviewedSender() -> PreparedAttemptNodeMock { + let sender = PreparedAttemptNodeMock() + sender.amount = 1000 + sender.miningFee = 212 + sender.result = .accepted(txid: sender.txid) + return sender + } + + /// Runs the first approval at a 203 sat fee and returns the refusal for the 212 sat transaction it prepared. + private func refusedForHigherFee( + _ service: OnchainSendAttemptService, sender: PreparedAttemptNodeMock, requestId: PaykitPaymentRequest.ID? = nil, + paymentDeadline: PaykitPreciseInstant? = nil + ) async throws -> OnchainSendFeeIncreased { + do { + _ = try await sendReviewed( + service, sender: sender, reviewedFee: 203, requestId: requestId, paymentDeadline: paymentDeadline, + beforeBroadcastAttempt: { XCTFail("A refused fee must not start the request's payment") }, + onPreDispatchFailure: { _ in XCTFail("A refused fee has no started payment to roll back") } + ) + } catch let OnchainSendAttemptError.preDispatch(error) { + return try XCTUnwrap(error as? OnchainSendFeeIncreased, "Refused with \(error)") + } + XCTFail("A 212 sat transaction went out under a 203 sat approval") + throw CancellationError() + } + + func testInitialSendWithAHigherPreparedFeeIsRefusedThenSendsThatTransactionOnceWhenReapproved() async throws { + for requestId: PaykitPaymentRequest.ID? in [nil, .init(paymentRequestId: "request", counterparty: "payee", billingPeriodStartsAt: nil)] { + let store = MemoryAttemptStore() + let service = OnchainSendAttemptService(store: store) + let sender = reviewedSender() + + let increased = try await refusedForHigherFee(service, sender: sender, requestId: requestId) + XCTAssertEqual(increased, OnchainSendFeeIncreased(candidateTxid: sender.txid, miningFeeSats: 212, recipientAmountSats: 1000)) + XCTAssertEqual(sender.broadcasts, 0) + XCTAssertTrue(store.snapshot().isEmpty, "A refused fee must not leave an attempt that blocks later sends") + + // A second preparation would pick this other transaction. + sender.txid = String(repeating: "cd", count: 32) + var requestStarts = 0 + let result = try await sendReviewed( + service, sender: sender, reviewedFee: increased.miningFeeSats, reapproved: increased.candidateTxid, requestId: requestId, + beforeBroadcastAttempt: { + requestStarts += 1 + XCTAssertEqual(store.snapshot().first?.recoveryContext?.candidateTxids, [increased.candidateTxid]) + XCTAssertEqual(store.snapshot().first?.followupContext?.feeSats, 212) + XCTAssertEqual(sender.broadcasts, 0) + } + ) + XCTAssertEqual(result, .accepted(txid: increased.candidateTxid)) + XCTAssertEqual(sender.preparations, 1, "The approved transaction must be sent, not prepared again") + XCTAssertEqual(sender.broadcasts, 1) + XCTAssertEqual(requestStarts, 1) + XCTAssertEqual(store.snapshot().first?.txid, increased.candidateTxid) + XCTAssertEqual(store.snapshot().first?.requestId, requestId) + + do { + _ = try await sendReviewed(service, sender: sender, reviewedFee: 212, reapproved: increased.candidateTxid) + XCTFail("An approval must not send its transaction twice") + } catch let OnchainSendAttemptError.preDispatch(error) { + XCTAssertTrue(error is OnchainSendCandidateUnavailable, "Refused with \(error)") + } + XCTAssertEqual(sender.broadcasts, 1) + } + } + + func testInitialSendAtOrBelowTheReviewedFeeSendsWithoutAnotherApproval() async throws { + for reviewedFee: UInt64 in [212, 213, 5000] { + let store = MemoryAttemptStore() + let service = OnchainSendAttemptService(store: store) + let sender = reviewedSender() + let result = try await sendReviewed(service, sender: sender, reviewedFee: reviewedFee) + XCTAssertEqual(result, .accepted(txid: sender.txid)) + XCTAssertEqual(sender.preparations, 1) + XCTAssertEqual(sender.broadcasts, 1) + XCTAssertEqual(store.snapshot().first?.followupContext?.feeSats, 212) + } + } + + func testCancelledFeeReapprovalSendsNothingAndLeavesLaterSendsFree() async throws { + for discardsExplicitly in [true, false] { + let store = MemoryAttemptStore() + let service = OnchainSendAttemptService(store: store) + let sender = reviewedSender() + let increased = try await refusedForHigherFee(service, sender: sender) + if discardsExplicitly { + await service.discardHeldCandidate() + } + XCTAssertEqual(sender.broadcasts, 0) + XCTAssertTrue(store.snapshot().isEmpty) + let blocking = try await service.blockingAttempt() + XCTAssertNil(blocking) + + // Another payment is prepared on its own and drops the refused transaction. + sender.txid = String(repeating: "cd", count: 32) + sender.result = .accepted(txid: sender.txid) + let next = try await sendReviewed(service, sender: sender, reviewedFee: 212, amountSats: 1000) + XCTAssertEqual(next, .accepted(txid: sender.txid)) + XCTAssertEqual(sender.preparations, 2) + XCTAssertEqual(sender.broadcasts, 1) + try await service.acknowledgeLocalFollowup(txid: sender.txid) + + do { + _ = try await sendReviewed(service, sender: sender, reviewedFee: 212, reapproved: increased.candidateTxid) + XCTFail("A dropped transaction must not be sent or prepared again under its old approval") + } catch let OnchainSendAttemptError.preDispatch(error) { + XCTAssertTrue(error is OnchainSendCandidateUnavailable, "Refused with \(error)") + } + XCTAssertEqual(sender.preparations, 2) + XCTAssertEqual(sender.broadcasts, 1) + } + } + + func testReapprovedTransactionThatCanNoLongerBeSentIsNotRebuilt() async throws { + let deadlineDate = Date(timeIntervalSince1970: 1_800_000_000) + let deadline = PaykitPreciseInstant(date: deadlineDate) + let requestId = PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee", billingPeriodStartsAt: nil) + let changes: [(String, (PreparedAttemptNodeMock) -> Void, (inout UInt64, inout PaykitPaymentRequest.ID?) -> Void)] = [ + ("its coins were spent", { $0.spendable = [] }, { _, _ in }), + ("the request expired", { $0.deadlineClock = { deadlineDate.addingTimeInterval(1) } }, { _, _ in }), + ("the wallet changed", { $0.currentWalletIndex = 1 }, { _, _ in }), + ("the amount changed", { _ in }, { amount, _ in amount = 1001 }), + ("the request changed", { _ in }, { _, request in request = nil }), + ] + for (reason, changeSender, changePayment) in changes { + let store = MemoryAttemptStore() + let service = OnchainSendAttemptService(store: store) + let sender = reviewedSender() + sender.deadlineClock = { deadlineDate.addingTimeInterval(-1) } + sender.spendable = Set(sender.inputs) + let increased = try await refusedForHigherFee(service, sender: sender, requestId: requestId, paymentDeadline: deadline) + changeSender(sender) + var amount: UInt64 = 1000 + var request: PaykitPaymentRequest.ID? = requestId + changePayment(&amount, &request) + do { + _ = try await sendReviewed( + service, sender: sender, reviewedFee: 212, reapproved: increased.candidateTxid, amountSats: amount, + requestId: request, paymentDeadline: deadline + ) + XCTFail("The approved transaction went out although \(reason)") + } catch OnchainSendAttemptError.preDispatch {} + XCTAssertEqual(sender.preparations, 1, "No other transaction may be prepared when \(reason)") + XCTAssertEqual(sender.broadcasts, 0, "Nothing may be sent when \(reason)") + XCTAssertTrue(store.snapshot().isEmpty, "The attempt must be released when \(reason)") + } + } + + func testReapprovalBelowTheActualFeeKeepsTheSameTransactionForAnotherApproval() async throws { + let store = MemoryAttemptStore() + let service = OnchainSendAttemptService(store: store) + let sender = reviewedSender() + let increased = try await refusedForHigherFee(service, sender: sender) + do { + _ = try await sendReviewed(service, sender: sender, reviewedFee: 211, reapproved: increased.candidateTxid) + XCTFail("211 sats do not approve a 212 sat fee") + } catch let OnchainSendAttemptError.preDispatch(error) { + XCTAssertEqual(error as? OnchainSendFeeIncreased, increased) + } + XCTAssertEqual(sender.broadcasts, 0) + let result = try await sendReviewed(service, sender: sender, reviewedFee: 212, reapproved: increased.candidateTxid) + XCTAssertEqual(result, .accepted(txid: increased.candidateTxid)) + XCTAssertEqual(sender.preparations, 1) + XCTAssertEqual(sender.broadcasts, 1) + } + func testPreparedReceiptIsDurableBeforeNativeDispatch() async throws { for max in [false, true] { let store = MemoryAttemptStore() @@ -1750,6 +1933,11 @@ final class PreparedAttemptNodeMock: OnchainSending { var result: OnchainSendResult? var deadlineClock: () -> Date = Date.init var onNativeQueueDispatch: (() -> Void)? + var spendable: Set? + + func spendableOnchainInputs() async throws -> Set? { + spendable + } func prepareOnchainSend(address: String, sats: UInt64, satsPerVbyte: UInt32, utxosToSpend: [SpendableUtxo]?, isMaxAmount: Bool, diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index a1aefad92c..0e24a458c9 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -3,6 +3,53 @@ import LDKNode import XCTest final class SendConfirmationViewTests: XCTestCase { + @MainActor + func testFeeWarningsUseTheFeeOfThePreparedTransactionAfterAFeeIncrease() async throws { + let service = OnchainSendAttemptService(store: MemoryAttemptStore()) + let sender = PreparedAttemptNodeMock() + sender.amount = 1000 + sender.miningFee = 520 + let reviewedFee: UInt64 = 203 + XCTAssertEqual(SendConfirmationView.feeWarnings(feeSats: reviewedFee, amountSats: 1000, isOverUsdLimit: false), []) + + var reapproval: SendConfirmationView.FeeReapproval? + do { + _ = try await service.send( + using: sender, address: "bcrt1qexample", amountSats: 1000, satsPerVbyte: 1, utxosToSpend: nil, + isMaxAmount: false, reviewedMiningFeeSats: reviewedFee + ) + XCTFail("A 520 sat transaction went out under a 203 sat approval") + } catch let OnchainSendAttemptError.preDispatch(error) { + let increased = try XCTUnwrap(error as? OnchainSendFeeIncreased) + reapproval = .init(increased, address: "bcrt1qexample", requestedSats: 1000, isMaxAmount: false, feeRate: 1, utxos: nil) + } + let review = try XCTUnwrap(reapproval) + XCTAssertEqual(review.miningFeeSats, 520) + XCTAssertEqual( + SendConfirmationView.feeWarnings(feeSats: review.miningFeeSats, amountSats: review.recipientAmountSats, isOverUsdLimit: false), + [.feePercentage] + ) + XCTAssertEqual( + SendConfirmationView.feeWarnings(feeSats: review.miningFeeSats, amountSats: review.recipientAmountSats, isOverUsdLimit: true), + [.fee, .feePercentage] + ) + } + + func testFeeReapprovalCoversOnlyThePaymentItsTransactionWasPreparedFor() { + let utxo = SpendableUtxo(outpoint: OutPoint(txid: String(repeating: "a", count: 64), vout: 0), valueSats: 20000) + // A send-all's prepared transaction delivers less once its fee is higher, and that amount is the one reviewed. + let increased = OnchainSendFeeIncreased(candidateTxid: String(repeating: "ab", count: 32), miningFeeSats: 212, recipientAmountSats: 19788) + let review = SendConfirmationView.FeeReapproval( + increased, address: "bcrt1qexample", requestedSats: 19797, isMaxAmount: true, feeRate: 1, utxos: [utxo] + ) + XCTAssertTrue(review.covers(address: "bcrt1qexample", amountSats: 19788, feeRate: 1, utxos: [utxo])) + XCTAssertFalse(review.covers(address: "bcrt1qother", amountSats: 19788, feeRate: 1, utxos: [utxo])) + XCTAssertFalse(review.covers(address: "bcrt1qexample", amountSats: 19797, feeRate: 1, utxos: [utxo])) + XCTAssertFalse(review.covers(address: "bcrt1qexample", amountSats: 19788, feeRate: 2, utxos: [utxo])) + XCTAssertFalse(review.covers(address: "bcrt1qexample", amountSats: 19788, feeRate: nil, utxos: [utxo])) + XCTAssertFalse(review.covers(address: "bcrt1qexample", amountSats: 19788, feeRate: 1, utxos: nil)) + } + func testLightningPaymentRejectsAmountsThatDifferFromTheFixedInvoice() async throws { for (invoiceAmount, reviewedAmount, expectedSend) in [(10000, 1000, false), (10000, 10000, true), (0, 1000, true)] { var sent = false diff --git a/changelog.d/next/1079.fixed.md b/changelog.d/next/1079.fixed.md new file mode 100644 index 0000000000..55259a6a75 --- /dev/null +++ b/changelog.d/next/1079.fixed.md @@ -0,0 +1 @@ +A Bitcoin payment whose mining fee turns out higher than the fee shown on the review screen now shows the actual fee and asks you to confirm again before anything is sent. diff --git a/journeys/send/prepared-fee-recovery.md b/journeys/send/prepared-fee-recovery.md index aff724c65c..1059efef3e 100644 --- a/journeys/send/prepared-fee-recovery.md +++ b/journeys/send/prepared-fee-recovery.md @@ -9,6 +9,15 @@ These checks need a disposable funded regtest wallet and controlled native trans If the winning fee is not already known, an attempt without a retained candidate fee must still wait for verified transaction-history data. The private candidate-fee map is not exported in the shared backup: reset or a new installation uses the existing history fallback, not an imported fee. A retained fee is bookkeeping evidence, never payment-acceptance evidence. +## Initial send fee approval + +The first swipe approves the fee shown on Confirm, which is an estimate. These checks need a controlled fixture in which the transaction prepared after the swipe pays a higher mining fee than that estimate at an unchanged rate, such as wallet coins that change between the estimate and the swipe; an ordinary send does not produce it. + +1. Swipe with payment PIN enabled. Verify nothing is broadcast, Confirm stays open with the higher fee and the actual amount, a "Network fee changed" notice appears (toast id "SendFeeIncreasedToast" on iOS), and no Pending payment or blocked send remains. Swipe again: the over-$10 and over-50% fee warnings must use the higher fee, the PIN or biometric prompt must appear again, and exactly one transaction must reach the backend, paying the fee shown on the second review. +2. After the notice, close the sheet, then separately go Back or change the amount, fee rate or coins. Verify nothing was sent, a new send starts from a fresh estimate, and a Paykit request is still unpaid and payable once. +3. After the notice, spend the wallet's coins another way, let a request expire, or switch wallet or payer identity, then swipe. Verify an error is shown and nothing is sent or silently prepared in its place. +4. Verify a prepared fee equal to or lower than the estimate sends on the first swipe with no notice. + ## Recovery review and authentication Use the retained original payment from the same controlled fixture. Keep transaction history controlled so an original confirmation cannot silently replace the approval being checked. From 45e0765b3407a1b865fd67459b2d16a5233e0375 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 17 Nov 2026 07:59:38 -0300 Subject: [PATCH 2/6] fix: refuse an unusable reapproved send before admission 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 --- Bitkit/Services/LightningService.swift | 3 + .../Services/OnchainSendAttemptService.swift | 26 ++++++-- .../Wallets/Send/SendConfirmationView.swift | 21 +++++- .../OnchainSendAttemptServiceTests.swift | 64 ++++++++++++++----- BitkitTests/SendConfirmationViewTests.swift | 17 +++++ 5 files changed, 108 insertions(+), 23 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 3cb2b07aa1..0cdf90a3f0 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -107,6 +107,8 @@ class LightningService: NodeLifecycleService { private static let watchOnlyAccountHighestPreRevealedAddressIndex: UInt32 = 999 private var node: Node? + /// Runs before the node stops, while its wallet can still release what was prepared on it. + var beforeNodeStop: (() async -> Void)? var onchainDispatchNode: AnyObject? { node } @@ -426,6 +428,7 @@ class LightningService: NodeLifecycleService { } Logger.debug("Stopping node...") + await beforeNodeStop?() try await ServiceQueue.background(.ldk) { try Self.stopReleasingFinishedNode(node.stop) } diff --git a/Bitkit/Services/OnchainSendAttemptService.swift b/Bitkit/Services/OnchainSendAttemptService.swift index 964fd59276..8367c97fc8 100644 --- a/Bitkit/Services/OnchainSendAttemptService.swift +++ b/Bitkit/Services/OnchainSendAttemptService.swift @@ -8,6 +8,8 @@ protocol OnchainSending { var onchainDispatchNode: AnyObject? { get } /// The coins the wallet can spend now, nil when the sender cannot tell. func spendableOnchainInputs() async throws -> Set? + /// Runs `action` before the node stops, while its wallet is still the live one. + func beforeOnchainNodeStops(_ action: @escaping () async -> Void) func prepareOnchainSend(address: String, sats: UInt64, satsPerVbyte: UInt32, utxosToSpend: [SpendableUtxo]?, isMaxAmount: Bool, expectedWalletIndex: Int, expectedNode: AnyObject?, paymentDeadline: PaykitPreciseInstant?) async throws @@ -18,6 +20,8 @@ extension OnchainSending { func spendableOnchainInputs() async throws -> Set? { nil } + + func beforeOnchainNodeStops(_: @escaping () async -> Void) {} } extension LightningService: OnchainSending { @@ -25,6 +29,10 @@ extension LightningService: OnchainSending { try await Set(listSpendableOutputs().map { OnchainSendInput(txid: $0.outpoint.txid, vout: $0.outpoint.vout) }) } + func beforeOnchainNodeStops(_ action: @escaping () async -> Void) { + beforeNodeStop = action + } + func prepareOnchainSend( address: String, sats: UInt64, satsPerVbyte: UInt32, utxosToSpend: [SpendableUtxo]?, isMaxAmount: Bool, @@ -627,6 +635,8 @@ actor OnchainSendAttemptService { private struct HeldCandidate { let prepared: PreparedOnchainSendDispatch let payment: Payment + /// The node that prepared it, the only one that can send it. + let node: AnyObject? struct Payment: Equatable { let walletIndex: Int @@ -641,8 +651,10 @@ actor OnchainSendAttemptService { } } - /// Drops the transaction kept for a renewed approval, as when its send flow is left. - func discardHeldCandidate() { + /// Drops the transaction kept for a renewed approval, as when its send flow is left or its node stops. With a + /// `txid`, only that transaction is dropped. + func discardHeldCandidate(txid: String? = nil) { + guard txid == nil || heldCandidate?.prepared.txid == txid else { return } heldCandidate = nil } @@ -691,7 +703,10 @@ actor OnchainSendAttemptService { ) var reapproved: PreparedOnchainSendDispatch? if let reapprovedCandidateTxid { - guard let held, held.prepared.txid == reapprovedCandidateTxid, held.payment == payment else { + // Checked before admission, so a transaction that cannot be sent leaves no attempt and starts no request payment. + guard let held, held.prepared.txid == reapprovedCandidateTxid, held.payment == payment, held.node === dispatchNode, + (try? PaykitPaymentRequest.checkPaymentDeadline(paymentDeadline)) != nil + else { throw OnchainSendAttemptError.preDispatch(OnchainSendCandidateUnavailable()) } reapproved = held.prepared @@ -750,7 +765,10 @@ actor OnchainSendAttemptService { if let reviewedMiningFeeSats { guard let miningFee = prepared.miningFeeSats else { throw OnchainSendAttemptError.unresolved } if miningFee > reviewedMiningFeeSats { - heldCandidate = HeldCandidate(prepared: prepared, payment: payment) + heldCandidate = HeldCandidate(prepared: prepared, payment: payment, node: dispatchNode) + // Dropping a kept transaction persists through the wallet that prepared it, so it is dropped + // while that wallet's node still runs, never after another instance took over its storage. + lightningService.beforeOnchainNodeStops { [weak self] in await self?.discardHeldCandidate() } throw OnchainSendFeeIncreased( candidateTxid: prepared.txid, miningFeeSats: miningFee, recipientAmountSats: prepared.recipientAmountSats ) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index e15021550b..3c8b207557 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1080,6 +1080,9 @@ struct SendConfirmationView: View { } } + // The fee the warnings and this approval are for; an estimate finishing later must not stand in for it. + let reviewedFeeSats = UInt64(max(0, transactionFee)) + // Validate payment and show warnings if needed let warnings = await validatePayment() if !warnings.isEmpty { @@ -1138,7 +1141,7 @@ struct SendConfirmationView: View { } else if !app.paykitUsesUsdt, let leg = app.paykitRoute?.serviceLeg { await performServiceRoutedPayment(leg) } else { - try await performPayment(isAutomatic: isAutomatic) + try await performPayment(isAutomatic: isAutomatic, reviewedFeeSats: reviewedFeeSats) } } @@ -1703,7 +1706,7 @@ struct SendConfirmationView: View { } } - private func performPayment(isAutomatic: Bool) async throws { + private func performPayment(isAutomatic: Bool, reviewedFeeSats: UInt64) async throws { let paymentActivity = PaykitPaymentActivity.shared.begin() defer { PaykitPaymentActivity.shared.end(paymentActivity) } isSubmittingPayment = true @@ -1899,7 +1902,7 @@ struct SendConfirmationView: View { tags: tagManager.selectedTagsArray, contact: contactPublicKey, createdAt: UInt64(Date().timeIntervalSince1970) ), - reviewedMiningFeeSats: UInt64(max(0, transactionFee)), + reviewedMiningFeeSats: reviewedFeeSats, reapprovedCandidateTxid: reapproval?.candidateTxid, paymentDeadline: incomingPaymentRequest?.submissionDeadline(quoteId: app.paykitPaymentTerms?.quoteId), beforeBroadcastAttempt: beforeBroadcastAttempt, @@ -2075,6 +2078,13 @@ struct SendConfirmationView: View { if case let OnchainSendAttemptError.preDispatch(refused) = error, let increased = refused as? OnchainSendFeeIncreased, let onchainSend, let feeRate = wallet.selectedFeeRateSatsPerVByte { + guard Self.isFeeRefusalCurrent( + presentationID: presentationID, activePresentationID: sheets.activeSheetConfiguration?.presentationID, + address: onchainSend.address, currentAddress: app.scannedOnchainInvoice?.address + ) else { + await OnchainSendAttemptService.shared.discardHeldCandidate(txid: increased.candidateTxid) + return + } reviewIncreasedFee(FeeReapproval( increased, address: onchainSend.address, requestedSats: onchainSend.requestedSats, isMaxAmount: onchainSend.isMaxAmount, feeRate: feeRate, utxos: wallet.selectedUtxos @@ -2097,6 +2107,11 @@ struct SendConfirmationView: View { } } + /// A refusal that returns after its send was closed or replaced has no review to go back to. + static func isFeeRefusalCurrent(presentationID: UUID?, activePresentationID: UUID?, address: String, currentAddress: String?) -> Bool { + presentationID != nil && presentationID == activePresentationID && address == currentAddress + } + /// Shows the fee and amount of the prepared transaction in place of the estimate the refused swipe approved. private func reviewIncreasedFee(_ reapproval: FeeReapproval) { Logger.warn( diff --git a/BitkitTests/OnchainSendAttemptServiceTests.swift b/BitkitTests/OnchainSendAttemptServiceTests.swift index 6a49a88350..959a6810a4 100644 --- a/BitkitTests/OnchainSendAttemptServiceTests.swift +++ b/BitkitTests/OnchainSendAttemptServiceTests.swift @@ -535,40 +535,64 @@ final class OnchainSendAttemptServiceTests: XCTestCase { } func testReapprovedTransactionThatCanNoLongerBeSentIsNotRebuilt() async throws { - let deadlineDate = Date(timeIntervalSince1970: 1_800_000_000) - let deadline = PaykitPreciseInstant(date: deadlineDate) + let future = PaykitPreciseInstant(date: Date().addingTimeInterval(3600)) + let expired = PaykitPreciseInstant(date: Date(timeIntervalSince1970: 1000)) let requestId = PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee", billingPeriodStartsAt: nil) - let changes: [(String, (PreparedAttemptNodeMock) -> Void, (inout UInt64, inout PaykitPaymentRequest.ID?) -> Void)] = [ - ("its coins were spent", { $0.spendable = [] }, { _, _ in }), - ("the request expired", { $0.deadlineClock = { deadlineDate.addingTimeInterval(1) } }, { _, _ in }), - ("the wallet changed", { $0.currentWalletIndex = 1 }, { _, _ in }), - ("the amount changed", { _ in }, { amount, _ in amount = 1001 }), - ("the request changed", { _ in }, { _, request in request = nil }), + typealias Case = ( + reason: String, deadline: PaykitPreciseInstant, refusedBeforeAdmission: Bool, + changeSender: (PreparedAttemptNodeMock) -> Void, changePayment: (inout UInt64, inout PaykitPaymentRequest.ID?) -> Void + ) + let cases: [Case] = [ + ("its coins were spent", future, false, { $0.spendable = [] }, { _, _ in }), + ("the request expired", expired, true, { _ in }, { _, _ in }), + ("the node changed", future, true, { $0.dispatchNode = NSObject() }, { _, _ in }), + ("the wallet changed", future, true, { $0.currentWalletIndex = 1 }, { _, _ in }), + ("the amount changed", future, true, { _ in }, { amount, _ in amount = 1001 }), + ("the request changed", future, true, { _ in }, { _, request in request = nil }), ] - for (reason, changeSender, changePayment) in changes { + for testCase in cases { + let reason = testCase.reason let store = MemoryAttemptStore() let service = OnchainSendAttemptService(store: store) let sender = reviewedSender() - sender.deadlineClock = { deadlineDate.addingTimeInterval(-1) } sender.spendable = Set(sender.inputs) - let increased = try await refusedForHigherFee(service, sender: sender, requestId: requestId, paymentDeadline: deadline) - changeSender(sender) + // The first approval is refused for its fee before any deadline is read. + let increased = try await refusedForHigherFee(service, sender: sender, requestId: requestId, paymentDeadline: testCase.deadline) + testCase.changeSender(sender) var amount: UInt64 = 1000 var request: PaykitPaymentRequest.ID? = requestId - changePayment(&amount, &request) + testCase.changePayment(&amount, &request) + let savesBefore = store.saves do { _ = try await sendReviewed( service, sender: sender, reviewedFee: 212, reapproved: increased.candidateTxid, amountSats: amount, - requestId: request, paymentDeadline: deadline + requestId: request, paymentDeadline: testCase.deadline, + beforeBroadcastAttempt: { XCTFail("The request's payment must not start when \(reason)") }, + onPreDispatchFailure: { _ in XCTFail("No started payment exists to roll back when \(reason)") } ) XCTFail("The approved transaction went out although \(reason)") - } catch OnchainSendAttemptError.preDispatch {} + } catch let OnchainSendAttemptError.preDispatch(error) { + XCTAssertTrue(error is OnchainSendCandidateUnavailable, "Refused with \(error) when \(reason)") + } XCTAssertEqual(sender.preparations, 1, "No other transaction may be prepared when \(reason)") XCTAssertEqual(sender.broadcasts, 0, "Nothing may be sent when \(reason)") XCTAssertTrue(store.snapshot().isEmpty, "The attempt must be released when \(reason)") + if testCase.refusedBeforeAdmission { + XCTAssertEqual(store.saves, savesBefore, "No attempt may be saved when \(reason)") + } } } + func testDiscardingAnotherTransactionKeepsTheOneAwaitingApproval() async throws { + let service = OnchainSendAttemptService(store: MemoryAttemptStore()) + let sender = reviewedSender() + let increased = try await refusedForHigherFee(service, sender: sender) + await service.discardHeldCandidate(txid: String(repeating: "cd", count: 32)) + let result = try await sendReviewed(service, sender: sender, reviewedFee: 212, reapproved: increased.candidateTxid) + XCTAssertEqual(result, .accepted(txid: increased.candidateTxid)) + XCTAssertEqual(sender.preparations, 1) + } + func testReapprovalBelowTheActualFeeKeepsTheSameTransactionForAnotherApproval() async throws { let store = MemoryAttemptStore() let service = OnchainSendAttemptService(store: store) @@ -1823,6 +1847,7 @@ final class OnchainSendAttemptServiceTests: XCTestCase { final class MemoryAttemptStore: OnchainSendAttemptStoring, @unchecked Sendable { private let lock = NSLock() private var attempts: [OnchainSendAttempt] = [] + private var saveCount = 0 var failLoad = false var failSave = false @@ -1841,9 +1866,16 @@ final class MemoryAttemptStore: OnchainSendAttemptStoring, @unchecked Sendable { if failSave { throw MemoryAttemptStoreError.failed } + saveCount += 1 self.attempts = attempts } + var saves: Int { + lock.lock() + defer { lock.unlock() } + return saveCount + } + func snapshot() -> [OnchainSendAttempt] { lock.lock() defer { lock.unlock() } @@ -1911,7 +1943,7 @@ final class AttemptNodeMock: OnchainSending { final class PreparedAttemptNodeMock: OnchainSending { var currentWalletIndex = 0 - let dispatchNode = NSObject() + var dispatchNode = NSObject() var onchainDispatchNode: AnyObject? { dispatchNode } diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 0e24a458c9..d10997b86f 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -35,6 +35,23 @@ final class SendConfirmationViewTests: XCTestCase { ) } + @MainActor + func testFeeRefusalIsIgnoredOnceItsSendWasClosedOrReplaced() { + let presentation = UUID() + XCTAssertTrue(SendConfirmationView.isFeeRefusalCurrent( + presentationID: presentation, activePresentationID: presentation, address: "bcrt1qexample", currentAddress: "bcrt1qexample" + )) + let stale: [(UUID?, String?)] = [(nil, "bcrt1qexample"), (UUID(), "bcrt1qexample"), (presentation, nil), (presentation, "bcrt1qother")] + for (active, address) in stale { + XCTAssertFalse(SendConfirmationView.isFeeRefusalCurrent( + presentationID: presentation, activePresentationID: active, address: "bcrt1qexample", currentAddress: address + )) + } + XCTAssertFalse(SendConfirmationView.isFeeRefusalCurrent( + presentationID: nil, activePresentationID: nil, address: "bcrt1qexample", currentAddress: "bcrt1qexample" + )) + } + func testFeeReapprovalCoversOnlyThePaymentItsTransactionWasPreparedFor() { let utxo = SpendableUtxo(outpoint: OutPoint(txid: String(repeating: "a", count: 64), vout: 0), valueSats: 20000) // A send-all's prepared transaction delivers less once its fee is higher, and that amount is the one reviewed. From 64d3be6dfa011455916ae54246b83e47f1488ebe Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 17 Nov 2026 08:24:24 -0300 Subject: [PATCH 3/6] fix: keep no reviewed send on a node that began stopping 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 --- Bitkit/Services/LightningService.swift | 8 +++- .../Services/OnchainSendAttemptService.swift | 18 +++++++-- .../Wallets/Send/SendConfirmationView.swift | 11 ++++++ .../OnchainSendAttemptServiceTests.swift | 37 +++++++++++++++++++ 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 0cdf90a3f0..95f2b79ef6 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -107,8 +107,14 @@ class LightningService: NodeLifecycleService { private static let watchOnlyAccountHighestPreRevealedAddressIndex: UInt32 = 999 private var node: Node? + private let beforeNodeStopLock = NSLock() + private var beforeNodeStopAction: (() async -> Void)? /// Runs before the node stops, while its wallet can still release what was prepared on it. - var beforeNodeStop: (() async -> Void)? + var beforeNodeStop: (() async -> Void)? { + get { beforeNodeStopLock.withLock { beforeNodeStopAction } } + set { beforeNodeStopLock.withLock { beforeNodeStopAction = newValue } } + } + var onchainDispatchNode: AnyObject? { node } diff --git a/Bitkit/Services/OnchainSendAttemptService.swift b/Bitkit/Services/OnchainSendAttemptService.swift index 8367c97fc8..5250981d23 100644 --- a/Bitkit/Services/OnchainSendAttemptService.swift +++ b/Bitkit/Services/OnchainSendAttemptService.swift @@ -574,6 +574,7 @@ actor OnchainSendAttemptService { private let store: any OnchainSendAttemptStoring private var knownAttempt: OnchainSendAttempt? private var heldCandidate: HeldCandidate? + private weak var stoppingNode: AnyObject? private var nativeDispatchInProgress: UUID? private var requestFollowupInProgress: UUID? private var ordinaryFollowupInProgress: UUID? @@ -658,6 +659,13 @@ actor OnchainSendAttemptService { heldCandidate = nil } + /// Dropping a kept transaction persists through the wallet that prepared it, so it is dropped before that wallet's + /// node stops, and a send still preparing on that node keeps nothing afterwards. + private func nodeStopping(_ node: AnyObject?) { + heldCandidate = nil + stoppingNode = node + } + /// - Parameters: /// - reviewedMiningFeeSats: The mining fee the user approved. A prepared transaction paying more is kept and /// refused with `OnchainSendFeeIncreased` before any broadcast side effect. @@ -711,6 +719,9 @@ actor OnchainSendAttemptService { } reapproved = held.prepared } + if reviewedMiningFeeSats != nil { + lightningService.beforeOnchainNodeStops { [weak self, weak dispatchNode] in await self?.nodeStopping(dispatchNode) } + } let attemptId = try admit( walletId: Self.walletId(index: walletIndex), requestId: requestId, @@ -765,10 +776,11 @@ actor OnchainSendAttemptService { if let reviewedMiningFeeSats { guard let miningFee = prepared.miningFeeSats else { throw OnchainSendAttemptError.unresolved } if miningFee > reviewedMiningFeeSats { + // A node that began stopping while this was prepared can no longer send it. + guard lightningService.onchainDispatchNode === dispatchNode, stoppingNode !== dispatchNode else { + throw OnchainSendCandidateUnavailable() + } heldCandidate = HeldCandidate(prepared: prepared, payment: payment, node: dispatchNode) - // Dropping a kept transaction persists through the wallet that prepared it, so it is dropped - // while that wallet's node still runs, never after another instance took over its storage. - lightningService.beforeOnchainNodeStops { [weak self] in await self?.discardHeldCandidate() } throw OnchainSendFeeIncreased( candidateTxid: prepared.txid, miningFeeSats: miningFee, recipientAmountSats: prepared.recipientAmountSats ) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 3c8b207557..4b64642042 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -2097,6 +2097,17 @@ struct SendConfirmationView: View { throw CancellationError() } + if case let OnchainSendAttemptError.preDispatch(refused) = error, let unavailable = refused as? OnchainSendCandidateUnavailable { + // The kept transaction is gone, so the review goes back to an estimate. + app.toast(type: .error, title: t("common__error"), description: unavailable.localizedDescription) + Task { await calculateTransactionFee() } + if isAutomatic { + showManualConfirmation(reason: "reviewed transaction unavailable") + return + } + throw CancellationError() + } + navigationPath.append(.failure(SendFailureContext( error: error, retryRoute: .confirm, diff --git a/BitkitTests/OnchainSendAttemptServiceTests.swift b/BitkitTests/OnchainSendAttemptServiceTests.swift index 959a6810a4..023f15e177 100644 --- a/BitkitTests/OnchainSendAttemptServiceTests.swift +++ b/BitkitTests/OnchainSendAttemptServiceTests.swift @@ -583,6 +583,37 @@ final class OnchainSendAttemptServiceTests: XCTestCase { } } + func testNodeStopDropsTheKeptTransactionAndASendStillPreparingKeepsNone() async throws { + for stopsWhilePreparing in [false, true] { + let store = MemoryAttemptStore() + let service = OnchainSendAttemptService(store: store) + let sender = reviewedSender() + var candidateTxid = sender.txid + if stopsWhilePreparing { + sender.onPrepare = { await sender.beforeNodeStop?() } + do { + _ = try await sendReviewed(service, sender: sender, reviewedFee: 203) + XCTFail("A 212 sat transaction went out under a 203 sat approval") + } catch let OnchainSendAttemptError.preDispatch(error) { + XCTAssertTrue(error is OnchainSendCandidateUnavailable, "Refused with \(error)") + } + sender.onPrepare = nil + } else { + candidateTxid = try await refusedForHigherFee(service, sender: sender).candidateTxid + await sender.beforeNodeStop?() + } + XCTAssertTrue(store.snapshot().isEmpty) + do { + _ = try await sendReviewed(service, sender: sender, reviewedFee: 212, reapproved: candidateTxid) + XCTFail("A transaction of a stopped node must not be sent") + } catch let OnchainSendAttemptError.preDispatch(error) { + XCTAssertTrue(error is OnchainSendCandidateUnavailable, "Refused with \(error)") + } + XCTAssertEqual(sender.preparations, 1) + XCTAssertEqual(sender.broadcasts, 0) + } + } + func testDiscardingAnotherTransactionKeepsTheOneAwaitingApproval() async throws { let service = OnchainSendAttemptService(store: MemoryAttemptStore()) let sender = reviewedSender() @@ -1971,6 +2002,12 @@ final class PreparedAttemptNodeMock: OnchainSending { spendable } + var beforeNodeStop: (() async -> Void)? + + func beforeOnchainNodeStops(_ action: @escaping () async -> Void) { + beforeNodeStop = action + } + func prepareOnchainSend(address: String, sats: UInt64, satsPerVbyte: UInt32, utxosToSpend: [SpendableUtxo]?, isMaxAmount: Bool, expectedWalletIndex: Int, expectedNode: AnyObject?, From 9b8d6e9c5be4733fe487f6d47b4988e306b6f91a Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 17 Nov 2026 10:22:17 -0300 Subject: [PATCH 4/6] docs: record the initial send fee device findings in the journey Co-Authored-By: Claude Opus 5.5 --- journeys/send/prepared-fee-recovery.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/journeys/send/prepared-fee-recovery.md b/journeys/send/prepared-fee-recovery.md index 1059efef3e..fb307eb063 100644 --- a/journeys/send/prepared-fee-recovery.md +++ b/journeys/send/prepared-fee-recovery.md @@ -11,7 +11,11 @@ If the winning fee is not already known, an attempt without a retained candidate ## Initial send fee approval -The first swipe approves the fee shown on Confirm, which is an estimate. These checks need a controlled fixture in which the transaction prepared after the swipe pays a higher mining fee than that estimate at an unchanged rate, such as wallet coins that change between the estimate and the swipe; an ordinary send does not produce it. +The first swipe approves the fee shown on Confirm, which is an estimate. These checks need a controlled fixture in which the transaction prepared after the swipe pays a higher mining fee than that estimate at an unchanged rate; an ordinary send does not produce it. + +On iOS no device fixture is known. Amount, a BIP21 with an amount and Max all select coins before the estimate and send that stored list, so estimate and prepare spend the same inputs (scanned BIP21 amounts since commit 2a2f798ef). A coin-selection failure near the whole balance stays on Amount or leaves Confirm instead of estimating with no coins; a deposit while Confirm is open is not picked up (the received sheet is skipped while a send is active); a stale Max flag sends the fixed amount from the stored coins. A device run on 2026-11-17 tried manual coin selection, near-balance amounts, BIP21 amounts, deposits while Confirm was open and Max after a deposit: every prepared fee equalled the estimate. Cases 1–3 below are covered by `OnchainSendAttemptServiceTests` and `SendConfirmationViewTests` until a debug fault hook exists. Android reproduces it by depositing a coin while Confirm is open near the whole balance. + +Driving notes for a run on the simulator: `xcodebuildmcp ui-automation tap` reports success without pressing this app's buttons, so use `touch --down --up --delay 0.15` on a fresh snapshot ref (refs go stale after any other action). Drag the swipe handle with `wait-for-ui --identifier GRAB --predicate exists` and `drag --direction right --distance 1 --duration 1`. Max is the Available amount text (`MoneyText`), reached by its label. Enter addresses with Enter Manually: the simulator pasteboard mirrors the host clipboard, so Paste Invoice pastes whatever the host holds. Sending over 50% of the balance shows an "Are You Sure?" dialog before the PIN pad. The payment PIN switch on the PIN-set screen is `ToggleBioForPayments`. Read the app log from the app group's `logs/bitkit_foreground_*.log`: a refusal logs `exceeds the reviewed`, and after a re-approval there must be no new `Created PSBT` for the recipient before `Onchain send result txid`. `./lsp` has no transaction lookup, so confirm a broadcast by mining a block and watching the activity item confirm. 1. Swipe with payment PIN enabled. Verify nothing is broadcast, Confirm stays open with the higher fee and the actual amount, a "Network fee changed" notice appears (toast id "SendFeeIncreasedToast" on iOS), and no Pending payment or blocked send remains. Swipe again: the over-$10 and over-50% fee warnings must use the higher fee, the PIN or biometric prompt must appear again, and exactly one transaction must reach the backend, paying the fee shown on the second review. 2. After the notice, close the sheet, then separately go Back or change the amount, fee rate or coins. Verify nothing was sent, a new send starts from a fresh estimate, and a Paykit request is still unpaid and payable once. From 4be47f63d58031b37540aadf08fd593e602e7dd3 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 17 Nov 2026 12:01:28 -0300 Subject: [PATCH 5/6] fix: consume the payment list again after a fee refusal on confirm Co-Authored-By: Claude Fable 5.2 --- .../Wallets/Send/SendConfirmationView.swift | 10 +++ .../PaykitPaymentRequestServiceTests.swift | 68 +++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 4b64642042..77f5b8e52f 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -2085,6 +2085,7 @@ struct SendConfirmationView: View { await OnchainSendAttemptService.shared.discardHeldCandidate(txid: increased.candidateTxid) return } + await Self.restoreRequestForAnotherSwipe(contactPaymentContext, app: app, manager: paykitPaymentRequestManager) reviewIncreasedFee(FeeReapproval( increased, address: onchainSend.address, requestedSats: onchainSend.requestedSats, isMaxAmount: onchainSend.isMaxAmount, feeRate: feeRate, utxos: wallet.selectedUtxos @@ -2099,6 +2100,7 @@ struct SendConfirmationView: View { if case let OnchainSendAttemptError.preDispatch(refused) = error, let unavailable = refused as? OnchainSendCandidateUnavailable { // The kept transaction is gone, so the review goes back to an estimate. + await Self.restoreRequestForAnotherSwipe(contactPaymentContext, app: app, manager: paykitPaymentRequestManager) app.toast(type: .error, title: t("common__error"), description: unavailable.localizedDescription) Task { await calculateTransactionFee() } if isAutomatic { @@ -2118,6 +2120,14 @@ struct SendConfirmationView: View { } } + /// A refusal that stays on Confirm has released the request's private payment list. The request loses its approval + /// here, so the next swipe prepares it again and consumes that list before anything is sent. + @MainActor + static func restoreRequestForAnotherSwipe(_ context: ContactPaymentContext?, app: AppViewModel, manager: PaykitPaymentRequestManager) async { + guard let context else { return } + await SendSheet.restoreHardwareContactPaymentForRetry(context, app: app, manager: manager) + } + /// A refusal that returns after its send was closed or replaced has no review to go back to. static func isFeeRefusalCurrent(presentationID: UUID?, activePresentationID: UUID?, address: String, currentAddress: String?) -> Bool { presentationID != nil && presentationID == activePresentationID && address == currentAddress diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index b5454dfca1..43ddcce8c5 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -2053,6 +2053,74 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { XCTAssertFalse(manager.isApprovedForPayment(request)) } + @MainActor + func testFeeRefusalOnConfirmConsumesThePaymentListAgainBeforeTheReapprovedSend() async throws { + for swipesAgain in [true, false] { + let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") + let sdk = PaymentRequestSdkMock(records: [record]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.pendingRequests.first) + let app = AppViewModel() + let context = ContactPaymentContext(publicKey: request.counterparty, incomingPaymentRequest: request, endpoints: []) + app.contactPaymentContext = context + let attempts = OnchainSendAttemptService(store: MemoryAttemptStore()) + let sender = PreparedAttemptNodeMock() + sender.amount = 1000 + sender.miningFee = 212 + sender.result = .accepted(txid: sender.txid) + var isListConsumed = false + var consumptions = 0 + let consume = { + XCTAssertFalse(isListConsumed) + isListConsumed = true + consumptions += 1 + } + func swipe(reviewedFee: UInt64, reapproved: String?) async throws -> OnchainSendResult { + let current = try XCTUnwrap(app.contactPaymentContext?.incomingPaymentRequest) + try await manager.prepareForPayment(current, consumePrivatePaymentList: consume) + return try await attempts.send( + using: sender, address: "bcrt1qexample", amountSats: 1000, satsPerVbyte: 1, utxosToSpend: nil, + isMaxAmount: false, requestId: current.id, paymentIdentity: "payer", + reviewedMiningFeeSats: reviewedFee, reapprovedCandidateTxid: reapproved, + beforeBroadcastAttempt: { + XCTAssertTrue(isListConsumed, "The payment list must be consumed before the transaction is sent") + XCTAssertEqual(sender.broadcasts, 0) + }, + onPreDispatchFailure: { _ in } + ) + } + + var candidateTxid: String? + do { + _ = try await swipe(reviewedFee: 203, reapproved: nil) + XCTFail("A 212 sat transaction went out under a 203 sat approval") + } catch let OnchainSendAttemptError.preDispatch(error) { + candidateTxid = (error as? OnchainSendFeeIncreased)?.candidateTxid + } + XCTAssertEqual(consumptions, 1) + // The refusal is a definite pre-broadcast failure, which releases the list. + isListConsumed = false + try await sdk.setRecords([paymentRequestRecord(counterparty: record.counterparty, state: .accepted)]) + await SendConfirmationView.restoreRequestForAnotherSwipe(context, app: app, manager: manager) + XCTAssertEqual(app.contactPaymentContext?.id, context.id) + + guard swipesAgain else { + XCTAssertFalse(isListConsumed, "A cancelled review must leave the list released") + XCTAssertEqual(sender.broadcasts, 0) + continue + } + let result = try await swipe(reviewedFee: 212, reapproved: XCTUnwrap(candidateTxid)) + XCTAssertEqual(result, .accepted(txid: sender.txid)) + XCTAssertEqual(consumptions, 2, "The second swipe must consume the released list again, once") + XCTAssertTrue(isListConsumed) + XCTAssertEqual(sender.preparations, 1) + XCTAssertEqual(sender.broadcasts, 1) + let accepted = await sdk.snapshot().acceptedRequests + XCTAssertEqual(accepted.count, 1, "The request must not be accepted a second time") + } + } + func testApprovedPaymentRechecksBlockingInEachSoftwareSendRouteWithoutRepeatingAcceptance() async throws { let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") let sdk = PaymentRequestSdkMock(records: [record]) From f2915cff28ae35e70caca41ff66418848af56615 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Tue, 17 Nov 2026 12:10:11 -0300 Subject: [PATCH 6/6] fix: recheck the send flow after restoring a refused request Co-Authored-By: Claude Fable 5.2 --- .../Wallets/Send/SendConfirmationView.swift | 32 ++++++++++++----- .../PaykitPaymentRequestServiceTests.swift | 34 ++++++++++++++++++- 2 files changed, 57 insertions(+), 9 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 77f5b8e52f..0dccb13246 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -2078,14 +2078,13 @@ struct SendConfirmationView: View { if case let OnchainSendAttemptError.preDispatch(refused) = error, let increased = refused as? OnchainSendFeeIncreased, let onchainSend, let feeRate = wallet.selectedFeeRateSatsPerVByte { - guard Self.isFeeRefusalCurrent( - presentationID: presentationID, activePresentationID: sheets.activeSheetConfiguration?.presentationID, - address: onchainSend.address, currentAddress: app.scannedOnchainInvoice?.address + guard await Self.restoreRequestForAnotherSwipe( + contactPaymentContext, app: app, manager: paykitPaymentRequestManager, + isCurrentSend: { isCurrentRefusedSend(address: onchainSend.address) } ) else { await OnchainSendAttemptService.shared.discardHeldCandidate(txid: increased.candidateTxid) return } - await Self.restoreRequestForAnotherSwipe(contactPaymentContext, app: app, manager: paykitPaymentRequestManager) reviewIncreasedFee(FeeReapproval( increased, address: onchainSend.address, requestedSats: onchainSend.requestedSats, isMaxAmount: onchainSend.isMaxAmount, feeRate: feeRate, utxos: wallet.selectedUtxos @@ -2100,7 +2099,10 @@ struct SendConfirmationView: View { if case let OnchainSendAttemptError.preDispatch(refused) = error, let unavailable = refused as? OnchainSendCandidateUnavailable { // The kept transaction is gone, so the review goes back to an estimate. - await Self.restoreRequestForAnotherSwipe(contactPaymentContext, app: app, manager: paykitPaymentRequestManager) + guard await Self.restoreRequestForAnotherSwipe( + contactPaymentContext, app: app, manager: paykitPaymentRequestManager, + isCurrentSend: { isCurrentRefusedSend(address: onchainSend?.address) } + ) else { return } app.toast(type: .error, title: t("common__error"), description: unavailable.localizedDescription) Task { await calculateTransactionFee() } if isAutomatic { @@ -2122,10 +2124,24 @@ struct SendConfirmationView: View { /// A refusal that stays on Confirm has released the request's private payment list. The request loses its approval /// here, so the next swipe prepares it again and consumes that list before anything is sent. + /// Returns whether the refused send still owns the flow once that is done: the sheet can close or start another + /// payment while the request is restored, and a refusal must write nothing into that payment. @MainActor - static func restoreRequestForAnotherSwipe(_ context: ContactPaymentContext?, app: AppViewModel, manager: PaykitPaymentRequestManager) async { - guard let context else { return } - await SendSheet.restoreHardwareContactPaymentForRetry(context, app: app, manager: manager) + static func restoreRequestForAnotherSwipe( + _ context: ContactPaymentContext?, app: AppViewModel, manager: PaykitPaymentRequestManager, isCurrentSend: () -> Bool + ) async -> Bool { + if let context { + await SendSheet.restoreHardwareContactPaymentForRetry(context, app: app, manager: manager) + } + return isCurrentSend() + } + + private func isCurrentRefusedSend(address: String?) -> Bool { + guard let address else { return false } + return Self.isFeeRefusalCurrent( + presentationID: presentationID, activePresentationID: sheets.activeSheetConfiguration?.presentationID, + address: address, currentAddress: app.scannedOnchainInvoice?.address + ) } /// A refusal that returns after its send was closed or replaced has no review to go back to. diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index 43ddcce8c5..9d1525349b 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -2102,7 +2102,8 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { // The refusal is a definite pre-broadcast failure, which releases the list. isListConsumed = false try await sdk.setRecords([paymentRequestRecord(counterparty: record.counterparty, state: .accepted)]) - await SendConfirmationView.restoreRequestForAnotherSwipe(context, app: app, manager: manager) + let isCurrent = await SendConfirmationView.restoreRequestForAnotherSwipe(context, app: app, manager: manager) { true } + XCTAssertTrue(isCurrent) XCTAssertEqual(app.contactPaymentContext?.id, context.id) guard swipesAgain else { @@ -2121,6 +2122,37 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { } } + @MainActor + func testFeeRefusalIsDroppedWhenAnotherSendStartsWhileItsRequestIsRestored() async throws { + let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") + let sdk = PaymentRequestSdkMock(records: [record]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.pendingRequests.first) + let app = AppViewModel() + let context = ContactPaymentContext(publicKey: request.counterparty, incomingPaymentRequest: request, endpoints: []) + app.contactPaymentContext = context + try await manager.prepareForPayment(request) + try await sdk.setRecords([paymentRequestRecord(counterparty: record.counterparty, state: .accepted)]) + await sdk.pauseNextPaymentRequestList() + + var ownsFlow = true + let restore = Task { @MainActor in + await SendConfirmationView.restoreRequestForAnotherSwipe(context, app: app, manager: manager) { ownsFlow } + } + try await waitUntil { await sdk.paymentRequestListIsPaused() } + // The sheet is replaced by another payment while the refused one waits on the SDK. + let replacement = ContactPaymentContext(publicKey: "pubkyother") + app.contactPaymentContext = replacement + ownsFlow = false + await sdk.resumePaymentRequestList() + + let isCurrent = await restore.value + XCTAssertFalse(isCurrent, "A refusal must not write its fee and amount into another payment") + XCTAssertEqual(app.contactPaymentContext?.id, replacement.id, "The restored request must not replace the new payment's context") + XCTAssertFalse(manager.isApprovedForPayment(request)) + } + func testApprovedPaymentRechecksBlockingInEachSoftwareSendRouteWithoutRepeatingAcceptance() async throws { let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") let sdk = PaymentRequestSdkMock(records: [record])