diff --git a/asset_sources/default_themes/stack_duo/dark.zip b/asset_sources/default_themes/stack_duo/dark.zip index a44c89cf8b..e7cd9e0647 100644 Binary files a/asset_sources/default_themes/stack_duo/dark.zip and b/asset_sources/default_themes/stack_duo/dark.zip differ diff --git a/asset_sources/default_themes/stack_duo/light.zip b/asset_sources/default_themes/stack_duo/light.zip index 82dc05870e..9824e430c1 100644 Binary files a/asset_sources/default_themes/stack_duo/light.zip and b/asset_sources/default_themes/stack_duo/light.zip differ diff --git a/asset_sources/default_themes/stack_wallet/dark.zip b/asset_sources/default_themes/stack_wallet/dark.zip index a44c89cf8b..e7cd9e0647 100644 Binary files a/asset_sources/default_themes/stack_wallet/dark.zip and b/asset_sources/default_themes/stack_wallet/dark.zip differ diff --git a/asset_sources/default_themes/stack_wallet/light.zip b/asset_sources/default_themes/stack_wallet/light.zip index 82dc05870e..9824e430c1 100644 Binary files a/asset_sources/default_themes/stack_wallet/light.zip and b/asset_sources/default_themes/stack_wallet/light.zip differ diff --git a/integration_test/grin/grin_test_chain_test.dart b/integration_test/grin/grin_test_chain_test.dart index 6f1fb62a39..f4fe8a3464 100644 --- a/integration_test/grin/grin_test_chain_test.dart +++ b/integration_test/grin/grin_test_chain_test.dart @@ -19,6 +19,7 @@ import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/services/node_service.dart'; import 'package:stackwallet/utilities/logger.dart'; @@ -351,11 +352,11 @@ void main() { expect(await alice.pendingSlatepackFor(slateId), s1); final inspected = await bob.inspectSlatepack(s1); - expect(inspected.state, GrinSlateState.s1); - expect(inspected.amount, grin(50).raw); - expect(inspected.sender, aliceAddress); + expect(inspected.state, SlateState.s1); + expect(inspected.amount, grin(50)); + expect(inspected.senderAddress, aliceAddress); final s2 = await bob.receiveSlatepack(s1); - expect(s2.state, GrinSlateState.s2); + expect(s2.state, SlateState.s2); expect(s2.slateId, slateId); await sync(bob); @@ -368,7 +369,7 @@ void main() { expect(bob.info.cachedBalance.pendingSpendable, grin(50)); expect(bob.info.cachedBalance.spendable, grin(0)); - final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + final s3 = await alice.finalizeSlatepack(s2.slatepack!); expect(s3.posted, isTrue); expect(s3.kernelExcess, hasLength(66)); // Posting mined height 16; ten more give it 11 confirmations. @@ -385,7 +386,7 @@ void main() { expect(data[TxV2OdKeys.grinHasStoredTx], isTrue); expect(a.hash, s3.kernelExcess); expect(sent(a), grin(50)); - expect(fee(a), nano(s3.fee)); + expect(fee(a), confirmed.fee); b = await row(bob, slateId); expect(b.height, 16); @@ -406,27 +407,21 @@ void main() { amount: grin(30), payerAddress: aliceAddress, ); - expect(i1.state, GrinSlateState.i1); + expect(i1.state, SlateState.i1); await sync(bob); - var b = await row(bob, i1.slateId); + var b = await row(bob, i1.slateId!); expect(b.type, TransactionType.incoming); expect(label(bob, b), 'Invoice issued (waiting for payer)'); expect(otherData(b)[TxV2OdKeys.grinSlateState], 'I1'); // An amount other than the invoice's is refused before the library is // asked to pay, and nothing is recorded or locked. - await expectLater( - alice.processInvoice( - i1.armoredSlatepack, - confirmedAmount: nano(grin(30).raw - BigInt.one), - ), - throwsA( - predicate( - (e) => e.toString().contains('does not match'), - 'amount mismatch', - ), - ), + final refused = await alice.processInvoice( + i1.slatepack!, + confirmedAmount: nano(grin(30).raw - BigInt.one), ); + expect(refused.success, isFalse); + expect(refused.error, contains('does not match')); expect( chain.backend.calls.where((c) => c.startsWith('processInvoice')), isEmpty, @@ -435,47 +430,47 @@ void main() { expect( await MainDB.instance.isar.transactionV2s .where() - .txidWalletIdEqualTo(i1.slateId, alice.walletId) + .txidWalletIdEqualTo(i1.slateId!, alice.walletId) .findFirst(), isNull, ); expect(alice.info.cachedBalance.spendable, before); final i2 = await alice.processInvoice( - i1.armoredSlatepack, + i1.slatepack!, confirmedAmount: grin(30), ); - expect(i2.state, GrinSlateState.i2); + expect(i2.state, SlateState.i2); expect( chain.backend.calls.where((c) => c.startsWith('processInvoice')), hasLength(1), ); await sync(alice); - var a = await row(alice, i1.slateId); + var a = await row(alice, i1.slateId!); expect(a.type, TransactionType.outgoing); expect(label(alice, a), 'Paying invoice (waiting for invoicer)'); expect(otherData(a)[TxV2OdKeys.grinSlateState], 'I2'); expect(alice.info.cachedBalance.spendable < before, isTrue); - final i3 = await bob.finalizeInvoice(i2.armoredSlatepack); + final i3 = await bob.finalizeInvoice(i2.slatepack!); expect(i3.posted, isTrue); // Posting mined height 16, to Bob. expect(await chain.mine(alice, 10), 26); await sync(alice); await sync(bob); - b = await row(bob, i1.slateId); + b = await row(bob, i1.slateId!); expect(b.height, 16); expect(label(bob, b), 'Received'); expect(received(b), grin(30)); expect(otherData(b)[TxV2OdKeys.grinKernelExcess], i3.kernelExcess); - a = await row(alice, i1.slateId); + a = await row(alice, i1.slateId!); expect(a.height, 16); expect(label(alice, a), 'Sent'); expect(sent(a), grin(30)); - expect(fee(a), nano(i2.fee)); + expect(fee(a), i2.fee!); // Bob also got the block 16 coinbase and the fee. - expect(bob.info.cachedBalance.total, grin(30 + reward) + nano(i2.fee)); + expect(bob.info.cachedBalance.total, grin(30 + reward) + i2.fee!); }, timeout: _timeout); testWidgets('cancelling an unfinalized send unlocks its inputs', ( @@ -491,13 +486,13 @@ void main() { await sync(alice); expect(alice.info.cachedBalance.spendable < before.spendable, isTrue); expect( - label(alice, await row(alice, slate.slateId)), + label(alice, await row(alice, slate.slateId!)), 'Sending (waiting for response)', ); - expect(await alice.cancelPendingTransactionAndPost(slate.slateId), ''); + expect(await alice.cancelPendingTransactionAndPost(slate.slateId!), ''); await sync(alice); - final tx = await row(alice, slate.slateId); + final tx = await row(alice, slate.slateId!); expect(tx.isCancelled, isTrue); expect(label(alice, tx), 'Cancelled'); expect(tx.height, isNull); @@ -506,7 +501,7 @@ void main() { // A second cancel is reported, not thrown. expect( - await alice.cancelPendingTransactionAndPost(slate.slateId), + await alice.cancelPendingTransactionAndPost(slate.slateId!), isNotEmpty, ); }, timeout: _timeout); @@ -522,20 +517,20 @@ void main() { // Nothing is stored to post yet. await sync(alice); - await expectLater(alice.repost(slate.slateId), throwsA(anything)); + await expectLater(alice.repost(slate.slateId!), throwsA(anything)); expect(chain.backend.calls.where((c) => c.startsWith('repost')), isEmpty); - final s2 = await bob.receiveSlatepack(slate.armoredSlatepack); + final s2 = await bob.receiveSlatepack(slate.slatepack!); (await chain.api(alice)).skipNextBroadcast = true; - final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + final s3 = await alice.finalizeSlatepack(s2.slatepack!); expect(s3.posted, isFalse); await sync(alice); - var tx = await row(alice, slate.slateId); + var tx = await row(alice, slate.slateId!); expect(otherData(tx)[TxV2OdKeys.grinHasStoredTx], isTrue); expect(tx.height, isNull); expect(alice.info.cachedChainHeight, 15); - await alice.repost(slate.slateId); + await alice.repost(slate.slateId!); expect( chain.backend.calls.where((c) => c.startsWith('repost')), hasLength(1), @@ -544,7 +539,7 @@ void main() { expect(await chain.mine(alice, 10), 26); await sync(alice); await sync(bob); - tx = await row(alice, slate.slateId); + tx = await row(alice, slate.slateId!); expect(tx.height, 16); expect(label(alice, tx), 'Sent'); expect(otherData(tx)[TxV2OdKeys.grinKernelExcess], s3.kernelExcess); @@ -557,13 +552,13 @@ void main() { amount: grin(25), recipientAddress: await bob.slatepackAddress(), ); - final s2 = await bob.receiveSlatepack(slate.armoredSlatepack); - final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + final s2 = await bob.receiveSlatepack(slate.slatepack!); + final s3 = await alice.finalizeSlatepack(s2.slatepack!); await chain.mine(alice, 1); await sync(alice); await sync(bob); - final json = await alice.exportPaymentProof(slate.slateId); + final json = await alice.exportPaymentProof(slate.slateId!); final proof = GrinPaymentProof.fromJsonString(json); expect(proof.amount, grin(25).raw); expect(proof.excess, s3.kernelExcess); @@ -587,11 +582,11 @@ void main() { ); // The receiving side keeps no proof. expect( - otherData(await row(bob, slate.slateId))[TxV2OdKeys.grinHasPaymentProof], + otherData(await row(bob, slate.slateId!))[TxV2OdKeys.grinHasPaymentProof], isFalse, ); await expectLater( - bob.exportPaymentProof(slate.slateId), + bob.exportPaymentProof(slate.slateId!), throwsA(predicate((e) => e.toString().contains('no payment proof'))), ); }, timeout: _timeout); diff --git a/lib/models/slatepack_models.dart b/lib/models/slatepack_models.dart index c326908bba..8d5f4cb71b 100644 --- a/lib/models/slatepack_models.dart +++ b/lib/models/slatepack_models.dart @@ -176,3 +176,148 @@ class FinalizeResult { ")"; } } + +/// What the confirm screen has to ask, or refuse, before a direct send. +class SlatepackHttpPolicy { + const SlatepackHttpPolicy({ + this.blockedReason, + this.needsClearnetAck = false, + this.needsPlaintextAck = false, + }); + + /// Set when the send cannot go ahead now. Shown to the user. + final String? blockedReason; + + /// The target is reached without Tor and learns the user's IP address. + final bool needsClearnetAck; + + /// The target is a plain http:// URL, readable on the way (also by a Tor + /// exit). + final bool needsPlaintextAck; + + bool get isBlocked => blockedReason != null; +} + +/// Slatepack details of a stored transaction, for the details screen. +class SlatepackTxInfo { + const SlatepackTxInfo({ + this.state = SlateState.unknown, + this.slateId, + this.kernelExcess, + this.counterpartyAddress, + this.ttlCutoffHeight, + this.finalizedAwaitingConfirmation = false, + this.broadcastPosted, + this.canRepost = false, + this.canShowSlatepack = false, + this.hasPaymentProof = false, + }); + + /// The last state the wallet saw. + final SlateState state; + final String? slateId; + final String? kernelExcess; + final String? counterpartyAddress; + final int? ttlCutoffHeight; + + /// Finalized and stored but not seen on chain yet. + final bool finalizedAwaitingConfirmation; + + /// The result of the wallet's last broadcast attempt. Null means that this + /// process did not observe the result. + final bool? broadcastPosted; + + final bool canRepost; + + /// The wallet still has the slatepack the other party needs. + final bool canShowSlatepack; + + final bool hasPaymentProof; + + /// Whether cancelling can release a transaction that is still local. + /// A finalized transaction is cancellable only when this wallet observed + /// that the node rejected its broadcast. An unknown or successful broadcast + /// may still confirm and must not be presented as safely cancellable. + bool get canCancel => finalizedAwaitingConfirmation + ? broadcastPosted == false + : state != SlateState.s3 && state != SlateState.i3; +} + +/// The texts of the dialog that asks before a slatepack transaction is +/// cancelled. +class SlatepackCancelPrompt { + const SlatepackCancelPrompt({ + required this.title, + required this.message, + required this.confirmLabel, + }); + + final String title; + final String message; + final String confirmLabel; + + /// What cancelling does depends on what the other party already holds. + /// [info] is null for wallets that keep no slate state; [incoming] is the + /// direction of the transaction. + factory SlatepackCancelPrompt.of( + SlatepackTxInfo? info, { + required bool incoming, + }) { + final state = info?.state ?? SlateState.unknown; + final String message; + if (info?.finalizedAwaitingConfirmation == true && + info?.broadcastPosted == false) { + message = + "The node did not accept this transaction. Cancelling unlocks its " + "funds in this wallet. If it was posted somewhere else in the " + "meantime, it can still confirm."; + } else if (state == SlateState.i2) { + // An invoice this wallet paid: the payee finalizes alone. + message = + "Cancelling changes this wallet only: the funds it locked become " + "spendable here again. If the payee already has your payment, " + "they can still complete it until those funds are spent in " + "another transaction."; + } else if (state == SlateState.s2 || + (state == SlateState.unknown && incoming)) { + // A payment this wallet answered: the sender finalizes alone. + message = + "Cancelling removes this transaction from this wallet only. If " + "the sender already has your response, they can still complete " + "the payment, and the funds may then only show after a rescan."; + } else { + // This wallet has to finalize, and will not after a cancel. + message = + "The other party can no longer complete it, and any funds it " + "locked become spendable again."; + } + return SlatepackCancelPrompt( + title: "Cancel this transaction?", + message: message, + confirmLabel: "Yes, cancel", + ); + } +} + +/// A checked payment proof. +class PaymentProofCheck { + const PaymentProofCheck({ + required this.amount, + required this.kernelExcess, + required this.senderAddress, + required this.recipientAddress, + required this.isSender, + required this.isRecipient, + }); + + final Amount amount; + final String kernelExcess; + final String senderAddress; + final String recipientAddress; + + /// This wallet's address is the proof's sender. + final bool isSender; + + /// This wallet's address is the proof's recipient. + final bool isRecipient; +} diff --git a/lib/pages/receive_view/receive_view.dart b/lib/pages/receive_view/receive_view.dart index 51875505eb..2feacb24f7 100644 --- a/lib/pages/receive_view/receive_view.dart +++ b/lib/pages/receive_view/receive_view.dart @@ -53,6 +53,7 @@ import '../../widgets/qr.dart'; import '../../widgets/rounded_white_container.dart'; import 'addresses/wallet_addresses_view.dart'; import 'generate_receiving_uri_qr_code_view.dart'; +import '../slatepack/request_invoice_view.dart'; import '../slatepack/slatepack_import_flow.dart'; import 'sub_widgets/slatepack_entry_dialog.dart'; @@ -82,6 +83,7 @@ class _ReceiveViewState extends ConsumerState { late final bool _showMultiType; late bool supportsMweb; SlatepackTerms? _slatepackTerms; + SlatepackInterface? _slatepackWallet; int _currentIndex = 0; @@ -283,6 +285,7 @@ class _ReceiveViewState extends ConsumerState { _supportsSpark = wallet is SparkInterface; if (wallet is SlatepackInterface) { _slatepackTerms = wallet.slatepackTerms; + _slatepackWallet = wallet; } supportsMweb = wallet is MwebInterface && @@ -682,6 +685,13 @@ class _ReceiveViewState extends ConsumerState { ), ), ), + if (_slatepackWallet?.receiveAddressNote != null) ...[ + const SizedBox(height: 8), + Text( + _slatepackWallet!.receiveAddressNote!, + style: STextStyles.label(context), + ), + ], const SizedBox(height: 12), PrimaryButton( label: "Copy address", @@ -718,6 +728,13 @@ class _ReceiveViewState extends ConsumerState { onPressed: _importSlatepack, ), ], + if (_slatepackWallet?.supportsInvoices ?? false) ...[ + const SizedBox(height: 12), + SecondaryButton( + label: "Request payment", + onPressed: () => showRequestInvoice(context, walletId), + ), + ], const SizedBox(height: 30), RoundedWhiteContainer( child: Padding( @@ -726,11 +743,15 @@ class _ReceiveViewState extends ConsumerState { child: Column( children: [ QR( - data: AddressUtils.buildUriString( - coin.uriScheme, - address, - {}, - ), + data: + _slatepackWallet?.receiveQrIsRawAddress ?? + false + ? address + : AddressUtils.buildUriString( + coin.uriScheme, + address, + {}, + ), size: MediaQuery.of(context).size.width / 2, ), const SizedBox(height: 20), diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index f045094c69..a0c5286e2e 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -21,6 +21,7 @@ import '../../models/input.dart'; import '../../models/isar/models/isar_models.dart'; import '../../models/isar/models/transaction_note.dart'; import '../../models/isar/ordinal.dart'; +import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; import '../../pages_desktop_specific/coin_control/desktop_coin_control_use_dialog.dart'; import '../../pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart'; @@ -34,7 +35,10 @@ import '../../utilities/amount/amount.dart'; import '../../utilities/amount/amount_formatter.dart'; import '../../utilities/amount/fee_rate_formatter.dart'; import '../../utilities/constants.dart'; +import '../../utilities/exception_message.dart'; +import '../../utilities/enums/slatepack_method.dart'; import '../../utilities/logger.dart'; +import '../../utilities/route_presentation.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; @@ -45,6 +49,7 @@ import '../../wallets/isar/providers/wallet_info_provider.dart'; import '../../wallets/models/tx_data.dart'; import '../../wallets/wallet/impl/firo_wallet.dart'; import '../../wallets/wallet/impl/solana_wallet.dart'; +import '../../wallets/wallet/supporting/grin/grin_errors.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/ordinals_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; @@ -62,9 +67,11 @@ import '../../widgets/stack_text_field.dart'; import '../../widgets/textfield_icon_button.dart'; import '../../wl_gen/interfaces/libepiccash_interface.dart'; import '../pinpad_views/lock_screen_view.dart'; +import '../slatepack/slatepack_import_flow.dart'; import '../wallet_view/wallet_view.dart'; import 'sub_widgets/multi_recipient.dart'; import 'sub_widgets/sending_transaction_dialog.dart'; +import 'sub_widgets/slatepack_transport_warnings.dart'; import 'sub_widgets/split_transaction_warning.dart'; class ConfirmTransactionView extends ConsumerStatefulWidget { @@ -105,6 +112,10 @@ class ConfirmTransactionView extends ConsumerStatefulWidget { class _ConfirmTransactionViewState extends ConsumerState { + // Direct (http) slatepack sends: transport warnings the user accepted. + bool _clearnetAck = false; + bool _plaintextAck = false; + late final String walletId; late final String routeOnSuccessName; late final bool isDesktop; @@ -157,35 +168,36 @@ class _ConfirmTransactionViewState final coin = wallet.info.coin; final sendProgressController = ProgressAndSuccessController(); - var isSendingDialogOpen = true; + final navigator = Navigator.of(context, rootNavigator: true); + final sendingRoute = CurrentAwareDialogRoute( + context: context, + useSafeArea: false, + barrierDismissible: false, + themes: InheritedTheme.capture(from: context, to: navigator.context), + builder: (_) => SendingTransactionDialog( + coin: coin, + controller: sendProgressController, + ), + ); - void closeSendingDialog() { - if (!context.mounted || !isSendingDialogOpen) { - return; - } - final navigator = Navigator.of(context, rootNavigator: true); - if (navigator.canPop()) { + Future closeSendingDialog() async { + if (!navigator.mounted || !sendingRoute.isActive) return; + if (context.mounted) await sendingRoute.waitUntilCurrent(); + if (!navigator.mounted || !sendingRoute.isActive) return; + if (sendingRoute.isCurrent) { navigator.pop(); + } else { + navigator.removeRoute(sendingRoute); } - isSendingDialogOpen = false; } - unawaited( - showDialog( - context: context, - useRootNavigator: true, - useSafeArea: false, - barrierDismissible: false, - builder: (context) { - return SendingTransactionDialog( - coin: coin, - controller: sendProgressController, - ); - }, - ).whenComplete(() => isSendingDialogOpen = false), - ); - final time = Future.delayed(const Duration(milliseconds: 2500)); + unawaited(navigator.push(sendingRoute)); + await waitForRoutePresentation(sendingRoute); + if (!context.mounted) { + await closeSendingDialog(); + return; + } final List txids = []; Future txDataFuture; @@ -235,6 +247,8 @@ class _ConfirmTransactionViewState noteOnChain: wallet.supportsOnChainNote ? onChainNoteController.text : null, + grinClearnetAcknowledged: _clearnetAck, + grinPlaintextAcknowledged: _plaintextAck, ), ); } else { @@ -279,7 +293,7 @@ class _ConfirmTransactionViewState unawaited(wallet.refresh()); } - closeSendingDialog(); + await closeSendingDialog(); widget.onSuccess.call(); @@ -292,9 +306,8 @@ class _ConfirmTransactionViewState } } } on BadHttpAddressException catch (_) { + await closeSendingDialog(); if (context.mounted) { - // pop building dialog - closeSendingDialog(); unawaited( showFloatingFlushBar( type: FlushBarType.warning, @@ -306,12 +319,49 @@ class _ConfirmTransactionViewState return; } } catch (e, s) { + if (e is GrinWalletException && + e.finalizedNotBroadcast && + wallet is SlatepackInterface) { + final slateId = e.slateId!; + Logging.instance.w( + "Send finalized but not broadcast. Slate id: $slateId", + ); + if (note.isNotEmpty) { + try { + await ref + .read(mainDBProvider) + .putTransactionNote( + TransactionNote( + walletId: walletId, + txid: slateId, + value: note, + ), + ); + } catch (_) { + // The finalized transaction remains available in wallet history. + } + } + await closeSendingDialog(); + if (context.mounted) { + await SlatepackImportFlow.notPosted(context, wallet, slateId); + } + widget.onSuccess.call(); + if (context.mounted) { + if (widget.onSuccessInsteadOfRouteOnSuccess == null) { + Navigator.of(context) + .popUntil(ModalRoute.withName(routeOnSuccessName)); + } else { + widget.onSuccessInsteadOfRouteOnSuccess!.call(); + } + } + return; + } + const message = "Broadcast transaction failed"; Logging.instance.e(message, error: e, stackTrace: s); - // pop sending dialog + final errorMessage = stripExceptionPrefixes(e); + await closeSendingDialog(); if (context.mounted) { - closeSendingDialog(); - await showDialog( context: context, useSafeArea: false, @@ -331,7 +381,7 @@ class _ConfirmTransactionViewState Flexible( child: SingleChildScrollView( child: SelectableText( - e.toString(), + errorMessage, style: STextStyles.smallMed14(context), ), ), @@ -356,7 +406,7 @@ class _ConfirmTransactionViewState } else { return StackDialog( title: message, - message: e.toString(), + message: errorMessage, rightButton: TextButton( style: Theme.of(context) .extension()! @@ -425,6 +475,7 @@ class _ConfirmTransactionViewState @override Widget build(BuildContext context) { final coin = ref.watch(pWalletCoin(walletId)); + final localNote = widget.txData.note ?? ""; final sentRecipients = [ for (final e in widget.txData.recipients ?? []) if (!e.isChange) e, @@ -490,6 +541,19 @@ class _ConfirmTransactionViewState final slatepackWallet = wallet is SlatepackInterface ? wallet : null; final showOnChainNote = slatepackWallet?.supportsOnChainNote ?? false; + final SlatepackHttpPolicy? httpPolicy = + slatepackWallet != null && + widget.txData.slatepackMethod == SlatepackMethod.http && + widget.txData.recipients?.firstOrNull != null + ? slatepackWallet.httpSendPolicy( + widget.txData.recipients!.first.address, + ) + : null; + final sendAllowed = SlatepackTransportWarnings.allows( + httpPolicy, + clearnetAck: _clearnetAck, + plaintextAck: _plaintextAck, + ); return ConditionalParent( condition: !isDesktop, @@ -637,24 +701,29 @@ class _ConfirmTransactionViewState mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text("Amount", style: STextStyles.smallMed12(context)), - SelectableText( - ref - .watch(pAmountFormatter(coin)) - .format( - amountWithoutChange, - tokenContract: - widget.isTokenTx && wallet is! SolanaWallet - ? ref - .watch(pCurrentTokenWallet)! - .tokenContract - : widget.isTokenTx && wallet is SolanaWallet - ? ref - .watch(pCurrentSolanaTokenWallet)! - .solContract - : null, - ), - style: STextStyles.itemSubtitle12(context), - textAlign: TextAlign.right, + const SizedBox(width: 8), + Flexible( + child: SelectableText( + ref + .watch(pAmountFormatter(coin)) + .format( + amountWithoutChange, + tokenContract: + widget.isTokenTx && + wallet is! SolanaWallet + ? ref + .watch(pCurrentTokenWallet)! + .tokenContract + : widget.isTokenTx && + wallet is SolanaWallet + ? ref + .watch(pCurrentSolanaTokenWallet)! + .solContract + : null, + ), + style: STextStyles.itemSubtitle12(context), + textAlign: TextAlign.right, + ), ), ], ), @@ -669,10 +738,13 @@ class _ConfirmTransactionViewState "Transaction fee", style: STextStyles.smallMed12(context), ), - SelectableText( - ref.watch(pAmountFormatter(coin)).format(fee!), - style: STextStyles.itemSubtitle12(context), - textAlign: TextAlign.right, + const SizedBox(width: 8), + Flexible( + child: SelectableText( + ref.watch(pAmountFormatter(coin)).format(fee!), + style: STextStyles.itemSubtitle12(context), + textAlign: TextAlign.right, + ), ), ], ), @@ -731,9 +803,8 @@ class _ConfirmTransactionViewState ], ), ), - if (widget.txData.note!.isNotEmpty) - const SizedBox(height: 12), - if (widget.txData.note!.isNotEmpty) + if (localNote.isNotEmpty) const SizedBox(height: 12), + if (localNote.isNotEmpty) RoundedWhiteContainer( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -744,7 +815,7 @@ class _ConfirmTransactionViewState ), const SizedBox(height: 4), SelectableText( - widget.txData.note!, + localNote, style: STextStyles.itemSubtitle12(context), ), ], @@ -1360,23 +1431,26 @@ class _ConfirmTransactionViewState .textConfirmTotalAmount, ), ), - SelectableText( - ref - .watch(pAmountFormatter(coin)) - .format(amountWithoutChange + fee!), - style: isDesktop - ? STextStyles.desktopTextExtraExtraSmall(context) - .copyWith( - color: Theme.of(context) - .extension()! - .textConfirmTotalAmount, - ) - : STextStyles.itemSubtitle12(context).copyWith( - color: Theme.of(context) - .extension()! - .textConfirmTotalAmount, - ), - textAlign: TextAlign.right, + const SizedBox(width: 8), + Flexible( + child: SelectableText( + ref + .watch(pAmountFormatter(coin)) + .format(amountWithoutChange + fee!), + style: isDesktop + ? STextStyles.desktopTextExtraExtraSmall(context) + .copyWith( + color: Theme.of(context) + .extension()! + .textConfirmTotalAmount, + ) + : STextStyles.itemSubtitle12(context).copyWith( + color: Theme.of(context) + .extension()! + .textConfirmTotalAmount, + ), + textAlign: TextAlign.right, + ), ), ], ), @@ -1425,6 +1499,19 @@ class _ConfirmTransactionViewState ), ), ), + if (httpPolicy != null) + Padding( + padding: isDesktop + ? const EdgeInsets.symmetric(horizontal: 32, vertical: 8) + : const EdgeInsets.symmetric(vertical: 8), + child: SlatepackTransportWarnings( + policy: httpPolicy, + onClearnetAck: (value) => + setState(() => _clearnetAck = value), + onPlaintextAck: (value) => + setState(() => _plaintextAck = value), + ), + ), SizedBox(height: isDesktop ? 28 : 16), Padding( padding: isDesktop @@ -1433,6 +1520,7 @@ class _ConfirmTransactionViewState child: PrimaryButton( label: "Send", buttonHeight: isDesktop ? ButtonHeight.l : null, + enabled: sendAllowed, onPressed: () async { if (isDesktop) { final unlocked = await showDialog( @@ -1481,7 +1569,7 @@ class _ConfirmTransactionViewState RouteGenerator.getRoute( shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, - builder: (_) => const LockscreenView( + builder: (_) => LockscreenView( showBackButton: true, popOnSuccess: true, routeOnSuccessArguments: true, diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 8c482ffb58..0600e7b2e6 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -74,6 +74,7 @@ import '../../widgets/icon_widgets/clipboard_icon.dart'; import '../../widgets/icon_widgets/qrcode_icon.dart'; import '../../widgets/icon_widgets/x_icon.dart'; import '../../widgets/slatepack_method_toggle.dart'; +import '../slatepack/slatepack_recipient_field.dart'; import '../../widgets/rounded_white_container.dart'; import '../../widgets/stack_dialog.dart'; import '../../widgets/stack_text_field.dart'; @@ -116,6 +117,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { late final ClipboardInterface clipboard; late TextEditingController sendToController; + final _slatepackRecipientController = TextEditingController(); late TextEditingController cryptoAmountController; late TextEditingController baseAmountController; late TextEditingController noteController; @@ -755,8 +757,12 @@ class _SendViewState extends ConsumerState with SendFeeForm { await Future.delayed(const Duration(milliseconds: 100)); if (!mounted) return; final wallet = ref.read(pWallets).getWallet(walletId); - final isSlatepackSend = - wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + final slatepackWallet = wallet is SlatepackInterface ? wallet : null; + final selectedSlatepack = + slatepackWallet != null && ref.read(pIsSlatepack(walletId)); + final manualAddressRecipient = slatepackWallet + ?.manualSlatepackRecipientForAddress(_address ?? ""); + final isSlatepackSend = selectedSlatepack || manualAddressRecipient != null; String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; @@ -779,10 +785,17 @@ class _SendViewState extends ConsumerState with SendFeeForm { final Amount amount = ref.read(pSendAmount)!; if (isSlatepackSend) { + final slatepackRecipient = _slatepackRecipientController.text.trim(); final created = await SlatepackSendFlow.run( context: context, - wallet: wallet, + wallet: slatepackWallet!, amount: amount, + recipientAddress: + manualAddressRecipient ?? + (slatepackWallet.supportsSlatepackRecipient && + slatepackRecipient.isNotEmpty + ? slatepackRecipient + : null), message: onChainNoteController.text, localNote: noteController.text, db: ref.read(mainDBProvider), @@ -1161,6 +1174,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { onChainNoteController.text = ""; feeController.text = ""; memoController.text = ""; + _slatepackRecipientController.text = ""; _address = ""; _addressToggleFlag = false; _clearRecipientForms(); @@ -1320,6 +1334,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { } sendToController.dispose(); + _slatepackRecipientController.dispose(); cryptoAmountController.dispose(); baseAmountController.dispose(); noteController.dispose(); @@ -1424,6 +1439,10 @@ class _SendViewState extends ConsumerState with SendFeeForm { final wallet = ref.watch( pWallets.select((value) => value.getWallet(walletId)), ); + final isManualSlatepackCreation = + isSlatepackMode || + (wallet is SlatepackInterface && + wallet.manualSlatepackRecipientForAddress(_address ?? "") != null); // Preserve the existing mobile UI: Epic exposes its on-chain note field; // MWC only exposed that field on desktop before this refactor. final showOnChainNote = coin is Epiccash; @@ -1594,6 +1613,16 @@ class _SendViewState extends ConsumerState with SendFeeForm { const SizedBox(height: 16), ], + if (isSlatepackMode && + _slatepackWallet! + .supportsSlatepackRecipient) ...[ + SlatepackRecipientField( + controller: _slatepackRecipientController, + coin: coin, + ), + const SizedBox(height: 16), + ], + if (!isSlatepackMode) Row( mainAxisAlignment: @@ -1693,8 +1722,12 @@ class _SendViewState extends ConsumerState with SendFeeForm { _applyUri(parsed); } else { _setOpReturnData(null); + // The field already contains this + // text. Writing it back moves the + // cursor to the end on every edit. await _checkSparkNameAndOrSetAddress( newValue, + setController: false, ); } } else { @@ -1718,7 +1751,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { standardInputDecoration( isSlatepackMode ? "Enter ${coin.ticker} address (optional)" - : "Enter ${coin.ticker} address", + : _slatepackWallet + ?.directSendAddressHint ?? + "Enter ${coin.ticker} address", _addressFocusNode, context, ).copyWith( @@ -2471,7 +2506,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { ), ), const SizedBox(height: 12), - if (hasFees) + if (hasFees && !isManualSlatepackCreation) Text( coin is Xelis || coin is Grin || hasCustomFee ? "Transaction fee" @@ -2479,8 +2514,10 @@ class _SendViewState extends ConsumerState with SendFeeForm { style: STextStyles.smallMed12(context), textAlign: TextAlign.left, ), - if (hasFees) const SizedBox(height: 8), - if (coin is Xelis || coin is Grin) + if (hasFees && !isManualSlatepackCreation) + const SizedBox(height: 8), + if (!isManualSlatepackCreation && + (coin is Xelis || coin is Grin)) Padding( padding: const EdgeInsets.all(12), child: Text( @@ -2488,7 +2525,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { style: STextStyles.itemSubtitle(context), ), ) - else if (hasFees) + else if (hasFees && !isManualSlatepackCreation) Stack( children: [ TextField( @@ -2652,7 +2689,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { context, ), child: Text( - isSlatepackMode && + isManualSlatepackCreation && wallet is SlatepackInterface ? "Create ${wallet.slatepackTerms.noun}" : "Preview", diff --git a/lib/pages/send_view/sub_widgets/slatepack_transport_warnings.dart b/lib/pages/send_view/sub_widgets/slatepack_transport_warnings.dart new file mode 100644 index 0000000000..5ec6e2e485 --- /dev/null +++ b/lib/pages/send_view/sub_widgets/slatepack_transport_warnings.dart @@ -0,0 +1,125 @@ +import 'package:flutter/material.dart'; + +import '../../../models/slatepack_models.dart'; +import '../../../themes/stack_colors.dart'; +import '../../../utilities/text_styles.dart'; +import '../../../widgets/custom_buttons/checkbox_text_button.dart'; +import '../../../widgets/rounded_container.dart'; + +/// Transport warnings for a direct send on the confirm screen. A blocked +/// send shows the reason; the IP disclosure and plain http:// warnings each +/// need a tick before [allows] is true. +class SlatepackTransportWarnings extends StatelessWidget { + const SlatepackTransportWarnings({ + super.key, + required this.policy, + required this.onClearnetAck, + required this.onPlaintextAck, + }); + + final SlatepackHttpPolicy policy; + final void Function(bool) onClearnetAck; + final void Function(bool) onPlaintextAck; + + static bool allows( + SlatepackHttpPolicy? policy, { + required bool clearnetAck, + required bool plaintextAck, + }) { + if (policy == null) return true; + if (policy.isBlocked) return false; + if (policy.needsClearnetAck && !clearnetAck) return false; + if (policy.needsPlaintextAck && !plaintextAck) return false; + return true; + } + + Widget _box( + BuildContext context, { + required bool error, + required Widget child, + }) { + final colors = Theme.of(context).extension()!; + return RoundedContainer( + color: error ? colors.textFieldErrorBG : colors.warningBackground, + child: child, + ); + } + + Widget _text(BuildContext context, String text, {required bool error}) { + final colors = Theme.of(context).extension()!; + return Text( + text, + style: STextStyles.smallMed12(context) + .copyWith(color: error ? colors.textError : colors.warningForeground), + ); + } + + @override + Widget build(BuildContext context) { + if (policy.isBlocked) { + return _box( + context, + error: true, + child: _text( + context, + "${policy.blockedReason} This send cannot go ahead.", + error: true, + ), + ); + } + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (policy.needsClearnetAck) + _box( + context, + error: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _text( + context, + "Tor is off. The recipient's wallet, and anyone watching " + "the connection, will see your IP address.", + error: false, + ), + const SizedBox(height: 8), + CheckboxTextButton( + key: const Key("slatepackClearnetAck"), + label: "Send without Tor and reveal my IP address", + onChanged: onClearnetAck, + ), + ], + ), + ), + if (policy.needsClearnetAck && policy.needsPlaintextAck) + const SizedBox(height: 8), + if (policy.needsPlaintextAck) + _box( + context, + error: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _text( + context, + "This address uses unencrypted http://. Anyone on the path, " + "including a Tor exit relay, can read and change the " + "transaction data.", + error: false, + ), + const SizedBox(height: 8), + CheckboxTextButton( + key: const Key("slatepackPlaintextAck"), + label: "Send over unencrypted http:// anyway", + onChanged: onPlaintextAck, + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart index e8690392af..ee75b1490d 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart @@ -29,6 +29,7 @@ import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/multi_address_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/rbf_interface.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/view_only_option_interface.dart'; import '../../../../widgets/background.dart'; @@ -39,6 +40,7 @@ import '../../../../widgets/desktop/secondary_button.dart'; import '../../../../widgets/rounded_white_container.dart'; import '../../../../widgets/stack_dialog.dart'; import '../../../pinpad_views/lock_screen_view.dart'; +import '../../../slatepack/verify_payment_proof_view.dart'; import 'delete_wallet_warning_view.dart'; import 'edit_refresh_height_view.dart'; import 'rbf_settings_view.dart'; @@ -627,6 +629,37 @@ class _WalletSettingsWalletSettingsViewState ), ), ), + if (wallet is SlatepackInterface && + wallet.supportsPaymentProofs) ...[ + const SizedBox(height: 8), + RoundedWhiteContainer( + padding: const EdgeInsets.all(0), + child: RawMaterialButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + Constants.size.circularBorderRadius, + ), + ), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + onPressed: () => + showVerifyPaymentProof(context, widget.walletId), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12.0, + vertical: 20, + ), + child: Row( + children: [ + Text( + "Verify payment proof", + style: STextStyles.titleBold12(context), + ), + ], + ), + ), + ), + ), + ], const SizedBox(height: 8), RoundedWhiteContainer( padding: const EdgeInsets.all(0), diff --git a/lib/pages/slatepack/pay_invoice_confirm_view.dart b/lib/pages/slatepack/pay_invoice_confirm_view.dart new file mode 100644 index 0000000000..e305547305 --- /dev/null +++ b/lib/pages/slatepack/pay_invoice_confirm_view.dart @@ -0,0 +1,432 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../models/slatepack_models.dart'; +import '../../providers/global/wallets_provider.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/amount/amount.dart'; +import '../../utilities/amount/amount_formatter.dart'; +import '../../utilities/logger.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/isar/providers/wallet_info_provider.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/background.dart'; +import '../../widgets/conditional_parent.dart'; +import '../../widgets/custom_buttons/app_bar_icon_button.dart'; +import '../../widgets/desktop/desktop_dialog_close_button.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/desktop/secondary_button.dart'; +import '../../widgets/detail_item.dart'; +import '../../widgets/rounded_container.dart'; +import '../../widgets/rounded_white_container.dart'; +import '../../widgets/stack_dialog.dart'; +import 'slatepack_auth.dart'; +import 'slatepack_dialog.dart'; +import 'slatepack_import_flow.dart'; + +/// Review of someone else's invoice (I1) before paying it. Modelled on the +/// send confirm screen. The invoice carries no fee, so the fee is the +/// wallet's estimate. Pops true once a payment was made and still stands: +/// the payment slatepack (I2) was shown, the payment failed after the wallet +/// recorded it, or the payment could not be cancelled again. +class PayInvoiceConfirmView extends ConsumerStatefulWidget { + const PayInvoiceConfirmView({ + super.key, + required this.walletId, + required this.invoice, + required this.inspection, + }); + + static const String routeName = "/payInvoiceConfirm"; + + final String walletId; + + /// The armored I1. + final String invoice; + + /// The I1 as the wallet read it. Its amount is what the user confirms. + final SlateInspection inspection; + + @override + ConsumerState createState() => + _PayInvoiceConfirmViewState(); +} + +class _PayInvoiceConfirmViewState extends ConsumerState { + late final SlatepackInterface _wallet; + Amount? _estimatedFee; + bool _estimateFailed = false; + bool _busy = false; + String? _pendingAbandonedPayment; + + Amount get _amount => widget.inspection.amount!; + + @override + void dispose() { + final slateId = _pendingAbandonedPayment; + _pendingAbandonedPayment = null; + if (slateId != null) { + unawaited(_cancelAbandonedPayment(slateId)); + } + super.dispose(); + } + + Future _cancelAbandonedPayment(String slateId) async { + try { + final message = await _wallet.cancelPendingTransactionAndPost(slateId); + if (message.isNotEmpty) { + Logging.instance.w( + "Could not cancel an abandoned invoice payment: $message", + ); + } + } catch (e, s) { + Logging.instance.w( + "Could not cancel an abandoned invoice payment", + error: e, + stackTrace: s, + ); + } + } + + @override + void initState() { + super.initState(); + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + unawaited(_estimateFee()); + } + + Future _estimateFee() async { + try { + final fee = await _wallet.estimateFeeFor(_amount, BigInt.zero); + if (mounted) setState(() => _estimatedFee = fee); + } catch (e, s) { + Logging.instance.w( + "Could not estimate the fee of an invoice payment", + error: e, + stackTrace: s, + ); + if (mounted) setState(() => _estimateFailed = true); + } + } + + void _retryEstimate() { + setState(() => _estimateFailed = false); + unawaited(_estimateFee()); + } + + Future _pay() async { + if (_busy) return; + setState(() => _busy = true); + try { + await _payUnlocked(); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Future _payUnlocked() async { + final unlocked = await authenticateSlatepackSpend( + context, + coin: _wallet.cryptoCurrency, + reason: "Authenticate to pay invoice", + ); + if (!unlocked || !mounted) return; + + final terms = _wallet.slatepackTerms; + final result = await SlatepackImportFlow.withLoading( + context, + "Paying invoice...", + () async { + final r = await _wallet.processInvoice( + widget.invoice, + confirmedAmount: _amount, + ); + if ((!r.success || r.slatepack == null) && r.slateId == null) { + throw Exception(r.error ?? "Failed to pay the invoice"); + } + return r; + }, + errorTitle: "Invoice payment failed", + ); + if (result == null || !mounted) return; + + if (!result.success || result.slatepack == null) { + // The payment failed but stays in the wallet, where it can be + // cancelled. Paying this invoice again from here cannot work. + await SlatepackImportFlow.showMessage( + context, + "Invoice payment failed", + result.error ?? "Failed to pay the invoice", + ); + if (mounted) Navigator.of(context).pop(true); + return; + } + + final estimate = _estimatedFee; + final actual = result.fee; + if (estimate != null && actual != null && actual > estimate) { + _pendingAbandonedPayment = result.slateId; + final keep = await _confirmHigherFee(estimate, actual); + if (keep != true) { + if (!mounted) return; + final slateId = _pendingAbandonedPayment; + _pendingAbandonedPayment = null; + await _cancelPayment(slateId); + return; + } + _pendingAbandonedPayment = null; + if (!mounted) return; + } + + await showSlatepackDialog( + context: context, + terms: terms, + result: result, + supportsEncryption: _wallet.supportsSlatepackEncryption, + ); + if (mounted) Navigator.of(context).pop(true); + } + + Future _confirmHigherFee(Amount estimate, Amount actual) { + final formatter = ref.read(pAmountFormatter(_wallet.cryptoCurrency)); + return showDialog( + context: context, + barrierDismissible: false, + builder: (context) => StackDialog( + width: Util.isDesktop ? 500 : null, + title: "Higher fee", + message: + "The payment needs a fee of ${formatter.format(actual)}, more " + "than the estimate of ${formatter.format(estimate)}. The funds " + "are locked now. Cancel the payment to unlock them, or continue " + "and hand out the payment ${_wallet.slatepackTerms.noun}.", + leftButton: SecondaryButton( + label: Util.isDesktop ? "Cancel payment" : "Cancel", + buttonHeight: Util.isDesktop ? ButtonHeight.l : null, + onPressed: () => Navigator.of(context).pop(false), + ), + rightButton: PrimaryButton( + label: "Continue", + buttonHeight: Util.isDesktop ? ButtonHeight.l : null, + onPressed: () => Navigator.of(context).pop(true), + ), + ), + ); + } + + /// Cancels the payment just made. The screen closes either way: when the + /// cancel fails the payment still exists with its funds locked, and paying + /// from here again would be a second one. + Future _cancelPayment(String? slateId) async { + String? failure; + if (slateId == null) { + failure = "Could not cancel automatically."; + } else { + final message = await SlatepackImportFlow.withLoading( + context, + "Cancelling payment...", + () async { + try { + return await _wallet.cancelPendingTransactionAndPost(slateId); + } catch (e) { + return e.toString().replaceFirst("Exception: ", ""); + } + }, + errorTitle: "Cancel failed", + ); + if (!mounted) return; + if (message == null || message.isNotEmpty) { + failure = message ?? "Could not cancel automatically."; + } + } + await SlatepackImportFlow.showMessage( + context, + failure == null ? "Payment cancelled" : "Cancel failed", + failure == null + ? "The funds are unlocked. Nothing was handed out." + : "$failure The funds are still locked. Cancel the payment from " + "the transaction details.", + ); + if (mounted) Navigator.of(context).pop(failure != null); + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final coin = _wallet.cryptoCurrency; + final formatter = ref.watch(pAmountFormatter(coin)); + final spendable = ref.watch(pWalletBalance(widget.walletId)).spendable; + final inspection = widget.inspection; + + final amountStyle = isDesktop + ? STextStyles.desktopH2(context) + : STextStyles.pageTitleH1(context); + + final body = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RoundedWhiteContainer( + borderColor: isDesktop ? colors.backgroundAppBar : null, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("You pay", style: STextStyles.label(context)), + const SizedBox(height: 4), + SelectableText( + formatter.format(_amount), + key: const Key("payInvoiceAmount"), + style: amountStyle, + ), + ], + ), + ), + const SizedBox(height: 12), + Builder( + builder: (context) { + final fee = _estimatedFee; + final String feeText; + final String totalText; + final String remainingText; + if (_estimateFailed) { + feeText = "Could not estimate"; + totalText = "-"; + remainingText = "-"; + } else if (fee == null) { + feeText = "Estimating..."; + totalText = "..."; + remainingText = "..."; + } else { + final total = _amount + fee; + feeText = formatter.format(fee); + totalText = formatter.format(total); + remainingText = total > spendable + ? "Not enough funds" + : formatter.format(spendable - total); + } + final rows = <(String, String)>[ + ("Pay to", inspection.senderAddress ?? "Not given"), + ("Encrypted", inspection.isEncrypted ? "Yes" : "No"), + ( + "Expires", + inspection.ttlCutoffHeight != null + ? "At block ${inspection.ttlCutoffHeight}" + : "If not finalized within about a day", + ), + ("Fee (estimated)", feeText), + ("Total", totalText), + ("Remaining balance", remainingText), + ("Slate ID", inspection.slateId), + ]; + return RoundedWhiteContainer( + padding: EdgeInsets.zero, + borderColor: isDesktop ? colors.backgroundAppBar : null, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) const DetailDivider(), + DetailItem(title: rows[i].$1, detail: rows[i].$2), + ], + ], + ), + ); + }, + ), + const SizedBox(height: 16), + RoundedContainer( + color: colors.warningBackground, + child: Text( + "Paying locks the funds until the payee finalizes the " + "transaction. Cancelling unlocks them in this wallet, but a " + "payee who already has your payment " + "${_wallet.slatepackTerms.noun} can still complete the payment " + "until the funds are spent in another transaction. Only pay " + "invoices you expect.", + style: STextStyles.label(context) + .copyWith(color: colors.warningForeground), + ), + ), + const SizedBox(height: 24), + Builder( + builder: (context) { + if (_estimateFailed) { + return SecondaryButton( + key: const Key("payInvoiceRetryEstimate"), + label: "Estimate the fee again", + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: _retryEstimate, + ); + } + final fee = _estimatedFee; + final canPay = !_busy && fee != null && _amount + fee <= spendable; + return PrimaryButton( + key: const Key("payInvoiceButton"), + label: "Pay invoice", + buttonHeight: isDesktop ? ButtonHeight.l : null, + enabled: canPay, + onPressed: canPay ? _pay : null, + ); + }, + ), + ], + ); + + return ConditionalParent( + condition: !isDesktop, + builder: (child) => Background( + child: Scaffold( + backgroundColor: colors.background, + appBar: AppBar( + backgroundColor: colors.background, + leading: AppBarBackButton( + onPressed: () => Navigator.of(context).pop(false), + ), + title: Text("Pay invoice", style: STextStyles.navBarTitle(context)), + ), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: child, + ), + ), + ), + ), + child: ConditionalParent( + condition: isDesktop, + builder: (child) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Padding( + padding: const EdgeInsets.only(left: 32), + child: Text( + "Pay invoice", + style: STextStyles.desktopH3(context), + ), + ), + const DesktopDialogCloseButton(), + ], + ), + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), + child: child, + ), + ), + ], + ), + child: body, + ), + ); + } +} diff --git a/lib/pages/slatepack/request_invoice_view.dart b/lib/pages/slatepack/request_invoice_view.dart new file mode 100644 index 0000000000..b47b2e5da4 --- /dev/null +++ b/lib/pages/slatepack/request_invoice_view.dart @@ -0,0 +1,352 @@ +import 'package:decimal/decimal.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../providers/global/locale_provider.dart'; +import '../../providers/global/prefs_provider.dart'; +import '../../providers/global/price_provider.dart'; +import '../../providers/global/wallets_provider.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/amount/amount.dart'; +import '../../utilities/amount/amount_input_formatter.dart'; +import '../../utilities/constants.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/background.dart'; +import '../../widgets/conditional_parent.dart'; +import '../../widgets/custom_buttons/app_bar_icon_button.dart'; +import '../../widgets/desktop/desktop_dialog.dart'; +import '../../widgets/desktop/desktop_dialog_close_button.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/rounded_container.dart'; +import '../../widgets/stack_text_field.dart'; +import 'slatepack_dialog.dart'; +import 'slatepack_import_flow.dart'; +import 'slatepack_recipient_field.dart'; + +/// Opens the invoice request form: a page on mobile, a dialog on desktop. +Future showRequestInvoice(BuildContext context, String walletId) { + final view = RequestInvoiceView(walletId: walletId); + if (Util.isDesktop) { + return showDialog( + context: context, + builder: (_) => + DesktopDialog(maxWidth: 580, maxHeight: null, child: view), + ); + } + return Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => view, + settings: const RouteSettings(name: RequestInvoiceView.routeName), + ), + ); +} + +/// Asks someone for a payment: makes an invoice (I1) for an amount, +/// optionally encrypted to the payer. +class RequestInvoiceView extends ConsumerStatefulWidget { + const RequestInvoiceView({super.key, required this.walletId}); + + static const String routeName = "/requestInvoice"; + + final String walletId; + + @override + ConsumerState createState() => _RequestInvoiceViewState(); +} + +class _RequestInvoiceViewState extends ConsumerState { + late final SlatepackInterface _wallet; + final _amountController = TextEditingController(); + final _fiatController = TextEditingController(); + final _payerController = TextEditingController(); + final _amountFocus = FocusNode(); + final _fiatFocus = FocusNode(); + bool _lock = false; + bool _busy = false; + + @override + void initState() { + super.initState(); + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + _payerController.addListener(_payerChanged); + } + + void _payerChanged() => setState(() {}); + + @override + void dispose() { + _amountController.dispose(); + _fiatController.dispose(); + _payerController.dispose(); + _amountFocus.dispose(); + _fiatFocus.dispose(); + super.dispose(); + } + + String get _locale => ref.read(localeServiceChangeNotifierProvider).locale; + + Decimal? get _price { + final price = ref + .read(priceAnd24hChangeNotifierProvider) + .getPrice(_wallet.cryptoCurrency) + ?.value; + return price == null || price <= Decimal.zero ? null : price; + } + + Amount? get _amount { + final amount = Amount.tryParseEditableAmount( + _amountController.text, + locale: _locale, + fractionDigits: _wallet.cryptoCurrency.fractionDigits, + ); + return amount == null || amount.raw <= BigInt.zero ? null : amount; + } + + void _amountChanged(String _) { + if (_lock) return; + final price = _price; + final amount = _amount; + _lock = true; + _fiatController.text = price == null || amount == null + ? "" + : Amount.formatEditableDecimal( + (amount.decimal * price).toAmount(fractionDigits: 2).decimal, + locale: _locale, + ); + _lock = false; + setState(() {}); + } + + void _fiatChanged(String text) { + if (_lock) return; + final price = _price; + final fiat = Amount.tryParseFiatString(text, locale: _locale); + final digits = _wallet.cryptoCurrency.fractionDigits; + _lock = true; + _amountController.text = price == null || fiat == null + ? "" + : Amount.formatEditableDecimal( + (fiat.decimal / price) + .toDecimal(scaleOnInfinitePrecision: digits) + .toAmount(fractionDigits: digits) + .decimal, + locale: _locale, + ); + _lock = false; + setState(() {}); + } + + bool get _canCreate => + !_busy && + _amount != null && + SlatepackRecipientField.isAcceptable( + _wallet.cryptoCurrency, + _payerController.text, + ); + + Future _create() async { + final amount = _amount; + if (amount == null || !_canCreate) return; + setState(() => _busy = true); + try { + final payer = _payerController.text.trim(); + final result = await SlatepackImportFlow.withLoading( + context, + "Creating invoice...", + () async { + final r = await _wallet.issueInvoice( + amount: amount, + payerAddress: payer.isEmpty ? null : payer, + ); + if (!r.success || r.slatepack == null) { + throw Exception(r.error ?? "Failed to create the invoice"); + } + return r; + }, + errorTitle: "Invoice error", + ); + if (result == null || !mounted) return; + await showSlatepackDialog( + context: context, + terms: _wallet.slatepackTerms, + result: result, + supportsEncryption: _wallet.supportsSlatepackEncryption, + ); + if (mounted) Navigator.of(context).pop(); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Widget _field({ + required TextEditingController controller, + required FocusNode focusNode, + required String label, + required int decimals, + required void Function(String) onChanged, + Key? key, + }) { + final isDesktop = Util.isDesktop; + return ClipRRect( + borderRadius: BorderRadius.circular(Constants.size.circularBorderRadius), + child: TextField( + key: key, + controller: controller, + focusNode: focusNode, + autocorrect: false, + enableSuggestions: false, + keyboardType: isDesktop + ? null + : const TextInputType.numberWithOptions(decimal: true), + inputFormatters: [ + AmountInputFormatter( + controller: controller, + decimals: decimals, + locale: ref.watch( + localeServiceChangeNotifierProvider.select((e) => e.locale), + ), + ), + ], + onChanged: onChanged, + style: isDesktop + ? STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textFieldActiveText, + height: 1.8, + ) + : STextStyles.field(context), + decoration: standardInputDecoration( + label, + focusNode, + context, + desktopMed: true, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final coin = _wallet.cryptoCurrency; + final currency = ref.watch( + prefsChangeNotifierProvider.select((p) => p.currency), + ); + final price = ref + .watch(priceAnd24hChangeNotifierProvider) + .getPrice(coin) + ?.value; + final hasPrice = price != null && price > Decimal.zero; + + final body = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _field( + key: const Key("requestInvoiceAmount"), + controller: _amountController, + focusNode: _amountFocus, + label: "Amount (${coin.ticker})", + decimals: coin.fractionDigits, + onChanged: _amountChanged, + ), + if (hasPrice) ...[ + const SizedBox(height: 12), + _field( + controller: _fiatController, + focusNode: _fiatFocus, + label: "Amount ($currency)", + decimals: 2, + onChanged: _fiatChanged, + ), + ], + const SizedBox(height: 16), + SlatepackRecipientField( + controller: _payerController, + coin: coin, + label: "Payer address (optional)", + help: + "The invoice is encrypted to this address so only the payer " + "can read it.", + ), + const SizedBox(height: 16), + RoundedContainer( + color: colors.infoItemBG, + child: Text( + "The payer returns a payment ${_wallet.slatepackTerms.noun}. " + "Import it on the Slatepack screen to finalize. An invoice locks " + "none of your funds.", + style: STextStyles.label(context), + ), + ), + const SizedBox(height: 24), + PrimaryButton( + key: const Key("requestInvoiceCreate"), + label: "Create invoice", + buttonHeight: isDesktop ? ButtonHeight.l : null, + enabled: _canCreate, + onPressed: _canCreate ? _create : null, + ), + ], + ); + + return ConditionalParent( + condition: !isDesktop, + builder: (child) => Background( + child: Scaffold( + backgroundColor: colors.background, + appBar: AppBar( + backgroundColor: colors.background, + leading: AppBarBackButton( + onPressed: () => Navigator.of(context).pop(), + ), + title: Text( + "Request payment", + style: STextStyles.navBarTitle(context), + ), + ), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: child, + ), + ), + ), + ), + child: ConditionalParent( + condition: isDesktop, + builder: (child) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Padding( + padding: const EdgeInsets.only(left: 32), + child: Text( + "Request payment", + style: STextStyles.desktopH3(context), + ), + ), + const DesktopDialogCloseButton(), + ], + ), + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), + child: child, + ), + ), + ], + ), + child: body, + ), + ); + } +} diff --git a/lib/pages/slatepack/slatepack_auth.dart b/lib/pages/slatepack/slatepack_auth.dart new file mode 100644 index 0000000000..eeff7b4f32 --- /dev/null +++ b/lib/pages/slatepack/slatepack_auth.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; + +import '../../notifications/show_flush_bar.dart'; +import '../../pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart'; +import '../../route_generator.dart'; +import '../../utilities/util.dart'; +import '../../wallets/crypto_currency/crypto_currency.dart'; +import '../../widgets/desktop/desktop_dialog.dart'; +import '../../widgets/desktop/desktop_dialog_close_button.dart'; +import '../pinpad_views/lock_screen_view.dart'; + +/// The same unlock step the confirm screen uses before a send: passphrase +/// on desktop, PIN or biometrics on mobile. Returns true when unlocked. +Future authenticateSlatepackSpend( + BuildContext context, { + required CryptoCurrency coin, + String reason = "Authenticate to send transaction", +}) async { + final bool? unlocked; + if (Util.isDesktop) { + final navigator = Navigator.of(context, rootNavigator: true); + final route = DialogRoute( + context: context, + builder: (context) => DesktopDialog( + maxWidth: 580, + maxHeight: double.infinity, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [DesktopDialogCloseButton()], + ), + Padding( + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), + child: DesktopAuthSend(coin: coin), + ), + ], + ), + ), + ); + unlocked = await navigator.push(route); + // Navigator.push completes when pop starts. Native Mimblewimble calls can + // block the UI isolate, so do not start one while the authentication + // dialog is still animating away. + await route.completed; + } else { + final navigator = Navigator.of(context); + final route = RouteGenerator.getRoute( + shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, + builder: (_) => LockscreenView( + showBackButton: true, + popOnSuccess: true, + routeOnSuccessArguments: true, + routeOnSuccess: "", + biometricsCancelButtonString: "CANCEL", + biometricsLocalizedReason: reason, + biometricsAuthenticationTitle: "Confirm Transaction", + ), + settings: const RouteSettings(name: "/confirmsendlockscreen"), + ); + unlocked = await navigator.push(route); + if (route case final TransitionRoute transitionRoute) { + await transitionRoute.completed; + } + } + + if (unlocked == true) return true; + // A closed dialog is not a failed attempt. + if (unlocked == false && context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.warning, + message: Util.isDesktop ? "Invalid passphrase" : "Invalid PIN", + context: context, + ); + } + return false; +} diff --git a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart index ef8a62ccaa..7bed13d380 100644 --- a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart +++ b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; +import '../../models/slatepack_models.dart'; import '../../themes/stack_colors.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; @@ -14,7 +15,18 @@ bool canCancelSlateTransaction({ }) => slateId?.isNotEmpty == true && !isCancelled && confirmations < 1; class SlatepackCancelTransactionDialog extends StatelessWidget { - const SlatepackCancelTransactionDialog({super.key}); + const SlatepackCancelTransactionDialog({ + super.key, + this.prompt = const SlatepackCancelPrompt( + title: "Cancel this transaction?", + message: + "This cancels the transaction in this wallet. It may not prevent " + "another party from completing or broadcasting it.", + confirmLabel: "Cancel it", + ), + }); + + final SlatepackCancelPrompt prompt; @override Widget build(BuildContext context) { @@ -26,15 +38,14 @@ class SlatepackCancelTransactionDialog extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( - "Cancel this transaction?", + prompt.title, style: Util.isDesktop ? STextStyles.desktopH3(context) : STextStyles.pageTitleH2(context), ), const SizedBox(height: 12), Text( - "This cancels the transaction in this wallet. It may not prevent " - "another party from completing or broadcasting it.", + prompt.message, style: STextStyles.smallMed14(context).copyWith( color: Theme.of(context).extension()!.textDark3, ), @@ -46,7 +57,7 @@ class SlatepackCancelTransactionDialog extends StatelessWidget { ), const SizedBox(height: 8), PrimaryButton( - label: "Cancel it", + label: prompt.confirmLabel, onPressed: () => Navigator.of(context).pop(true), ), ], diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index 26d1935ada..47cc5135d7 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; +import '../../route_generator.dart'; import '../../utilities/amount/amount.dart'; import '../../utilities/exception_message.dart'; import '../../themes/stack_colors.dart'; @@ -13,7 +14,11 @@ import '../../utilities/slatepack_text.dart'; import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../widgets/custom_loading_overlay.dart'; +import '../../widgets/desktop/desktop_dialog.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/desktop/secondary_button.dart'; import '../../widgets/stack_dialog.dart'; +import 'pay_invoice_confirm_view.dart'; import 'slatepack_dialog.dart'; import 'slatepack_popup.dart'; import 'slatepack_summary_dialog.dart'; @@ -26,6 +31,12 @@ enum SlatepackRoute { /// S2: finalize our send. finalizeSend, + /// I1: pay someone's invoice. + payInvoice, + + /// I2: finalize our invoice. + finalizeInvoice, + /// S3 or I3: nothing left to do. alreadyFinalized, @@ -44,10 +55,20 @@ abstract final class SlatepackImportFlow { static const _receiveHistoryLookupTimeout = Duration(seconds: 3); static const _finalizeHistoryLookupTimeout = Duration(seconds: 3); - static SlatepackRoute routeFor(SlateState state) => switch (state) { + static SlatepackRoute routeFor( + SlateState state, { + required bool supportsInvoices, + }) => switch (state) { SlateState.s1 => SlatepackRoute.receive, SlateState.s2 => SlatepackRoute.finalizeSend, - SlateState.i1 || SlateState.i2 => SlatepackRoute.invoicesUnsupported, + SlateState.i1 => + supportsInvoices + ? SlatepackRoute.payInvoice + : SlatepackRoute.invoicesUnsupported, + SlateState.i2 => + supportsInvoices + ? SlatepackRoute.finalizeInvoice + : SlatepackRoute.invoicesUnsupported, SlateState.s3 || SlateState.i3 => SlatepackRoute.alreadyFinalized, SlateState.unknown => SlatepackRoute.unsupported, }; @@ -69,16 +90,21 @@ abstract final class SlatepackImportFlow { final terms = wallet.slatepackTerms; final slatepack = normalize(text); - final read = await _withLoading( + final read = await withLoading( context, "Reading ${terms.noun}...", () async { final inspection = await wallet.inspectSlatepack(slatepack); - final route = routeFor(inspection.state); + final route = routeFor( + inspection.state, + supportsInvoices: wallet.supportsInvoices, + ); var historyLookupTimedOut = false; final needsLocalHistory = route == SlatepackRoute.receive || - route == SlatepackRoute.finalizeSend; + route == SlatepackRoute.finalizeSend || + route == SlatepackRoute.payInvoice || + route == SlatepackRoute.finalizeInvoice; final local = needsLocalHistory ? await wallet .localTxForSlate(inspection.slateId) @@ -114,7 +140,7 @@ abstract final class SlatepackImportFlow { switch (route) { case SlatepackRoute.receive: if (read.historyLookupTimedOut) { - await _message( + await showMessage( context, "Could not check wallet history", "The wallet is busy. Try importing this ${terms.noun} again.", @@ -128,11 +154,15 @@ abstract final class SlatepackImportFlow { "received or finalized." : "This transaction's earlier receive was cancelled. Ask the " "sender to create a new transaction."; - await _message(context, "Cannot receive this ${terms.noun}", reason); + await showMessage( + context, + "Cannot receive this ${terms.noun}", + reason, + ); return false; } if (local?.isSend == true) { - await _message( + await showMessage( context, "Cannot receive this ${terms.noun}", "This wallet created the transaction. Share this ${terms.noun} " @@ -141,7 +171,7 @@ abstract final class SlatepackImportFlow { return false; } if (local != null) { - await _message( + await showMessage( context, "Cannot receive this ${terms.noun}", "This transaction is already in this wallet's history.", @@ -153,7 +183,7 @@ abstract final class SlatepackImportFlow { case SlatepackRoute.finalizeSend: final local = read.local; if (local != null && !local.isSend) { - await _message( + await showMessage( context, "Cannot finalize this ${terms.noun}", "This ${terms.noun} belongs to a transaction this wallet " @@ -163,7 +193,7 @@ abstract final class SlatepackImportFlow { return false; } if (local?.isCancelled == true) { - await _message( + await showMessage( context, "Cannot finalize this ${terms.noun}", "This transaction was cancelled. A cancelled send cannot be " @@ -182,8 +212,73 @@ abstract final class SlatepackImportFlow { historyLookupTimedOut: read.historyLookupTimedOut, ); + case SlatepackRoute.payInvoice: + if (read.historyLookupTimedOut) { + await showMessage( + context, + "Could not check wallet history", + "The wallet is busy. Try importing this invoice again.", + ); + return false; + } + if (read.local != null) { + await showMessage( + context, + "Cannot pay this invoice", + "This wallet created the invoice. Share it with the wallet that " + "will pay it instead.", + ); + return false; + } + return _payInvoice(context, wallet, slatepack, inspection); + + case SlatepackRoute.finalizeInvoice: + if (read.historyLookupTimedOut) { + await showMessage( + context, + "Could not check wallet history", + "The wallet is busy. Try importing this invoice again.", + ); + return false; + } + final local = read.local; + if (local == null || local.isSend) { + await showMessage( + context, + "Cannot finalize this invoice", + local == null + ? "This wallet did not issue the invoice this ${terms.noun} " + "pays. Only the wallet that issued an invoice can " + "finalize it. If the invoice was made here moments " + "ago, let the wallet finish syncing and try again." + : "This ${terms.noun} is this wallet's own payment of an " + "invoice. Give it to the wallet that issued the " + "invoice, which is the one that finalizes it.", + ); + return false; + } + if (local.isCancelled) { + await showMessage( + context, + "Cannot finalize this invoice", + "This invoice was cancelled and cannot be finalized.", + ); + return false; + } + return _finalize( + context, + wallet, + slatepack, + inspection, + amount: local.amount, + fee: null, + historyWarning: false, + historyLookupTimedOut: false, + invoice: true, + ); + case SlatepackRoute.invoicesUnsupported: - await _message( + await showMessage( context, "Invoices not supported", "This ${terms.noun} is part of an invoice. " @@ -193,7 +288,22 @@ abstract final class SlatepackImportFlow { return false; case SlatepackRoute.alreadyFinalized: - await _message( + if (wallet.supportsRepost && + await wallet.canRepost(inspection.slateId)) { + if (!context.mounted) return false; + return offerRepost( + context, + wallet, + inspection.slateId, + title: "Already finalized", + message: + "This ${terms.noun} is already finalized, but the " + "transaction is not confirmed yet. You can post it to the " + "node again.", + ); + } + if (!context.mounted) return false; + await showMessage( context, "Already finalized", "This ${terms.noun} is already finalized. There is nothing left " @@ -202,7 +312,7 @@ abstract final class SlatepackImportFlow { return false; case SlatepackRoute.unsupported: - await _message( + await showMessage( context, "Unsupported ${terms.noun}", "Could not tell which step of a transaction this ${terms.noun} " @@ -249,7 +359,7 @@ abstract final class SlatepackImportFlow { // shown if the screen that started the import is gone by then. final root = Navigator.of(context, rootNavigator: true); - final result = await _withLoading( + final result = await withLoading( context, "Processing ${terms.noun}...", () async { @@ -303,6 +413,7 @@ abstract final class SlatepackImportFlow { required Amount? fee, required bool historyWarning, required bool historyLookupTimedOut, + bool invoice = false, }) async { final terms = wallet.slatepackTerms; @@ -330,18 +441,20 @@ abstract final class SlatepackImportFlow { "Review them with the other party before finalizing."; } - // An S2 may carry amount 0, so the summary shows [amount] and [fee] from - // our own record of the send. + // An S2 or I2 may carry amount 0, so the summary shows [amount] and + // [fee] from our own record of the send or issued invoice. final confirmed = await showSlatepackPopup( context: context, child: SlatepackSummaryDialog( - title: "Finalize ${terms.noun}", + title: invoice ? "Finalize invoice" : "Finalize ${terms.noun}", coin: wallet.cryptoCurrency, actionLabel: "Finalize", amount: amount, fee: fee, warning: warning, details: [ + if (invoice && inspection.senderAddress != null) + ("From", inspection.senderAddress!), if (inspection.slateId.isNotEmpty) ("Slate ID", inspection.slateId), if (wallet.supportsSlatepackEncryption) ("Encrypted", inspection.isEncrypted ? "Yes" : "No"), @@ -350,17 +463,21 @@ abstract final class SlatepackImportFlow { ); if (confirmed != true || !context.mounted) return false; - final result = await _withLoading( + final result = await withLoading( context, - "Finalizing ${terms.noun}...", + "Finalizing ${invoice ? "invoice" : terms.noun}...", () async { - final r = await wallet.finalizeSlatepack(text, inspection: inspection); + final r = invoice + ? await wallet.finalizeInvoice(text) + : await wallet.finalizeSlatepack(text, inspection: inspection); if (!r.success) { throw Exception(r.error ?? "Finalize failed"); } return r; }, - errorTitle: "${terms.title} finalize error", + errorTitle: invoice + ? "Invoice finalize error" + : "${terms.title} finalize error", ); if (result == null) return false; @@ -381,15 +498,9 @@ abstract final class SlatepackImportFlow { ), ); } else if (result.posted == false) { - await _message( - context, - "Finalized, not broadcast", - "The transaction is finalized but the node did not accept it yet. " - "Check the node connection and transaction history before " - "creating a replacement.", - ); + await notPosted(context, wallet, result.slateId ?? inspection.slateId); } else { - await _message( + await showMessage( context, "Transaction finalized", "The native wallet finalized the transaction, but its broadcast " @@ -400,9 +511,121 @@ abstract final class SlatepackImportFlow { return true; } + /// A finalized transaction the node did not take. Offers repost where + /// the wallet can do it. + static Future notPosted( + BuildContext context, + SlatepackInterface wallet, + String slateId, + ) async { + const message = + "The transaction is finalized but the node did not accept it yet."; + if (wallet.supportsRepost && slateId.isNotEmpty) { + await offerRepost( + context, + wallet, + slateId, + title: "Finalized, not broadcast", + message: + "$message You can post it again now, or later from the " + "transaction details.", + ); + } else { + await showMessage( + context, + "Finalized, not broadcast", + "$message The transaction may still be submitted later.", + ); + } + } + + /// Asks whether to post [slateId] again and does it. Returns true when + /// it was posted. + static Future offerRepost( + BuildContext context, + SlatepackInterface wallet, + String slateId, { + required String title, + required String message, + }) async { + final go = await showDialog( + context: context, + builder: (context) => StackDialog( + width: Util.isDesktop ? 500 : null, + title: title, + message: message, + leftButton: SecondaryButton( + label: "Later", + buttonHeight: Util.isDesktop ? ButtonHeight.l : null, + onPressed: () => Navigator.of(context).pop(false), + ), + rightButton: PrimaryButton( + label: "Repost", + buttonHeight: Util.isDesktop ? ButtonHeight.l : null, + onPressed: () => Navigator.of(context).pop(true), + ), + ), + ); + if (go != true || !context.mounted) return false; + + final done = await withLoading(context, "Posting transaction...", () async { + await wallet.repost(slateId); + return true; + }, errorTitle: "Repost failed"); + if (done != true || !context.mounted) return false; + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: "Transaction posted to the node", + context: context, + ), + ); + return true; + } + + static Future _payInvoice( + BuildContext context, + SlatepackInterface wallet, + String text, + SlateInspection inspection, + ) async { + if (inspection.amount == null || inspection.amount!.raw <= BigInt.zero) { + await showMessage( + context, + "Invoice", + "This invoice does not say how much to pay.", + ); + return false; + } + + final view = PayInvoiceConfirmView( + walletId: wallet.walletId, + invoice: text, + inspection: inspection, + ); + final bool? paid; + if (Util.isDesktop) { + paid = await showDialog( + context: context, + barrierDismissible: false, + builder: (_) => + DesktopDialog(maxWidth: 700, maxHeight: null, child: view), + ); + } else { + paid = await Navigator.of(context).push( + RouteGenerator.getRoute( + shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, + builder: (_) => view, + settings: const RouteSettings(name: PayInvoiceConfirmView.routeName), + ), + ); + } + return paid == true; + } + /// Runs [action] under a loading overlay. Shows the error and returns null /// when it throws. - static Future _withLoading( + static Future withLoading( BuildContext context, String message, Future Function() action, { @@ -459,16 +682,16 @@ abstract final class SlatepackImportFlow { ? "Unexpected result without an error" : stripExceptionPrefixes(error); if (context.mounted) { - await _message(context, errorTitle, text); + await showMessage(context, errorTitle, text); } else if (root.mounted) { - await _message(root.context, errorTitle, text); + await showMessage(root.context, errorTitle, text); } return null; } return result; } - static Future _message( + static Future showMessage( BuildContext context, String title, String message, diff --git a/lib/pages/slatepack/slatepack_input_field.dart b/lib/pages/slatepack/slatepack_input_field.dart index 9f3880288a..b3a819eb3c 100644 --- a/lib/pages/slatepack/slatepack_input_field.dart +++ b/lib/pages/slatepack/slatepack_input_field.dart @@ -36,6 +36,7 @@ class SlatepackInputField extends ConsumerStatefulWidget { required this.controller, required this.hint, required this.terms, + this.inputName, this.onChanged, this.focusNode, this.clipboard = const ClipboardWrapper(), @@ -44,10 +45,13 @@ class SlatepackInputField extends ConsumerStatefulWidget { final TextEditingController controller; final String hint; final SlatepackTerms terms; + final String? inputName; final void Function(String)? onChanged; final FocusNode? focusNode; final ClipboardInterface clipboard; + String get inputNoun => inputName ?? terms.noun; + @override ConsumerState createState() => _SlatepackInputFieldState(); @@ -113,7 +117,7 @@ class _SlatepackInputFieldState extends ConsumerState { } } else { Logging.instance.w( - "Camera permission error while scanning a ${widget.terms.noun}", + "Camera permission error while scanning a ${widget.inputNoun}", error: e, stackTrace: s, ); @@ -124,7 +128,7 @@ class _SlatepackInputFieldState extends ConsumerState { Future _openFile() async { try { final result = await FilePicker.platform.pickFiles( - dialogTitle: "Open ${widget.terms.noun} file", + dialogTitle: "Open ${widget.inputNoun} file", lockParentWindow: true, ); final picked = result?.files.singleOrNull; @@ -133,7 +137,7 @@ class _SlatepackInputFieldState extends ConsumerState { if (picked.size > kSlatepackFileMaxBytes) { throw Exception( "File is too large (${picked.size} bytes). " - "A ${widget.terms.noun} file is at most " + "A ${widget.inputNoun} file is at most " "$kSlatepackFileMaxBytes bytes.", ); } @@ -141,7 +145,7 @@ class _SlatepackInputFieldState extends ConsumerState { final List bytes = picked.bytes ?? await File(picked.path!).readAsBytes(); if (bytes.length > kSlatepackFileMaxBytes) { - throw Exception("File is too large to be a ${widget.terms.noun}."); + throw Exception("File is too large to be a ${widget.inputNoun}."); } final text = utf8.decode(bytes).trim(); @@ -153,7 +157,7 @@ class _SlatepackInputFieldState extends ConsumerState { _showError("That file is not a text file."); } catch (e, s) { Logging.instance.w( - "Opening ${widget.terms.noun} file failed", + "Opening ${widget.inputNoun} file failed", error: e, stackTrace: s, ); diff --git a/lib/pages/slatepack/slatepack_recipient_field.dart b/lib/pages/slatepack/slatepack_recipient_field.dart new file mode 100644 index 0000000000..7f0c713b6a --- /dev/null +++ b/lib/pages/slatepack/slatepack_recipient_field.dart @@ -0,0 +1,96 @@ +import 'package:flutter/material.dart'; +import 'package:grin_native/grin_native.dart' show GrinAddressKind; + +import '../../themes/stack_colors.dart'; +import '../../utilities/constants.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/crypto_currency/crypto_currency.dart'; +import '../../widgets/stack_text_field.dart'; + +/// Optional address a slatepack send is encrypted to. +class SlatepackRecipientField extends StatefulWidget { + const SlatepackRecipientField({ + super.key, + required this.controller, + required this.coin, + this.label = "Recipient address (optional)", + this.help = + "The Slatepack is encrypted to this address and a payment proof is " + "requested. Leave empty to hand out a plain Slatepack.", + }); + + final TextEditingController controller; + final CryptoCurrency coin; + final String label; + final String help; + + /// Empty, or an address the coin accepts. + static bool isAcceptable(CryptoCurrency coin, String text) { + final trimmed = text.trim(); + return trimmed.isEmpty || + (coin is Grin + ? coin.addressKind(trimmed) == GrinAddressKind.slatepack + : coin.validateAddress(trimmed)); + } + + @override + State createState() => + _SlatepackRecipientFieldState(); +} + +class _SlatepackRecipientFieldState extends State { + final _focusNode = FocusNode(); + + @override + void dispose() { + _focusNode.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final valid = SlatepackRecipientField.isAcceptable( + widget.coin, + widget.controller.text, + ); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular( + Constants.size.circularBorderRadius, + ), + child: TextField( + key: const Key("slatepackRecipientFieldKey"), + controller: widget.controller, + focusNode: _focusNode, + autocorrect: false, + enableSuggestions: false, + onChanged: (_) => setState(() {}), + style: isDesktop + ? STextStyles.desktopTextExtraSmall(context) + .copyWith(color: colors.textFieldActiveText, height: 1.8) + : STextStyles.field(context), + decoration: standardInputDecoration( + widget.label, + _focusNode, + context, + desktopMed: true, + ), + ), + ), + const SizedBox(height: 6), + Text( + valid ? widget.help : "Not a ${widget.coin.prettyName} address.", + style: STextStyles.label(context) + .copyWith(color: valid ? colors.textSubtitle1 : colors.textError), + ), + ], + ); + } +} diff --git a/lib/pages/slatepack/slatepack_send_flow.dart b/lib/pages/slatepack/slatepack_send_flow.dart index 2b6fcd6305..a47f97c808 100644 --- a/lib/pages/slatepack/slatepack_send_flow.dart +++ b/lib/pages/slatepack/slatepack_send_flow.dart @@ -15,7 +15,7 @@ import '../../widgets/custom_loading_overlay.dart'; import '../../widgets/stack_dialog.dart'; import 'slatepack_dialog.dart'; -/// Creates a manual Epic or MWC slate directly from either send screen. +/// Creates a manual Mimblewimble slate directly from either send screen. /// /// A manual slate is the first step of an interactive transaction, not a /// transaction ready to approve and broadcast. It therefore bypasses the @@ -26,6 +26,9 @@ abstract final class SlatepackSendFlow { required BuildContext context, required SlatepackInterface wallet, required Amount amount, + Amount? creationAmount, + String? recipientAddress, + bool sendAll = false, required String message, required String localNote, required MainDB db, @@ -63,10 +66,12 @@ abstract final class SlatepackSendFlow { // keyboard or another route is still animating away. await waitForRoutePresentation(overlay); result = await wallet.createSlatepack( - amount: amount, + amount: creationAmount ?? amount, + recipientAddress: recipientAddress, message: wallet.supportsOnChainNote && message.isNotEmpty ? message : null, + sendAll: sendAll, ); if (!result.success || (result.slatepack?.trim().isEmpty ?? true)) { throw Exception( diff --git a/lib/pages/slatepack/verify_payment_proof_view.dart b/lib/pages/slatepack/verify_payment_proof_view.dart new file mode 100644 index 0000000000..052fbea5ca --- /dev/null +++ b/lib/pages/slatepack/verify_payment_proof_view.dart @@ -0,0 +1,237 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../models/slatepack_models.dart'; +import '../../providers/global/wallets_provider.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/amount/amount_formatter.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/background.dart'; +import '../../widgets/conditional_parent.dart'; +import '../../widgets/custom_buttons/app_bar_icon_button.dart'; +import '../../widgets/desktop/desktop_dialog.dart'; +import '../../widgets/desktop/desktop_dialog_close_button.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/detail_item.dart'; +import '../../widgets/rounded_container.dart'; +import '../../widgets/rounded_white_container.dart'; +import 'slatepack_import_flow.dart'; +import 'slatepack_input_field.dart'; + +/// Opens the payment proof check: a page on mobile, a dialog on desktop. +Future showVerifyPaymentProof(BuildContext context, String walletId) { + final view = VerifyPaymentProofView(walletId: walletId); + if (Util.isDesktop) { + return showDialog( + context: context, + builder: (_) => + DesktopDialog(maxWidth: 700, maxHeight: null, child: view), + ); + } + return Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => view, + settings: const RouteSettings(name: VerifyPaymentProofView.routeName), + ), + ); +} + +/// Checks a payment proof through the wallet's node. +class VerifyPaymentProofView extends ConsumerStatefulWidget { + const VerifyPaymentProofView({super.key, required this.walletId}); + + static const String routeName = "/verifyPaymentProof"; + + final String walletId; + + @override + ConsumerState createState() => + _VerifyPaymentProofViewState(); +} + +class _VerifyPaymentProofViewState + extends ConsumerState { + late final SlatepackInterface _wallet; + final _controller = TextEditingController(); + PaymentProofCheck? _check; + bool _busy = false; + + @override + void initState() { + super.initState(); + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _verify() async { + if (_busy) return; + setState(() { + _busy = true; + _check = null; + }); + try { + final check = await SlatepackImportFlow.withLoading( + context, + "Checking payment proof...", + () => _wallet.verifyPaymentProof(_controller.text), + errorTitle: "Payment proof not verified", + ); + if (mounted) setState(() => _check = check); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Widget _result(BuildContext context, PaymentProofCheck check) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final formatter = ref.watch(pAmountFormatter(_wallet.cryptoCurrency)); + final rows = <(String, String)>[ + ("Amount", formatter.format(check.amount)), + ("Kernel excess", check.kernelExcess), + ("Sender address", check.senderAddress), + ("Recipient address", check.recipientAddress), + ("This wallet sent it", check.isSender ? "Yes" : "No"), + ("This wallet received it", check.isRecipient ? "Yes" : "No"), + ]; + return Column( + key: const Key("paymentProofResult"), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RoundedContainer( + color: colors.snackBarBackSuccess, + child: Text( + "Signatures valid. Kernel presence as reported by your node.", + style: STextStyles.label(context) + .copyWith(color: colors.snackBarTextSuccess), + ), + ), + const SizedBox(height: 12), + RoundedWhiteContainer( + padding: EdgeInsets.zero, + borderColor: isDesktop ? colors.backgroundAppBar : null, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) const DetailDivider(), + DetailItem(title: rows[i].$1, detail: rows[i].$2), + ], + ], + ), + ), + if (!check.isSender && !check.isRecipient) ...[ + const SizedBox(height: 12), + Text( + "The proof is valid but neither address belongs to this wallet.", + style: STextStyles.label(context), + ), + ], + ], + ); + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final canVerify = !_busy && _controller.text.trim().isNotEmpty; + + final body = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + "A payment proof shows that a recipient's address signed for an " + "amount. The check looks up the transaction kernel through your " + "node.", + style: STextStyles.label(context), + ), + const SizedBox(height: 16), + SlatepackInputField( + controller: _controller, + hint: "Payment proof (JSON)", + terms: _wallet.slatepackTerms, + inputName: "payment proof", + onChanged: (_) => setState(() => _check = null), + ), + const SizedBox(height: 16), + PrimaryButton( + key: const Key("verifyPaymentProofButton"), + label: "Verify", + buttonHeight: isDesktop ? ButtonHeight.l : null, + enabled: canVerify, + onPressed: canVerify ? _verify : null, + ), + if (_check != null) ...[ + const SizedBox(height: 24), + _result(context, _check!), + ], + ], + ); + + return ConditionalParent( + condition: !isDesktop, + builder: (child) => Background( + child: Scaffold( + backgroundColor: colors.background, + appBar: AppBar( + backgroundColor: colors.background, + leading: AppBarBackButton( + onPressed: () => Navigator.of(context).pop(), + ), + title: Text( + "Verify payment proof", + style: STextStyles.navBarTitle(context), + ), + ), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: child, + ), + ), + ), + ), + child: ConditionalParent( + condition: isDesktop, + builder: (child) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Padding( + padding: const EdgeInsets.only(left: 32), + child: Text( + "Verify payment proof", + style: STextStyles.desktopH3(context), + ), + ), + const DesktopDialogCloseButton(), + ], + ), + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), + child: child, + ), + ), + ], + ), + child: body, + ), + ); + } +} diff --git a/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart b/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart index 120b99b258..5f8e0701a2 100644 --- a/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart +++ b/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart @@ -12,6 +12,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../models/balance.dart'; +import '../../../providers/global/wallets_provider.dart'; import '../../../providers/wallet/public_private_balance_state_provider.dart'; import '../../../providers/wallet/wallet_balance_toggle_state_provider.dart'; import '../../../themes/stack_colors.dart'; @@ -22,6 +23,7 @@ import '../../../utilities/enums/wallet_balance_toggle_state.dart'; import '../../../utilities/text_styles.dart'; import '../../../wallets/crypto_currency/crypto_currency.dart'; import '../../../wallets/isar/providers/wallet_info_provider.dart'; +import '../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; enum _BalanceType { available, full, privateAvailable, privateFull } @@ -42,25 +44,27 @@ class WalletBalanceToggleSheet extends ConsumerWidget { final balance = ref.watch(pWalletBalance(walletId)); + // Funds held by unfinished slatepack sends, not in either balance. + final wallet = ref.watch(pWallets).getWallet(walletId); + final locked = wallet is SlatepackInterface ? wallet.amountLocked : null; + _BalanceType _bal = ref.watch(walletBalanceToggleStateProvider.state).state == - WalletBalanceToggleState.available - ? _BalanceType.available - : _BalanceType.full; + WalletBalanceToggleState.available + ? _BalanceType.available + : _BalanceType.full; Balance? balancePrivate; if (hasPrivate) { - balancePrivate = - isMweb - ? ref.watch(pWalletBalanceSecondary(walletId)) - : ref.watch(pWalletBalanceTertiary(walletId)); + balancePrivate = isMweb + ? ref.watch(pWalletBalanceSecondary(walletId)) + : ref.watch(pWalletBalanceTertiary(walletId)); if (ref.watch(publicPrivateBalanceStateProvider.state).state == BalanceType.private) { - _bal = - _bal == _BalanceType.available - ? _BalanceType.privateAvailable - : _BalanceType.privateFull; + _bal = _bal == _BalanceType.available + ? _BalanceType.privateAvailable + : _BalanceType.privateFull; } } @@ -85,10 +89,9 @@ class WalletBalanceToggleSheet extends ConsumerWidget { Center( child: Container( decoration: BoxDecoration( - color: - Theme.of( - context, - ).extension()!.textFieldDefaultBG, + color: Theme.of(context) + .extension()! + .textFieldDefaultBG, borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), @@ -196,6 +199,17 @@ class WalletBalanceToggleSheet extends ConsumerWidget { value: _BalanceType.privateFull, groupValue: _bal, ), + if (locked != null) ...[ + const SizedBox(height: 16), + Padding( + padding: const EdgeInsets.only(left: 8.0), + child: Text( + "Locked in unfinished transactions: " + "${ref.watch(pAmountFormatter(coin)).format(locked)}", + style: STextStyles.label(context), + ), + ), + ], const SizedBox(height: 40), ], ), @@ -244,10 +258,9 @@ class BalanceSelector extends ConsumerWidget { width: 20, height: 20, child: Radio( - activeColor: - Theme.of( - context, - ).extension()!.radioButtonIconEnabled, + activeColor: Theme.of(context) + .extension()! + .radioButtonIconEnabled, value: value, groupValue: groupValue, onChanged: onChanged, @@ -262,10 +275,9 @@ class BalanceSelector extends ConsumerWidget { Text( ref.watch(pAmountFormatter(coin)).format(balance), style: STextStyles.itemSubtitle12(context).copyWith( - color: - Theme.of( - context, - ).extension()!.textSubtitle1, + color: Theme.of(context) + .extension()! + .textSubtitle1, ), ), ], diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/slatepack_tx_details.dart b/lib/pages/wallet_view/transaction_views/tx_v2/slatepack_tx_details.dart new file mode 100644 index 0000000000..3bb1ff7c5d --- /dev/null +++ b/lib/pages/wallet_view/transaction_views/tx_v2/slatepack_tx_details.dart @@ -0,0 +1,330 @@ +import 'dart:convert'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:share_plus/share_plus.dart'; + +import '../../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import '../../../../models/slatepack_models.dart'; +import '../../../../notifications/show_flush_bar.dart'; +import '../../../../themes/stack_colors.dart'; +import '../../../../utilities/assets.dart'; +import '../../../../utilities/clipboard_interface.dart'; +import '../../../../utilities/logger.dart'; +import '../../../../utilities/text_styles.dart'; +import '../../../../utilities/util.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../../../widgets/desktop/primary_button.dart'; +import '../../../../widgets/desktop/secondary_button.dart'; +import '../../../../widgets/rounded_white_container.dart'; +import '../../../slatepack/slatepack_dialog.dart'; +import '../../../slatepack/slatepack_import_flow.dart'; +import '../../../slatepack/slatepack_popup.dart'; + +/// Slatepack rows and actions on the transaction details screen: kernel +/// excess, counterparty, expiry, and show again, repost and proof export. +class SlatepackTxDetails extends StatelessWidget { + const SlatepackTxDetails({ + super.key, + required this.wallet, + required this.transaction, + required this.info, + this.onReposted, + this.clipboard = const ClipboardWrapper(), + }); + + final SlatepackInterface wallet; + final TransactionV2 transaction; + final SlatepackTxInfo info; + final VoidCallback? onReposted; + final ClipboardInterface clipboard; + + Future _showAgain(BuildContext context) async { + final slatepack = await SlatepackImportFlow.withLoading( + context, + "Loading ${wallet.slatepackTerms.noun}...", + () async { + final text = await wallet.pendingSlatepackFor(transaction.txid); + if (text == null) { + throw Exception( + "This wallet no longer has the ${wallet.slatepackTerms.noun}.", + ); + } + return text; + }, + errorTitle: "Not available", + ); + if (slatepack == null || !context.mounted) return; + await showSlatepackDialog( + context: context, + terms: wallet.slatepackTerms, + // The stored text does not include the metadata needed to say whether + // this particular Slatepack was encrypted. Do not claim either state. + supportsEncryption: false, + result: SlatepackResult( + success: true, + slatepack: slatepack, + state: info.state, + slateId: info.slateId, + ), + ); + } + + Future _repost(BuildContext context) async { + final posted = await SlatepackImportFlow.offerRepost( + context, + wallet, + transaction.txid, + title: "Repost transaction", + message: + "Post the finalized transaction to the node again. Do this when " + "it does not confirm.", + ); + if (posted) onReposted?.call(); + } + + Future _exportProof(BuildContext context) async { + final proof = await SlatepackImportFlow.withLoading( + context, + "Loading payment proof...", + () => wallet.exportPaymentProof(transaction.txid), + errorTitle: "Payment proof", + ); + if (proof == null || !context.mounted) return; + await showSlatepackPopup( + context: context, + child: PaymentProofExportDialog( + proof: proof, + fileName: "${info.slateId ?? transaction.txid}.proof.json", + clipboard: clipboard, + ), + ); + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final labelStyle = isDesktop + ? STextStyles.desktopTextExtraExtraSmall(context) + : STextStyles.itemSubtitle(context); + final detailStyle = isDesktop + ? STextStyles.desktopTextExtraExtraSmall(context) + .copyWith(color: colors.textDark) + : STextStyles.itemSubtitle12(context); + + Widget row(String label, String value, {bool copy = false}) { + return Padding( + padding: EdgeInsets.only(top: isDesktop ? 16 : 12), + child: RoundedWhiteContainer( + padding: isDesktop + ? const EdgeInsets.all(16) + : const EdgeInsets.all(12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: labelStyle), + const SizedBox(height: 4), + SelectableText(value, style: detailStyle), + ], + ), + ), + if (copy) + IconButton( + tooltip: "Copy", + icon: Icon(Icons.copy, size: 16, color: colors.infoItemIcons), + onPressed: () async { + await clipboard.setData(ClipboardData(text: value)); + if (context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.info, + message: "Copied to clipboard", + iconAsset: Assets.svg.copy, + context: context, + ); + } + }, + ), + ], + ), + ), + ); + } + + final actions = [ + if (info.canShowSlatepack) + SecondaryButton( + label: "Show ${wallet.slatepackTerms.title} again", + buttonHeight: isDesktop ? ButtonHeight.m : null, + onPressed: () => _showAgain(context), + ), + if (info.canRepost && wallet.supportsRepost) + SecondaryButton( + label: "Repost", + buttonHeight: isDesktop ? ButtonHeight.m : null, + onPressed: () => _repost(context), + ), + if (info.hasPaymentProof && wallet.supportsPaymentProofs) + SecondaryButton( + label: "Export payment proof", + buttonHeight: isDesktop ? ButtonHeight.m : null, + onPressed: () => _exportProof(context), + ), + ]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (info.finalizedAwaitingConfirmation) + row("Status", "Finalized, awaiting confirmation"), + if (info.kernelExcess != null) + row("Kernel excess", info.kernelExcess!, copy: true), + if (info.counterpartyAddress != null) + row("Counterparty", info.counterpartyAddress!, copy: true), + // The cutoff only matters until the transaction is mined. + if (info.ttlCutoffHeight != null && (transaction.height ?? 0) <= 0) + row("Expires at block", info.ttlCutoffHeight.toString()), + for (final action in actions) ...[ + SizedBox(height: isDesktop ? 16 : 12), + action, + ], + ], + ); + } +} + +/// A payment proof to copy, share or save. +class PaymentProofExportDialog extends StatelessWidget { + const PaymentProofExportDialog({ + super.key, + required this.proof, + required this.fileName, + this.clipboard = const ClipboardWrapper(), + }); + + final String proof; + final String fileName; + final ClipboardInterface clipboard; + + String get _pretty { + try { + return const JsonEncoder.withIndent(" ").convert(jsonDecode(proof)); + } catch (_) { + return proof; + } + } + + Future _save(BuildContext context) async { + try { + final path = await FilePicker.platform.saveFile( + dialogTitle: "Save payment proof", + fileName: fileName, + bytes: Uint8List.fromList(utf8.encode(_pretty)), + ); + if (path != null && context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.success, + message: "Payment proof saved", + context: context, + ); + } + } catch (e, s) { + Logging.instance.e( + "Saving payment proof failed", + error: e, + stackTrace: s, + ); + if (context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.warning, + message: "Could not save the payment proof", + context: context, + ); + } + } + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + return SlatepackPopupLayout( + title: "Payment proof", + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + "Anyone with this proof can check, through a Grin node, that the " + "recipient's address signed for this amount and that the kernel " + "is on the chain.", + style: STextStyles.label(context), + ), + const SizedBox(height: 12), + RoundedWhiteContainer( + child: SelectableText( + _pretty, + style: STextStyles.label(context) + .copyWith(fontFamily: "monospace"), + ), + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: SecondaryButton( + label: "Copy", + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: () async { + await clipboard.setData(ClipboardData(text: _pretty)); + if (context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.info, + message: "Payment proof copied", + iconAsset: Assets.svg.copy, + context: context, + ); + } + }, + ), + ), + const SizedBox(width: 12), + Expanded( + child: SecondaryButton( + label: "Share", + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: () async { + try { + await SharePlus.instance.share( + ShareParams(text: _pretty, subject: "Payment proof"), + ); + } catch (e, s) { + Logging.instance.e( + "Sharing payment proof failed", + error: e, + stackTrace: s, + ); + } + }, + ), + ), + const SizedBox(width: 12), + Expanded( + child: PrimaryButton( + label: "Save", + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: () => _save(context), + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart index a3d9298acc..f3ca3539df 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart @@ -23,6 +23,7 @@ import 'package:url_launcher/url_launcher.dart'; import '../../../../models/isar/models/blockchain_data/transaction.dart'; import '../../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; import '../../../../models/isar/models/contract.dart'; +import '../../../../models/slatepack_models.dart'; import '../../../../notifications/show_flush_bar.dart'; import '../../../../providers/global/address_book_service_provider.dart'; import '../../../../providers/providers.dart'; @@ -66,6 +67,7 @@ import '../../wallet_view.dart'; import '../dialogs/cancelling_transaction_progress_dialog.dart'; import '../edit_note_view.dart'; import 'boost_transaction_view.dart'; +import 'slatepack_tx_details.dart'; class TransactionV2DetailsView extends ConsumerStatefulWidget { const TransactionV2DetailsView({ @@ -103,9 +105,38 @@ class _TransactionV2DetailsViewState late final bool hasTxKeyProbably; late final bool isSlatepackWallet; late final bool showOnChainNote; + SlatepackTxInfo? _slatepackInfo; bool get isTokenTx => tokenContract != null; + bool _canCancelSlatepackTransaction(int currentHeight) { + if (!isSlatepackWallet || + _transaction.getConfirmations(currentHeight) >= 1 || + _transaction.isCancelled || + _transaction.isReverted || + _transaction.slateId == null) { + return false; + } + + // Only Grin exposes round-trip state. Do not infer state from message + // counts for Epic or MWC: preserve the base predicate for those wallets. + return _slatepackInfo?.canCancel ?? + canCancelSlateTransaction( + slateId: _transaction.slateId, + isCancelled: _transaction.isCancelled, + confirmations: _transaction.getConfirmations(currentHeight), + ); + } + + void _reloadSlatepackInfo() { + if (!mounted) return; + final wallet = ref.read(pWallets).getWallet(walletId); + if (wallet is! SlatepackInterface) return; + setState(() { + _slatepackInfo = wallet.slatepackTxInfo(_transaction); + }); + } + late final List<({List addresses, Amount amount})> data; bool showFeePending = false; @@ -210,6 +241,9 @@ class _TransactionV2DetailsViewState isSlatepackWallet = wallet is SlatepackInterface; showOnChainNote = wallet is SlatepackInterface && wallet.supportsOnChainNote; + _slatepackInfo = wallet is SlatepackInterface + ? wallet.slatepackTxInfo(_transaction) + : null; hasTxKeyProbably = (wallet is CryptonoteWallet) && @@ -1451,6 +1485,15 @@ class _TransactionV2DetailsViewState ], ), ), + if (_slatepackInfo != null) + SlatepackTxDetails( + wallet: + ref.read(pWallets).getWallet(walletId) + as SlatepackInterface, + transaction: _transaction, + info: _slatepackInfo!, + onReposted: _reloadSlatepackInfo, + ), if (!isDesktop) const SizedBox(height: 12), // if (whatIsIt( // _transaction, @@ -1469,27 +1512,14 @@ class _TransactionV2DetailsViewState ), ), ), - if (isSlatepackWallet && - canCancelSlateTransaction( - slateId: _transaction.slateId, - isCancelled: _transaction.isCancelled, - confirmations: _transaction.getConfirmations( - currentHeight, - ), - )) + if (_canCancelSlatepackTransaction(currentHeight)) const SizedBox(height: 40), ], ), ), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, - floatingActionButton: - (isSlatepackWallet && - canCancelSlateTransaction( - slateId: _transaction.slateId, - isCancelled: _transaction.isCancelled, - confirmations: _transaction.getConfirmations(currentHeight), - )) + floatingActionButton: _canCancelSlatepackTransaction(currentHeight) ? ConditionalParent( condition: isDesktop, builder: (child) => Padding( @@ -1525,10 +1555,15 @@ class _TransactionV2DetailsViewState return; } + final prompt = SlatepackCancelPrompt.of( + _slatepackInfo, + incoming: + _transaction.type == TransactionType.incoming, + ); final proceed = await showDialog( context: context, builder: (_) => - const SlatepackCancelTransactionDialog(), + SlatepackCancelTransactionDialog(prompt: prompt), ); if (proceed != true || !context.mounted) return; diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart index 242e71e8d1..379a2b4df8 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart @@ -26,10 +26,16 @@ import '../../../../widgets/loading_indicator.dart'; import '../../../../widgets/stack_text_field.dart'; class DesktopAuthSend extends ConsumerStatefulWidget { - const DesktopAuthSend({super.key, required this.coin, this.tokenTicker}); + const DesktopAuthSend({ + super.key, + required this.coin, + this.tokenTicker, + this.actionDescription, + }); final CryptoCurrency coin; final String? tokenTicker; + final String? actionDescription; @override ConsumerState createState() => _DesktopAuthSendState(); @@ -104,7 +110,7 @@ class _DesktopAuthSendState extends ConsumerState { Text("Confirm transaction", style: STextStyles.desktopH3(context)), const SizedBox(height: 16), Text( - "Enter your wallet password to send ${widget.tokenTicker?.toUpperCase() ?? widget.coin.ticker.toUpperCase()}", + "Enter your wallet password to ${widget.actionDescription ?? "send ${widget.tokenTicker?.toUpperCase() ?? widget.coin.ticker.toUpperCase()}"}", style: STextStyles.desktopTextMedium(context).copyWith( color: Theme.of(context).extension()!.textDark3, ), @@ -153,9 +159,9 @@ class _DesktopAuthSendState extends ConsumerState { hidePassword ? Assets.svg.eye : Assets.svg.eyeSlash, - color: Theme.of( - context, - ).extension()!.textDark3, + color: Theme.of(context) + .extension()! + .textDark3, width: 24, height: 24, ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart index e03703cde9..f94f0d4bcd 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart @@ -22,6 +22,7 @@ import '../../../../models/isar/models/isar_models.dart'; import '../../../../models/keys/view_only_wallet_data.dart'; import '../../../../notifications/show_flush_bar.dart'; import '../../../../pages/receive_view/generate_receiving_uri_qr_code_view.dart'; +import '../../../../pages/slatepack/request_invoice_view.dart'; import '../../../../pages/slatepack/slatepack_import_flow.dart'; import '../../../../pages/slatepack/slatepack_input_field.dart'; import '../../../../providers/providers.dart'; @@ -84,6 +85,7 @@ class _DesktopReceiveState extends ConsumerState { late final bool usesSlatepacks; late final TextEditingController _receiveSlateController; late final SlatepackTerms _slatepackTerms; + SlatepackInterface? _slatepackWallet; bool _importingSlatepack = false; int _currentIndex = 0; @@ -299,6 +301,7 @@ class _DesktopReceiveState extends ConsumerState { _slatepackTerms = wallet is SlatepackInterface ? wallet.slatepackTerms : SlatepackTerms.slatepack; + _slatepackWallet = wallet is SlatepackInterface ? wallet : null; if (wallet is ViewOnlyOptionInterface && wallet.isViewOnly) { showMultiType = false; @@ -618,6 +621,22 @@ class _DesktopReceiveState extends ConsumerState { ), ), + if (_slatepackWallet?.receiveAddressNote != null) ...[ + const SizedBox(height: 12), + Text( + _slatepackWallet!.receiveAddressNote!, + style: STextStyles.desktopTextExtraExtraSmall(context), + ), + ], + if (_slatepackWallet?.supportsInvoices ?? false) ...[ + const SizedBox(height: 20), + SecondaryButton( + buttonHeight: ButtonHeight.l, + label: "Request payment", + onPressed: () => showRequestInvoice(context, walletId), + ), + ], + if (canGen) const SizedBox(height: 20), if (canGen) @@ -636,7 +655,9 @@ class _DesktopReceiveState extends ConsumerState { const SizedBox(height: 20), Center( child: QR( - data: AddressUtils.buildUriString(coin.uriScheme, address, {}), + data: _slatepackWallet?.receiveQrIsRawAddress ?? false + ? address + : AddressUtils.buildUriString(coin.uriScheme, address, {}), size: 200, ), ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart index 20afa0f621..afd7f37a42 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart @@ -29,6 +29,7 @@ import '../../../../pages/send_view/frost_ms/recipient.dart'; import '../../../../pages/send_view/sub_widgets/building_transaction_dialog.dart'; import '../../../../pages/send_view/sub_widgets/multi_recipient.dart'; import '../../../../pages/slatepack/slatepack_send_flow.dart'; +import '../../../../pages/slatepack/slatepack_recipient_field.dart'; import '../../../../providers/providers.dart'; import '../../../../providers/ui/fee_rate_type_state_provider.dart'; import '../../../../providers/ui/preview_tx_button_state_provider.dart'; @@ -110,6 +111,7 @@ class _DesktopSendState extends ConsumerState { late final ClipboardInterface clipboard; late TextEditingController sendToController; + final _slatepackRecipientController = TextEditingController(); late TextEditingController cryptoAmountController; late TextEditingController baseAmountController; late TextEditingController memoController; @@ -126,6 +128,11 @@ class _DesktopSendState extends ConsumerState { late final bool hasOptionalMemo; late final bool usesSlatepacks; + String? get _directSendAddressHint { + final wallet = ref.read(pWallets).getWallet(walletId); + return wallet is SlatepackInterface ? wallet.directSendAddressHint : null; + } + void _formatMimblewimbleAddress() { var address = sendToController.text.trim(); if (address.isEmpty) return; @@ -268,8 +275,12 @@ class _DesktopSendState extends ConsumerState { final nonce = nonceInput.value; final wallet = ref.read(pWallets).getWallet(walletId); - final isSlatepackSend = - wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + final slatepackWallet = wallet is SlatepackInterface ? wallet : null; + final selectedSlatepack = + slatepackWallet != null && ref.read(pIsSlatepack(walletId)); + final manualAddressRecipient = slatepackWallet + ?.manualSlatepackRecipientForAddress(_address ?? ""); + final isSlatepackSend = selectedSlatepack || manualAddressRecipient != null; String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; @@ -292,10 +303,17 @@ class _DesktopSendState extends ConsumerState { final Amount amount = ref.read(pSendAmount)!; if (isSlatepackSend) { + final slatepackRecipient = _slatepackRecipientController.text.trim(); final created = await SlatepackSendFlow.run( context: context, - wallet: wallet, + wallet: slatepackWallet!, amount: amount, + recipientAddress: + manualAddressRecipient ?? + (slatepackWallet.supportsSlatepackRecipient && + slatepackRecipient.isNotEmpty + ? slatepackRecipient + : null), message: _onChainNote ?? "", localNote: _note ?? "", db: ref.read(mainDBProvider), @@ -733,6 +751,7 @@ class _DesktopSendState extends ConsumerState { baseAmountController.text = ""; memoController.text = ""; nonceController.text = ""; + _slatepackRecipientController.text = ""; _address = ""; _addressToggleFlag = false; _clearRecipientForms(); @@ -1399,6 +1418,7 @@ class _DesktopSendState extends ConsumerState { _feeAmount.dispose(); sendToController.dispose(); + _slatepackRecipientController.dispose(); cryptoAmountController.dispose(); baseAmountController.dispose(); memoController.dispose(); @@ -1479,6 +1499,10 @@ class _DesktopSendState extends ConsumerState { ref.watch(pWallets).getWallet(walletId) is CoinControlInterface && ref.watch(pWallets).getWallet(walletId) is! SalviumWallet && (showPrivateBalance ? balType == BalanceType.public : true); + final isManualSlatepackCreation = + ref.watch(pIsSlatepack(widget.walletId)) || + (wallet is SlatepackInterface && + wallet.manualSlatepackRecipientForAddress(_address ?? "") != null); return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -1512,6 +1536,17 @@ class _DesktopSendState extends ConsumerState { ), ), + if (usesSlatepacks && + ref.watch(pIsSlatepack(widget.walletId)) && + (wallet as SlatepackInterface).supportsSlatepackRecipient) + Padding( + padding: const EdgeInsets.only(bottom: 16), + child: SlatepackRecipientField( + controller: _slatepackRecipientController, + coin: coin, + ), + ), + if (coin is Firo) Text( "Send from", @@ -1884,7 +1919,12 @@ class _DesktopSendState extends ConsumerState { _applyUri(parsed); } else { _setOpReturnData(null); - await _checkSparkNameAndOrSetAddress(newValue); + // The field already contains this text. Writing it back + // moves the cursor to the end on every edit. + await _checkSparkNameAndOrSetAddress( + newValue, + setController: false, + ); } } else { _setOpReturnData(null); @@ -1911,7 +1951,8 @@ class _DesktopSendState extends ConsumerState { standardInputDecoration( ref.watch(pIsSlatepack(widget.walletId)) ? "Enter ${coin.ticker} address (optional)" - : "Enter ${coin.ticker} address", + : _directSendAddressHint ?? + "Enter ${coin.ticker} address", _addressFocusNode, context, desktopMed: true, @@ -2283,9 +2324,7 @@ class _DesktopSendState extends ConsumerState { (!needsEthFee || ethFee != null); return PrimaryButton( buttonHeight: ButtonHeight.l, - label: - ref.watch(pIsSlatepack(widget.walletId)) && - wallet is SlatepackInterface + label: isManualSlatepackCreation && wallet is SlatepackInterface ? "Create ${wallet.slatepackTerms.noun}" : "Preview send", enabled: enabled, diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart index ac01104ff3..ef6adc6b5c 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart @@ -33,6 +33,7 @@ import '../../../../wallets/isar/providers/eth/token_balance_provider.dart'; import '../../../../wallets/isar/providers/solana/current_sol_token_wallet_provider.dart'; import '../../../../wallets/isar/providers/solana/sol_token_balance_provider.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import 'desktop_balance_toggle_button.dart'; class DesktopWalletSummary extends ConsumerStatefulWidget { @@ -161,6 +162,11 @@ class _WDesktopWalletSummaryState extends ConsumerState { balanceToShow = _showAvailable ? balance.spendable : balance.total; } + final wallet = ref.watch(pWallets).getWallet(walletId); + final locked = widget.isToken || wallet is! SlatepackInterface + ? null + : wallet.amountLocked; + return Consumer( builder: (context, ref, __) { return Row( @@ -182,9 +188,19 @@ class _WDesktopWalletSummaryState extends ConsumerState { SelectableText( "${Amount.fromDecimal(price.value * balanceToShow.decimal, fractionDigits: 2).fiatString(locale: locale)} $baseCurrency", style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textSubtitle1, + color: Theme.of(context) + .extension()! + .textSubtitle1, + ), + ), + if (locked != null && locked.raw > BigInt.zero) + SelectableText( + "Locked in unfinished transactions: " + "${ref.watch(pAmountFormatter(coin)).format(locked)}", + style: STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textSubtitle1, ), ), // if (coin is Firo) diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart index ca6521ce04..a1807bf0a6 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart @@ -20,6 +20,7 @@ import '../../../../pages/settings_views/wallet_settings_view/wallet_settings_wa import '../../../../pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/edit_refresh_height_view.dart'; import '../../../../pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/spark_view_key_view.dart'; import '../../../../pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/xpub_view.dart'; +import '../../../../pages/slatepack/verify_payment_proof_view.dart'; import '../../../../providers/global/wallets_provider.dart'; import '../../../../route_generator.dart'; import '../../../../themes/stack_colors.dart'; @@ -35,6 +36,7 @@ import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; import '../../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/extended_keys_interface.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/view_only_option_interface.dart'; import '../../../addresses/desktop_wallet_addresses_view.dart'; @@ -50,7 +52,8 @@ enum _WalletOptions { frostOptions, refreshFromHeight, showSparkKey, - epicBoxSettings; + epicBoxSettings, + verifyPaymentProof; String get prettyName { switch (this) { @@ -70,6 +73,8 @@ enum _WalletOptions { return "Show Spark View Key"; case _WalletOptions.epicBoxSettings: return "Epic Box settings"; + case _WalletOptions.verifyPaymentProof: + return "Verify payment proof"; } } } @@ -133,6 +138,9 @@ class WalletOptionsButton extends ConsumerWidget { onEpicBoxSettingsPressed: () async { Navigator.of(context).pop(_WalletOptions.epicBoxSettings); }, + onVerifyPaymentProofPressed: () async { + Navigator.of(context).pop(_WalletOptions.verifyPaymentProof); + }, walletId: walletId, ); }, @@ -314,6 +322,9 @@ class WalletOptionsButton extends ConsumerWidget { ), ); break; + case _WalletOptions.verifyPaymentProof: + unawaited(showVerifyPaymentProof(context, walletId)); + break; } } }, @@ -346,6 +357,7 @@ class WalletOptionsPopupMenu extends ConsumerWidget { required this.onFrostMSWalletOptionsPressed, required this.onRefreshHeightPressed, required this.onEpicBoxSettingsPressed, + this.onVerifyPaymentProofPressed, required this.walletId, }); @@ -356,6 +368,7 @@ class WalletOptionsPopupMenu extends ConsumerWidget { final VoidCallback onFrostMSWalletOptionsPressed; final VoidCallback onRefreshHeightPressed; final VoidCallback onEpicBoxSettingsPressed; + final VoidCallback? onVerifyPaymentProofPressed; final String walletId; @override @@ -535,6 +548,44 @@ class WalletOptionsPopupMenu extends ConsumerWidget { ), ), ), + if (wallet is SlatepackInterface && + wallet.supportsPaymentProofs && + onVerifyPaymentProofPressed != null) ...[ + const SizedBox(height: 8), + TransparentButton( + onPressed: onVerifyPaymentProofPressed, + child: Padding( + padding: const EdgeInsets.all(8), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + SvgPicture.asset( + Assets.svg.checkCircle, + width: 20, + height: 20, + color: Theme.of(context) + .extension()! + .textFieldActiveSearchIconLeft, + ), + const SizedBox(width: 14), + Expanded( + child: Text( + _WalletOptions.verifyPaymentProof.prettyName, + style: + STextStyles.desktopTextExtraExtraSmall( + context, + ).copyWith( + color: Theme.of(context) + .extension()! + .textDark, + ), + ), + ), + ], + ), + ), + ), + ], if (wallet is EpiccashWallet) const SizedBox(height: 8), if (wallet is EpiccashWallet) TransparentButton( diff --git a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart index ca988e1d82..0b9c9c0b4b 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart @@ -47,6 +47,7 @@ class DesktopManageBlockExplorersDialog extends ConsumerWidget { e is! Mimblewimblecoin && e is! Grin, ) + .where(hasDefaultBlockExplorer) .toList(); return DesktopDialog( diff --git a/lib/themes/theme_service.dart b/lib/themes/theme_service.dart index 04e32f6de2..c5b09cbc3f 100644 --- a/lib/themes/theme_service.dart +++ b/lib/themes/theme_service.dart @@ -31,7 +31,7 @@ final pThemeService = Provider((ref) { }); class ThemeService { - static const _currentDefaultThemeVersion = 18; + static const _currentDefaultThemeVersion = 19; ThemeService._(); static ThemeService? _instance; static ThemeService get instance => _instance ??= ThemeService._(); @@ -160,9 +160,8 @@ class ThemeService { } final themesDir = StackFileSystem.themesDir!; - final jsonFileExists = await File( - "${themesDir.path}/$themeId/theme.json", - ).exists(); + final jsonFileExists = await File("${themesDir.path}/$themeId/theme.json") + .exists(); final assetsDirExists = await Directory( "${themesDir.path}/$themeId/assets", ).exists(); diff --git a/lib/utilities/address_utils.dart b/lib/utilities/address_utils.dart index 9005166e64..f7184d4db0 100644 --- a/lib/utilities/address_utils.dart +++ b/lib/utilities/address_utils.dart @@ -255,12 +255,25 @@ class AddressUtils { const cashAddrSchemes = {"bitcoincash", "bchtest", "ecash", "ectest"}; final parsedUri = Uri.tryParse(uri); final scheme = parsedUri?.scheme.toLowerCase(); + // A raw address is not a payment URI. Return before the legacy parser so + // address pastes do not turn an expected miss into a logged exception. + if (scheme == null || scheme.isEmpty) { + return null; + } if (parsedUri != null && (scheme == "xel" || (!parsedUri.hasQuery && cashAddrSchemes.contains(scheme)))) { return null; } + // A web URL is a send address for coins that send over HTTP (Epic Cash's + // and Grin's foreign API), never a payment URI. Without this, typing the + // "http:" of such an address parsed as a URI with an empty address and + // cleared the field. + if (scheme == "http" || scheme == "https") { + return null; + } + try { final parsedUri = _parseUri(uri); final Map parsedData = parsedUri.params; diff --git a/lib/utilities/block_explorers.dart b/lib/utilities/block_explorers.dart index b7f55b4b4e..bf7f316255 100644 --- a/lib/utilities/block_explorers.dart +++ b/lib/utilities/block_explorers.dart @@ -18,10 +18,7 @@ Future setBlockExplorerForCoin({ required Uri url, }) async { return await MainDB.instance.putTransactionBlockExplorer( - TransactionBlockExplorer( - ticker: coin.ticker, - url: url.toString(), - ), + TransactionBlockExplorer(ticker: coin.ticker, url: url.toString()), ); } @@ -30,8 +27,9 @@ Uri getBlockExplorerTransactionUrlFor({ required CryptoCurrency coin, required String txid, }) { - String? url = - MainDB.instance.getTransactionBlockExplorer(cryptoCurrency: coin)?.url; + String? url = MainDB.instance + .getTransactionBlockExplorer(cryptoCurrency: coin) + ?.url; if (url == null) { return coin.defaultBlockExplorer(txid); } else { @@ -39,3 +37,15 @@ Uri getBlockExplorerTransactionUrlFor({ return Uri.parse(url); } } + +/// Whether [coin] has a default block explorer. Coins without one throw from +/// [CryptoCurrency.defaultBlockExplorer], so they cannot be offered where an +/// explorer URL is shown or edited. +bool hasDefaultBlockExplorer(CryptoCurrency coin) { + try { + coin.defaultBlockExplorer("[TXID]"); + return true; + } catch (_) { + return false; + } +} diff --git a/lib/wallets/wallet/impl/epiccash_wallet.dart b/lib/wallets/wallet/impl/epiccash_wallet.dart index d6f3a8117b..86294fed61 100644 --- a/lib/wallets/wallet/impl/epiccash_wallet.dart +++ b/lib/wallets/wallet/impl/epiccash_wallet.dart @@ -235,6 +235,7 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }) async { try { _hackedCheckTorNodePrefs(); diff --git a/lib/wallets/wallet/impl/grin_wallet.dart b/lib/wallets/wallet/impl/grin_wallet.dart index c6337cd495..975e68270d 100644 --- a/lib/wallets/wallet/impl/grin_wallet.dart +++ b/lib/wallets/wallet/impl/grin_wallet.dart @@ -15,10 +15,10 @@ import '../../../app_config.dart'; import '../../../exceptions/wallet/node_tor_mismatch_config_exception.dart'; import '../../../models/balance.dart'; import '../../../models/isar/models/blockchain_data/address.dart'; -import '../../../models/isar/models/blockchain_data/transaction.dart'; import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; import '../../../models/node_model.dart'; import '../../../models/paymint/fee_object_model.dart'; +import '../../../models/slatepack_models.dart'; import '../../../services/event_bus/events/global/blocks_remaining_event.dart'; import '../../../services/event_bus/events/global/node_connection_status_changed_event.dart'; import '../../../services/event_bus/events/global/refresh_percent_changed_event.dart'; @@ -40,6 +40,7 @@ import '../../models/tx_data.dart'; import '../intermediate/bip39_wallet.dart'; import '../supporting/grin/grin_errors.dart'; import '../supporting/grin/grin_node_url.dart'; +import '../supporting/grin/grin_scan_pause_observer.dart'; import '../supporting/grin/grin_transport.dart'; import '../supporting/grin/grin_tx_mapping.dart'; import '../supporting/grin_wallet_info_extension.dart'; @@ -70,7 +71,7 @@ typedef _AppliedNetwork = ({ GrinTransport transport, }); -class GrinWallet extends Bip39Wallet { +class GrinWallet extends Bip39Wallet with SlatepackInterface { GrinWallet( CryptoCurrencyNetwork network, { GrinWalletBackend? backend, @@ -234,6 +235,18 @@ class GrinWallet extends Bip39Wallet { double highestPercent = 0; + GrinScanPauseObserver? _pauseObserver; + + /// Whether going to the background cancels a running scan. Mobile only. + @visibleForTesting + bool get cancelScanOnPause => Platform.isAndroid || Platform.isIOS; + + /// Cancels a running scan; it resumes on the next refresh. + void cancelRunningScan() { + if (_scanJob == null) return; + _api?.cancelScan(); + } + /// Whether the Tor feature is compiled in. @visibleForTesting bool get torFeatureEnabled => AppConfig.hasFeature(AppFeature.tor); @@ -243,6 +256,24 @@ class GrinWallet extends Bip39Wallet { bool get _scanPending => info.grinData?.pendingScanFrom != null; + @override + Map get slatepackTransactionMetadata => + info.grinData?.slatepackTransactions ?? const {}; + + @override + Future updateSlatepackTransactionMetadata( + Map metadata, + ) async { + final current = info.grinData; + if (current == null) return; + await info.updateGrinData( + grinData: current.withSlatepackTransactions( + Map.from(metadata), + ), + isar: mainDB.isar, + ); + } + /// Whether a scan has to finish before node refreshes, fee estimates, /// cancels and sends. bool get isScanPending => _scanPending; @@ -375,12 +406,20 @@ class GrinWallet extends Bip39Wallet { _owners[walletId] = this; _exited = false; _subscribeTor(); + if (cancelScanOnPause) { + _pauseObserver ??= GrinScanPauseObserver( + cancelScan: cancelRunningScan, + resumeScan: () => unawaited(_resumeAfterPause()), + ); + } } bool get _isLive => _api != null || _scanJob != null; Future _releaseOwnership() async { if (identical(_owners[walletId], this)) _owners.remove(walletId); + _pauseObserver?.dispose(); + _pauseObserver = null; await _cancelTorSubscriptions(); } @@ -446,6 +485,8 @@ class GrinWallet extends Bip39Wallet { ); } } + _localSyncRequested = false; + await _localSyncJob; await _releaseOwnership(); _api = null; _applied = null; @@ -656,6 +697,7 @@ class GrinWallet extends Bip39Wallet { } Future _runScanJob() { + if (_pauseObserver?.isPaused ?? false) return Future.value(); final running = _scanJob; if (running != null) return running; late final Future job; @@ -684,6 +726,7 @@ class GrinWallet extends Bip39Wallet { await _requireNetwork(); // Stopped before it started: nothing was scanned. if (_scanStopRequested) return; + if (_pauseObserver?.isPaused ?? false) return; await api.scan(startHeight: from); await _setPendingScanFrom(null); succeeded = true; @@ -708,6 +751,12 @@ class GrinWallet extends Bip39Wallet { } } + Future _resumeAfterPause() async { + final running = _scanJob; + if (running != null) await running; + if (!_exited && _api != null && _scanPending) await refresh(); + } + /// Moves the resume height past what the ended scan says it saved. /// /// An error without a height (a scan cancelled before it started, or one @@ -815,6 +864,7 @@ class GrinWallet extends Bip39Wallet { switch (event.newStatus) { case TorConnectionStatus.connecting: _torConnecting ??= Completer(); + unawaited(_applyTransport()); case TorConnectionStatus.connected: case TorConnectionStatus.disconnected: _releaseTorWaiters(); @@ -847,6 +897,10 @@ class GrinWallet extends Bip39Wallet { /// before the preference they belong to. A running scan is cancelled first /// so the change does not wait a whole batch; it resumes on the next /// refresh. + /// + /// While Tor connects the applied transport stays, unless it is a direct + /// one: the library would keep using it, for a whole scan batch at worst. + /// The network is then turned off until Tor connects or gives up. Future _applyTransport({bool refreshAfter = true}) async { Future? cancelledScan; final changed = await _transportMutex.protect(() async { @@ -854,7 +908,9 @@ class GrinWallet extends Bip39Wallet { if (api == null || _exited) return false; final network = _resolveNetwork(); final transport = network.transport; - if (transport is GrinHold) return false; + if (transport is GrinHold && _applied?.transport is! GrinDirect) { + return false; + } if (network == _applied) return false; if (_scanJob != null) { @@ -865,13 +921,17 @@ class GrinWallet extends Bip39Wallet { nodeUrl: network.nodeUrl, apiSecret: network.apiSecret, socksProxy: transport is GrinProxy ? transport.address : null, - networkEnabled: transport is! GrinBlocked, + networkEnabled: transport is GrinDirect || transport is GrinProxy, ); _applied = network; return true; }); if (!changed) return; + // On hold: the Tor event that ends the wait applies the next transport + // and refreshes. + if (_applied?.transport is GrinHold) return; + if (_applied?.transport is GrinBlocked) { _fireDisconnected(); } else if (refreshAfter && shouldAutoSync) { @@ -930,16 +990,28 @@ class GrinWallet extends Bip39Wallet { return api; } + static const _scanningMessage = + "Wait for the Grin wallet to finish scanning and try again."; + void _refuseWhileScanning() { - if (_scanPending) { - throw GrinWalletException( - "Wait for the Grin wallet to finish scanning and try again.", - ); - } + if (_scanPending) throw GrinWalletException(_scanningMessage); } - Exception _fail(String operation, Object error) => - _failStatic(operation, error); + /// [message] replaces the fixed text for a library error and keeps its + /// type, code, slate id and flags. + /// + Exception _fail(String operation, Object error, {String? message}) { + final ex = _failStatic(operation, error); + if (message == null || ex is! GrinWalletException) return ex; + return GrinWalletException( + message, + type: ex.type, + code: ex.code, + slateId: ex.slateId, + finalized: ex.finalized, + released: ex.released, + ); + } // ========== Sync =========================================================== @@ -991,20 +1063,71 @@ class GrinWallet extends Bip39Wallet { } @override - Future updateTransactions() async { + Future updateTransactions() => + _updateTransactions(refreshFromNode: !_scanPending); + + Future _updateTransactions({required bool refreshFromNode}) async { final current = _api; if (current == null || _exited) return; try { - final fromNode = !_scanPending; - final api = fromNode ? await _requireNetwork() : current; - final list = await api.getTransactions(refreshFromNode: fromNode); - if (fromNode) _offline = !list.refreshedFromNode; + final api = refreshFromNode ? await _requireNetwork() : current; + final list = await api.getTransactions(refreshFromNode: refreshFromNode); + if (refreshFromNode) _offline = !list.refreshedFromNode; await _storeTransactions(list); } catch (e) { throw _fail("updateTransactions", e); } } + /// Synchronizes state already held by grin-wallet. This never contacts the + /// node and is therefore safe on the short Slatepack UI paths. + Future _syncLocalWalletState() async { + if (_api == null || _exited) return; + try { + await _updateTransactions(refreshFromNode: false); + await updateBalance(); + } catch (e, s) { + Logging.instance.w( + "Could not copy local Grin wallet state", + error: e, + stackTrace: s, + ); + } + } + + Future? _localSyncJob; + bool _localSyncRequested = false; + + /// Copies native local state in the background without holding a Slatepack + /// screen behind Isar I/O. Requests are coalesced, and a mutation that lands + /// while a copy is running causes one more pass so it cannot be missed. + void _scheduleLocalWalletSync() { + if (_exited) return; + _localSyncRequested = true; + if (_localSyncJob != null) return; + + _localSyncJob = _drainLocalWalletSync(); + unawaited( + _localSyncJob!.whenComplete(() { + _localSyncJob = null; + if (_localSyncRequested && !_exited) _scheduleLocalWalletSync(); + }), + ); + } + + Future _drainLocalWalletSync() async { + do { + _localSyncRequested = false; + await _syncLocalWalletState(); + } while (_localSyncRequested && !_exited); + } + + void _syncAfterSlateError(Object error) { + if (error is GrinException && error.slateId != null && !_exited) { + _scheduleLocalWalletSync(); + } + } + Future _storeTransactions(GrinTxList list) async { _slatepacks = { for (final entry in list.transactions) @@ -1012,6 +1135,10 @@ class GrinWallet extends Bip39Wallet { grinTxid(entry): entry.armoredSlatepack!, }; + // There is nothing to merge. Avoid opening an unnecessary Isar query on + // every brand-new wallet and after operations that leave no local entry. + if (list.transactions.isEmpty) return; + final txids = {for (final entry in list.transactions) grinTxid(entry)}; final stored = await mainDB.isar.transactionV2s .where() @@ -1042,10 +1169,11 @@ class GrinWallet extends Bip39Wallet { refreshFromNode: false, minimumConfirmations: cryptoCurrency.minConfirms, ); - await info.updateBalance( - newBalance: grinBalanceToStack(balance, cryptoCurrency.fractionDigits), - isar: mainDB.isar, - ); + _amountLocked = _amount(balance.amountLocked); + final mapped = grinBalanceToStack(balance, cryptoCurrency.fractionDigits); + if (info.cachedBalance.toJsonIgnoreCoin() != mapped.toJsonIgnoreCoin()) { + await info.updateBalance(newBalance: mapped, isar: mainDB.isar); + } } catch (e) { throw _fail("updateBalance", e); } @@ -1082,14 +1210,20 @@ class GrinWallet extends Bip39Wallet { // ========== Sending ======================================================== /// Methods a Grin send can use. + @override List get supportedMethods => const [ SlatepackMethod.slatepack, SlatepackMethod.http, ]; /// Slate V4 has no message. + @override bool get supportsOnChainNote => false; + @override + bool get supportsSlatepackEncryption => true; + + @override bool get supportsInvoices => true; BigInt _nano(Amount amount) { @@ -1124,26 +1258,61 @@ class GrinWallet extends Bip39Wallet { transport: _applied?.transport ?? _resolveNetwork().transport, torWanted: _torWanted, kind: kind, - isPlainHttp: - kind == GrinAddressKind.http && - address.trim().toLowerCase().startsWith("http://"), + isPlainHttp: _isPlainHttp(address, kind), clearnetAcknowledged: clearnetAcknowledged, plaintextAcknowledged: plaintextAcknowledged, ); if (refusal == null) return; - throw GrinWalletException(switch (refusal) { - GrinSendRefusal.blocked => "The Grin wallet's network is blocked.", - GrinSendRefusal.torRequired => - "Sending to this address needs Tor. Turn Tor on and try again.", - GrinSendRefusal.torDown => - "Tor is not connected. Nothing was sent or locked.", - GrinSendRefusal.clearnetNotAcknowledged => - "Sending without Tor shows your IP address to the recipient.", - GrinSendRefusal.plaintextNotAcknowledged => - "This address uses unencrypted http://.", - GrinSendRefusal.unsupportedTarget => - "This is not an address a Grin wallet can send to.", - }); + throw GrinWalletException(_refusalMessage(refusal)); + } + + static String _refusalMessage(GrinSendRefusal refusal) => switch (refusal) { + GrinSendRefusal.blocked => + "The Grin wallet's network is blocked. Check the node and Tor " + "settings.", + GrinSendRefusal.torRequired => + "Sending to this address needs Tor. Turn Tor on and try again.", + GrinSendRefusal.torDown => + "Tor is not connected. Nothing was sent or locked.", + GrinSendRefusal.clearnetNotAcknowledged => + "Sending without Tor shows your IP address to the recipient.", + GrinSendRefusal.plaintextNotAcknowledged => + "This address uses unencrypted http://.", + GrinSendRefusal.unsupportedTarget => + "This is not an address a Grin wallet can send to.", + }; + + bool _isPlainHttp(String address, GrinAddressKind? kind) => + kind == GrinAddressKind.http && + address.trim().toLowerCase().startsWith("http://"); + + /// What the confirm screen must ask or refuse before an HTTP send. + @override + SlatepackHttpPolicy httpSendPolicy(String address) { + final kind = cryptoCurrency.addressKind(address); + // Resolved now: the applied transport can lag a Tor change. + final transport = _resolveNetwork().transport; + final plain = _isPlainHttp(address, kind); + GrinSendRefusal? check({required bool clearnet, required bool plaintext}) => + grinHttpSendRefusal( + transport: transport, + torWanted: _torWanted, + kind: kind, + isPlainHttp: plain, + clearnetAcknowledged: clearnet, + plaintextAcknowledged: plaintext, + ); + + final hard = check(clearnet: true, plaintext: true); + if (hard != null) { + return SlatepackHttpPolicy(blockedReason: _refusalMessage(hard)); + } + return SlatepackHttpPolicy( + needsClearnetAck: + check(clearnet: false, plaintext: true) == + GrinSendRefusal.clearnetNotAcknowledged, + needsPlaintextAck: plain, + ); } @override @@ -1195,7 +1364,7 @@ class GrinWallet extends Bip39Wallet { return txData.copyWith( recipients: [recipient.copyWith(amount: _amount(estimate.amount))], fee: _amount(estimate.fee), - otherData: slatepackMethodOtherData(method, existing: txData.otherData), + otherData: slatepackMethodOtherData(method), subtractFeeFromAmount: sendAll, ); } catch (e) { @@ -1222,12 +1391,18 @@ class GrinWallet extends Bip39Wallet { throw GrinWalletException("Grin has no relay."); case SlatepackMethod.slatepack: + await _checkFeeUnchanged(amount: amount, sendAll: sendAll, fee: fee); final slatepack = await _initSend( amount: amount, recipientAddress: address.isEmpty ? null : address, sendAll: sendAll, ); - unawaited(refresh()); + if (fee != null && slatepack.fee != fee.raw) { + // The inputs are locked and nothing was handed out yet. + await _giveUpSend(slatepack.slateId); + throw GrinWalletException(_feeChanged); + } + _scheduleLocalWalletSync(); return txData.copyWith( txid: slatepack.slateId, slatepack: slatepack.armoredSlatepack, @@ -1241,28 +1416,87 @@ class GrinWallet extends Bip39Wallet { clearnetAcknowledged: txData.grinClearnetAcknowledged, plaintextAcknowledged: txData.grinPlaintextAcknowledged, ); - final result = await api.sendHttp( - GrinHttpSendArgs( - amount: amount, - recipientUrlOrAddress: address, - minimumConfirmations: cryptoCurrency.minConfirms, - selectionStrategyIsAll: sendAll, - amountIncludesFee: sendAll, - ttlBlocks: slatepackTtlBlocks, - post: true, - ), - ); - unawaited(refresh()); + await _checkFeeUnchanged(amount: amount, sendAll: sendAll, fee: fee); + final GrinSendResult result; + try { + result = await api.sendHttp( + GrinHttpSendArgs( + amount: amount, + recipientUrlOrAddress: address, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + ttlBlocks: slatepackTtlBlocks, + post: true, + ), + ); + } on GrinSlateException catch (e) { + _syncAfterSlateError(e); + throw _fail("sendHttp", e, message: _badAnswerMessage(e)); + } on GrinTransactionException catch (e) { + _syncAfterSlateError(e); + throw _fail("sendHttp", e, message: _badAnswerMessage(e)); + } + _scheduleLocalWalletSync(); return txData.copyWith( txid: result.slateId, fee: _amount(result.fee), ); } } catch (e) { + _syncAfterSlateError(e); throw _fail("confirmSend", e); } } + /// The text for an HTTP send whose answer from the recipient was refused. + /// + /// Without a slate id the answer failed before anything was locked. With + /// one it failed at finalization, after the inputs were locked: the + /// library then cancels the send again and says so, or could not and + /// leaves it in the history to cancel. + static String _badAnswerMessage(GrinException error) { + const failed = "The recipient's answer failed checks."; + if (error.slateId == null) return "$failed Nothing was sent or locked."; + if (error.released) { + return "$failed Nothing was sent and no funds are locked."; + } + return "$failed Nothing was sent. $grinLeftPendingNote"; + } + + static const _feeChanged = + "The fee changed after you reviewed this send. Nothing was sent. " + "Review it again."; + + /// Throws when a send of [amount] no longer costs [fee], the fee the user + /// confirmed. The wallet's outputs can change between review and confirm. + Future _checkFeeUnchanged({ + required BigInt amount, + required bool sendAll, + required Amount? fee, + }) async { + if (fee == null) return; + final api = await _requireNetwork(); + final estimate = await api.estimateFee( + amount: amount, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + ); + if (estimate.fee != fee.raw) throw GrinWalletException(_feeChanged); + } + + /// Cancels a send that was started and must not go on. If the cancel + /// fails the send stays in the history, where it can be cancelled. + Future _giveUpSend(String slateId) async { + try { + await _requireApi().cancelTransaction(slateId: slateId); + } catch (e) { + Logging.instance.w("Grin send not cancelled: ${describeGrinError(e)}"); + } + _scheduleLocalWalletSync(); + } + Future _initSend({ required BigInt amount, required String? recipientAddress, @@ -1315,6 +1549,7 @@ class GrinWallet extends Bip39Wallet { // ========== Slatepacks ===================================================== /// The address counterparties send to. + @override Future slatepackAddress() async { final stored = await getCurrentReceivingAddress(); if (stored != null) return stored.value; @@ -1335,44 +1570,156 @@ class GrinWallet extends Bip39Wallet { } } + @override + bool get supportsSlatepackRecipient => true; + + @override + String? manualSlatepackRecipientForAddress(String address) { + final trimmed = address.trim(); + return cryptoCurrency.addressKind(trimmed) == GrinAddressKind.slatepack + ? trimmed + : null; + } + + @override + String? get directSendAddressHint => + "${cryptoCurrency.network == CryptoCurrencyNetwork.main ? "grin1" : "tgrin1"}" + " address, onion or http(s) URL"; + + @override + bool get receiveQrIsRawAddress => true; + + @override + String? get receiveAddressNote => + "Grin is received by Slatepack, or directly by your own listener. " + "Only this address receives; this wallet does not make new ones."; + + @override + Amount? get amountLocked => _amountLocked; + Amount? _amountLocked; + + SlateState _state(GrinSlateState state) => + SlateState.fromCode(state.wireName); + + SlatepackResult _result(GrinSlatepack slatepack) => SlatepackResult( + success: true, + slatepack: slatepack.armoredSlatepack, + wasEncrypted: slatepack.isEncrypted, + recipientAddress: slatepack.recipients.isEmpty + ? null + : slatepack.recipients.first, + state: _state(slatepack.state), + slateId: slatepack.slateId, + amount: _amount(slatepack.amount), + fee: _amount(slatepack.fee), + ); + + FinalizeResult _finalized(GrinFinalizeResult result) => FinalizeResult( + success: true, + slateId: result.slateId, + posted: result.posted, + kernelExcess: result.kernelExcess, + ); + + /// A finalize that failed. A node error that names the slate means the + /// transaction was finalized and stored but not accepted: success, not + /// posted, so the screens offer repost. + FinalizeResult _finalizeFailure( + String operation, + Object error, { + required String notFoundMessage, + }) { + _syncAfterSlateError(error); + final ex = error is GrinNotFoundException + ? _fail(operation, error, message: notFoundMessage) + : _fail(operation, error); + if (ex is GrinWalletException && ex.finalizedNotBroadcast) { + return FinalizeResult( + success: true, + error: ex.message, + slateId: ex.slateId, + posted: false, + ); + } + return FinalizeResult(success: false, error: ex.toString()); + } + /// Reads a Slatepack without changing anything. During a scan, a plain /// one is read without the wallet so it does not wait for the batch. - Future inspectSlatepack(String armored) async { + @override + Future inspectSlatepack(String armored) async { + final GrinSlateInfo info; try { - if (_scanJob != null) { - try { - return await backend.decodeSlatepackWithoutWallet( - armored, - cryptoCurrency.grinNetwork, - ); - } on GrinSlateException { - // Encrypted; only the wallet can read it. - } - } - return await _requireApi().decodeSlatepack(armored); + info = await _decode(armored); } catch (e) { throw _fail("inspectSlatepack", e); } + final state = _state(info.state); + // S2 and I2 carry amount 0; the local transaction has the real one. + final hasAmount = state != SlateState.s2 && state != SlateState.i2; + return SlateInspection( + state: state, + slateId: info.slateId, + amount: hasAmount ? _amount(info.amount) : null, + // An I1 carries fee 0: the payer sets it. + fee: info.fee > BigInt.zero ? _amount(info.fee) : null, + senderAddress: info.sender, + recipientAddress: info.recipients.isEmpty ? null : info.recipients.first, + isEncrypted: info.isEncrypted, + ttlCutoffHeight: info.ttlCutoffHeight, + ); + } + + Future _decode(String armored) async { + if (_scanJob != null) { + try { + return await backend.decodeSlatepackWithoutWallet( + armored, + cryptoCurrency.grinNetwork, + ); + } on GrinSlateException { + // Not readable without the wallet, which is busy until the scan + // ends. An encrypted Slatepack and a damaged one look the same + // here. + throw GrinWalletException( + "This Slatepack cannot be read while the Grin wallet is scanning. " + "If it is encrypted, wait for the scan to finish and try again.", + ); + } + } + return await _requireApi().decodeSlatepack(armored); } - /// Amount and fee of the stored transaction for [slateId]. - Future<({Amount amount, Amount fee})?> localTxForSlate(String slateId) async { - final tx = await _storedTx(slateId); - if (tx == null) return null; - final fractionDigits = cryptoCurrency.fractionDigits; - final amount = tx.type == TransactionType.incoming - ? tx.getAmountReceivedInThisWallet(fractionDigits: fractionDigits) - : tx.getAmountSentFromThisWallet( - fractionDigits: fractionDigits, - subtractFee: true, - ); - return (amount: amount, fee: tx.getFee(fractionDigits: fractionDigits)); + /// Amount, fee and direction of the stored transaction for [slateId]. An + /// invoice this wallet issued is a receive; a payment of someone's + /// invoice is a send. + @override + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async { + final known = await super.localTxForSlate(slateId); + if (known != null || _scanJob != null) return known; + + // A previous process may have exited after grin-wallet recorded the slate + // but before Isar was updated. Read native history locally only: importing + // a slate must never wait for Tor or a node refresh. + try { + await _updateTransactions(refreshFromNode: false); + } catch (e) { + Logging.instance.w( + "Grin local history read failed: ${describeGrinError(e)}", + ); + } + return super.localTxForSlate(slateId); } - /// Starts a Slatepack send and returns the S1. Locks the inputs. - Future createSlatepack({ + /// Starts a Slatepack send and returns the S1. Locks the inputs. With a + /// recipient address the S1 is encrypted to it and asks for a payment + /// proof. Grin slates have no message. + @override + Future createSlatepack({ required Amount amount, String? recipientAddress, + String? message, bool sendAll = false, }) async { try { @@ -1389,55 +1736,113 @@ class GrinWallet extends Bip39Wallet { recipientAddress: (address?.isEmpty ?? true) ? null : address, sendAll: sendAll, ); - unawaited(refresh()); - return result; + final slatepack = _result(result); + await rememberPendingSlateSend(slatepack); + _scheduleLocalWalletSync(); + return slatepack; } catch (e) { - throw _fail("createSlatepack", e); + _syncAfterSlateError(e); + return SlatepackResult( + success: false, + error: _fail("createSlatepack", e).toString(), + ); } } /// Answers an S1 and returns the S2. - Future receiveSlatepack(String s1) async { + @override + Future receiveSlatepack( + String s1, { + SlateInspection? inspection, + }) async { try { - final result = await _requireApi().receiveSlatepack(s1); - unawaited(refresh()); - return result; + _refuseWhileScanning(); + final api = await _requireNetwork(); + final result = await api.receiveSlatepack(s1); + final slatepack = _result(result); + await rememberPendingSlateReceive(slatepack); + _scheduleLocalWalletSync(); + return slatepack; } catch (e) { - throw _fail("receiveSlatepack", e); + _syncAfterSlateError(e); + return SlatepackResult( + success: false, + error: _fail("receiveSlatepack", e).toString(), + ); } } /// Finalizes a send from its S2 and broadcasts it. - Future finalizeSlatepack(String s2) async { + @override + Future finalizeSlatepack( + String s2, { + SlateInspection? inspection, + }) async { try { + _refuseWhileScanning(); final api = await _requireNetwork(); final result = await api.finalizeSlatepack(s2); - unawaited(refresh()); - return result; + final finalized = _finalized(result); + await rememberSlateBroadcastStatus(finalized.slateId, finalized.posted); + _scheduleLocalWalletSync(); + return finalized; } catch (e) { - throw _fail("finalizeSlatepack", e); + final failure = _finalizeFailure( + "finalizeSlatepack", + e, + notFoundMessage: "This is not a pending send from this wallet.", + ); + await rememberSlateBroadcastStatus(failure.slateId, failure.posted); + return failure; } } - /// Requests a payment and returns the I1. - Future issueInvoice({ + /// Requests a payment and returns the I1. Locks nothing. + @override + Future issueInvoice({ required Amount amount, String? payerAddress, }) async { try { - final result = await _requireApi().issueInvoice( - GrinInvoiceArgs(amount: _nano(amount), recipientAddress: payerAddress), + final payer = payerAddress?.trim(); + if (payer != null && + payer.isNotEmpty && + cryptoCurrency.addressKind(payer) != GrinAddressKind.slatepack) { + throw GrinWalletException( + "An invoice can only be encrypted to a Grin address.", + ); + } + final nano = _nano(amount); + if (nano <= BigInt.zero) { + throw GrinWalletException("The amount must be more than zero."); + } + _refuseWhileScanning(); + final api = await _requireNetwork(); + final result = await api.issueInvoice( + GrinInvoiceArgs( + amount: nano, + recipientAddress: (payer?.isEmpty ?? true) ? null : payer, + ), ); - unawaited(refresh()); - return result; + final invoice = _result(result); + await rememberPendingSlateReceive(invoice); + _scheduleLocalWalletSync(); + return invoice; } catch (e) { - throw _fail("issueInvoice", e); + _syncAfterSlateError(e); + return SlatepackResult( + success: false, + error: _fail("issueInvoice", e).toString(), + ); } } /// Pays an I1 for exactly [confirmedAmount], the amount the user agreed - /// to, and returns the I2. Locks the inputs. - Future processInvoice( + /// to, and returns the I2. Locks the inputs. The I1 is decoded again and + /// anything but an I1 for that amount is refused before the library is + /// asked to pay; the library checks the amount once more. + @override + Future processInvoice( String i1, { required Amount confirmedAmount, }) async { @@ -1462,27 +1867,50 @@ class GrinWallet extends Bip39Wallet { expectedAmount: expected, ), ); - unawaited(refresh()); - return result; + final payment = _result(result); + await rememberPendingSlateSend(payment); + _scheduleLocalWalletSync(); + return payment; } catch (e) { - throw _fail("processInvoice", e); + _syncAfterSlateError(e); + final failure = _fail("processInvoice", e); + return SlatepackResult( + success: false, + error: failure.toString(), + // Set when the payment stays in the wallet although the call failed. + slateId: + failure is GrinWalletException && failure.leftPendingTransaction + ? failure.slateId + : null, + ); } } /// Finalizes an invoice from its I2 and broadcasts it. - Future finalizeInvoice(String i2) async { + @override + Future finalizeInvoice(String i2) async { try { + _refuseWhileScanning(); final api = await _requireNetwork(); final result = await api.finalizeInvoice(i2); - unawaited(refresh()); - return result; + final finalized = _finalized(result); + await rememberSlateBroadcastStatus(finalized.slateId, finalized.posted); + _scheduleLocalWalletSync(); + return finalized; } catch (e) { - throw _fail("finalizeInvoice", e); + final failure = _finalizeFailure( + "finalizeInvoice", + e, + notFoundMessage: "This is not an invoice issued by this wallet.", + ); + await rememberSlateBroadcastStatus(failure.slateId, failure.posted); + return failure; } } /// Cancels the unconfirmed transaction [slateId]. Returns "" or a message /// to show. + @override Future cancelPendingTransactionAndPost(String slateId) async { try { _refuseWhileScanning(); @@ -1491,18 +1919,24 @@ class GrinWallet extends Bip39Wallet { if (logIds.isEmpty) { await api.cancelTransaction(slateId: slateId); } else { + // A self-send has two entries. One of them may already be + // cancelled or gone; the other is still cancelled. var cancelled = 0; + GrinException? failure; for (final id in logIds) { try { await api.cancelTransaction(txId: id); cancelled++; - } on GrinTransactionException { - // A self-send's other half may already be cancelled. - if (id == logIds.last && cancelled == 0) rethrow; + } on GrinTransactionException catch (e) { + failure ??= e; + } on GrinNotFoundException catch (e) { + failure ??= e; } } + if (cancelled == 0 && failure != null) throw failure; } - unawaited(refresh()); + await rememberPendingSlateCancelled(slateId); + _scheduleLocalWalletSync(); return ""; } catch (e) { return _fail("cancel", e).toString(); @@ -1510,6 +1944,7 @@ class GrinWallet extends Bip39Wallet { } /// The latest Slatepack of [txid], if the wallet kept one. + @override Future pendingSlatepackFor(String txid) async { final cached = _slatepacks[txid]; if (cached != null) return cached; @@ -1526,26 +1961,48 @@ class GrinWallet extends Bip39Wallet { } } + @override + bool get supportsRepost => true; + + @override + Future canRepost(String txid) async { + final tx = await _storedTx(txid); + return tx != null && (slatepackTxInfo(tx)?.canRepost ?? false); + } + /// Broadcasts the stored finalized transaction [txid] again. + @override Future repost(String txid) async { try { final tx = await _storedTx(txid); if (tx == null || !_otherDataFlag(tx, TxV2OdKeys.grinHasStoredTx)) { throw GrinWalletException("No finalized transaction is stored."); } + _refuseWhileScanning(); final api = await _requireNetwork(); final logIds = _logIds(tx); await api.repost( txId: logIds.isEmpty ? null : logIds.first, slateId: tx.slateId, ); - unawaited(refresh()); + await rememberSlateBroadcastStatus(tx.slateId ?? txid, true); + _scheduleLocalWalletSync(); } catch (e) { - throw _fail("repost", e); + throw _fail( + "repost", + e, + message: e is GrinNotFoundException + ? "This transaction is not finalized, or is already confirmed." + : null, + ); } } + @override + bool get supportsPaymentProofs => true; + /// The payment proof of [txid] as JSON. + @override Future exportPaymentProof(String txid) async { try { final tx = await _storedTx(txid); @@ -1559,28 +2016,87 @@ class GrinWallet extends Bip39Wallet { ); return proof.toJsonString(); } catch (e) { - throw _fail("exportPaymentProof", e); + throw _fail( + "exportPaymentProof", + e, + message: e is GrinNotFoundException + ? "The payment proof is not available until the transaction is " + "finalized." + : null, + ); } } /// Checks a payment proof against the chain through the wallet's node. - Future verifyPaymentProof( - String proofJson, - ) async { + @override + Future verifyPaymentProof(String proofJson) async { try { final GrinPaymentProof proof; try { - proof = GrinPaymentProof.fromJsonString(proofJson); + proof = GrinPaymentProof.fromJsonString(proofJson.trim()); } on FormatException { throw GrinWalletException("This is not a Grin payment proof."); } final api = await _requireNetwork(); - return await api.verifyPaymentProof(proof); + final check = await api.verifyPaymentProof(proof); + return PaymentProofCheck( + amount: _amount(proof.amount), + kernelExcess: proof.excess, + senderAddress: proof.senderAddress, + recipientAddress: proof.recipientAddress, + isSender: check.isSender, + isRecipient: check.isRecipient, + ); } catch (e) { - throw _fail("verifyPaymentProof", e); + throw _fail( + "verifyPaymentProof", + e, + message: switch (e) { + GrinTransactionException() => + "The proof did not verify: a signature is wrong or the kernel is " + "not on the chain.", + GrinJsonException() => + "This is not a valid Grin payment proof for this network.", + _ => null, + }, + ); } } + @override + SlatepackTxInfo? slatepackTxInfo(TransactionV2 tx) { + if (!tx.isGrinTransaction) return null; + final data = tx.otherData == null + ? const {} + : _decodeOtherData(tx.otherData!); + final state = SlateState.fromCode( + data[TxV2OdKeys.grinSlateState] as String?, + ); + final stored = data[TxV2OdKeys.grinHasStoredTx] == true; + final open = !tx.isCancelled && !tx.isReverted; + final unconfirmed = tx.height == null || tx.height! <= 0; + final finalized = stored && open && unconfirmed; + return SlatepackTxInfo( + state: state, + slateId: tx.slateId, + kernelExcess: data[TxV2OdKeys.grinKernelExcess] as String?, + counterpartyAddress: data[TxV2OdKeys.counterpartyAddress] as String?, + ttlCutoffHeight: data[TxV2OdKeys.grinTtlCutoff] as int?, + finalizedAwaitingConfirmation: finalized, + broadcastPosted: finalized ? slateBroadcastStatus(tx.slateId) : null, + canRepost: finalized, + canShowSlatepack: + open && + unconfirmed && + !stored && + (state == SlateState.s1 || + state == SlateState.s2 || + state == SlateState.i1 || + state == SlateState.i2), + hasPaymentProof: data[TxV2OdKeys.grinHasPaymentProof] == true, + ); + } + Future _storedTx(String txid) => mainDB.isar.transactionV2s .where() .txidWalletIdEqualTo(txid, walletId) @@ -1589,16 +2105,16 @@ class GrinWallet extends Bip39Wallet { List _logIds(TransactionV2? tx) { final data = tx?.otherData; if (data == null) return const []; - final ids = _decode(data)[TxV2OdKeys.grinLogIds]; + final ids = _decodeOtherData(data)[TxV2OdKeys.grinLogIds]; return ids is List ? ids.whereType().toList() : const []; } bool _otherDataFlag(TransactionV2 tx, String key) { final data = tx.otherData; - return data != null && _decode(data)[key] == true; + return data != null && _decodeOtherData(data)[key] == true; } - Map _decode(String data) { + Map _decodeOtherData(String data) { try { return Map.from(jsonDecode(data) as Map); } catch (_) { diff --git a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart index 0fc40ae1fc..8af5b3df8a 100644 --- a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart +++ b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart @@ -227,6 +227,7 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }) async { try { final handle = await _ensureWalletOpen(); @@ -236,7 +237,7 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { wallet: handle, amount: amount.raw.toInt(), minimumConfirmations: cryptoCurrency.minConfirms, - selectionStrategyIsAll: false, + selectionStrategyIsAll: sendAll, message: message ?? '', ); diff --git a/lib/wallets/wallet/supporting/grin/grin_errors.dart b/lib/wallets/wallet/supporting/grin/grin_errors.dart index 888277a49d..a24d201646 100644 --- a/lib/wallets/wallet/supporting/grin/grin_errors.dart +++ b/lib/wallets/wallet/supporting/grin/grin_errors.dart @@ -8,7 +8,14 @@ import '../../../../exceptions/wallet/insufficient_balance_exception.dart'; /// It carries the library's error type, code and slate id, never the /// library's message: that text can come from a node or a counterparty. class GrinWalletException extends SWException { - GrinWalletException(super.message, {this.type, this.code, this.slateId}); + GrinWalletException( + super.message, { + this.type, + this.code, + this.slateId, + this.finalized = false, + this.released = false, + }); /// The library exception's class name, if a library error caused this. final String? type; @@ -19,10 +26,37 @@ class GrinWalletException extends SWException { /// The slate the failed call was working on, if the library said. final String? slateId; + /// The library finalized and stored the transaction before the call + /// failed. + final bool finalized; + + /// The library cancelled the transaction again before the call returned: + /// nothing is locked and nothing was sent. + final bool released; + /// A finalized transaction whose broadcast failed. Offer repost. - bool get finalizedNotBroadcast => code == 9 && slateId != null; + bool get finalizedNotBroadcast => finalized && slateId != null; + + /// The call failed and left a transaction in the wallet that is neither + /// finalized nor cancelled. Its inputs may be locked. + bool get leftPendingTransaction => slateId != null && !finalized && !released; } +/// Shown for a call that failed after the transaction was finalized. +const grinFinalizedNotBroadcastMessage = + "The transaction was finalized but the node did not accept it. " + "You can try to repost it."; + +/// Shown for a send the library cancelled again after it failed. +const grinReleasedMessage = + "The transaction could not be completed. Nothing was sent and no funds " + "are locked."; + +/// Added to the message of a call that failed and left a transaction behind. +const grinLeftPendingNote = + "The transaction is still in this wallet and may hold funds locked. " + "Open it in the transaction history to cancel it."; + /// The library class and code of [error] for logs, and nothing else. String describeGrinError(Object error) => switch (error) { GrinException() => "${error.runtimeType}(${error.code})", @@ -45,7 +79,7 @@ Exception sanitizeGrinError(Object error) { return GrinWalletException("Grin wallet error (${error.runtimeType})"); } - final message = switch (error) { + final base = switch (error) { GrinInvalidArgumentException() => "The Grin library refused an argument.", GrinInvalidUtf8Exception() => "The Grin library refused an argument.", GrinJsonException() => "The Grin library refused an argument.", @@ -55,11 +89,7 @@ Exception sanitizeGrinError(Object error) { GrinWalletExistsException() => "A Grin wallet already exists here.", GrinInvalidHandleException() => "The Grin wallet is closed.", GrinLifecycleException() => "The Grin wallet could not be opened.", - GrinNodeException() => - error.slateId != null - ? "The transaction was finalized but the node did not accept it. " - "You can try to repost it." - : "Could not reach the Grin node.", + GrinNodeException() => "Could not reach the Grin node.", GrinInsufficientFundsException() => "Insufficient balance.", GrinSlateException() => "The Slatepack could not be read, or is not the one expected.", @@ -78,6 +108,17 @@ Exception sanitizeGrinError(Object error) { GrinInvalidMnemonicException() => "Invalid recovery phrase.", GrinUnknownException() => "Grin wallet error.", }; + final slateId = error.slateId; + final String message; + if (slateId == null) { + message = base; + } else if (error.finalized) { + message = grinFinalizedNotBroadcastMessage; + } else if (error.released) { + message = grinReleasedMessage; + } else { + message = "$base $grinLeftPendingNote"; + } if (error is GrinInsufficientFundsException) { return InsufficientBalanceException(message); @@ -87,6 +128,8 @@ Exception sanitizeGrinError(Object error) { message, type: "${error.runtimeType}", code: error.code, - slateId: error.slateId, + slateId: slateId, + finalized: slateId != null && error.finalized, + released: slateId != null && error.released, ); } diff --git a/lib/wallets/wallet/supporting/grin/grin_scan_pause_observer.dart b/lib/wallets/wallet/supporting/grin/grin_scan_pause_observer.dart new file mode 100644 index 0000000000..dc5692eb75 --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_scan_pause_observer.dart @@ -0,0 +1,58 @@ +import 'package:flutter/widgets.dart'; + +/// Cancels a running Grin scan when the app goes to the background. +/// +/// Modelled on the grin_native example's GrinLifecycleObserver. The scan +/// stops after its current batch and resumes from the stored height on the +/// next refresh. +class GrinScanPauseObserver { + GrinScanPauseObserver({ + required this._cancelScan, + required this._resumeScan, + }) { + _listener = AppLifecycleListener(onStateChange: onStateChange); + final state = WidgetsBinding.instance.lifecycleState; + _paused = + state == AppLifecycleState.paused || + state == AppLifecycleState.detached; + } + + /// Without a listener, for tests. + @visibleForTesting + GrinScanPauseObserver.detached({ + required this._cancelScan, + required this._resumeScan, + }); + + final void Function() _cancelScan; + final void Function() _resumeScan; + AppLifecycleListener? _listener; + bool _paused = false; + + bool get isPaused => _paused; + + @visibleForTesting + void onStateChange(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + final wasPaused = _paused; + _paused = false; + if (wasPaused) _resumeScan(); + return; + } + if (state != AppLifecycleState.paused && + state != AppLifecycleState.detached) { + return; + } + _paused = true; + try { + _cancelScan(); + } on StateError { + // Closed; nothing to cancel. + } catch (_) {} + } + + void dispose() { + _listener?.dispose(); + _listener = null; + } +} diff --git a/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart b/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart index 1160b85c06..0b1f1416a1 100644 --- a/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart +++ b/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart @@ -106,7 +106,9 @@ TransactionV2 _mapGroup({ } final isCoinbase = primary.type == GrinTxType.confirmedCoinbase; - final cancelled = primary.type.isCancelled; + // A self-send is cancelled once both halves are: a half that is not may + // still hold outputs, and the row has to stay cancellable for it. + final cancelled = group.every((e) => e.type.isCancelled); final reverted = group.any((e) => e.type == GrinTxType.txReverted); final confirmed = group.every((e) => e.confirmed) && !cancelled && !reverted; diff --git a/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart b/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart index f00885a2de..d3f98435fd 100644 --- a/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart +++ b/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart @@ -30,7 +30,11 @@ extension GrinWalletInfoExtension on WalletInfo { /// Grin state Stack keeps beside the native wallet. class GrinWalletData { - const GrinWalletData({required this.creationHeight, this.pendingScanFrom}); + const GrinWalletData({ + required this.creationHeight, + this.pendingScanFrom, + this.slatepackTransactions = const {}, + }); /// The height the wallet was created or restored from. final int creationHeight; @@ -38,21 +42,40 @@ class GrinWalletData { /// Where an unfinished scan resumes, or null when none is pending. final int? pendingScanFrom; + /// Small Stack-owned records that must be available before native history + /// is copied into Isar (ownership, cancellation and broadcast status). + final Map slatepackTransactions; + Map toMap() => { "creationHeight": creationHeight, "pendingScanFrom": pendingScanFrom, + "slatepackTransactions": slatepackTransactions, }; factory GrinWalletData.fromMap(Map map) => GrinWalletData( creationHeight: map["creationHeight"] as int, pendingScanFrom: map["pendingScanFrom"] as int?, + slatepackTransactions: Map.from( + map["slatepackTransactions"] as Map? ?? const {}, + ), + ); + + GrinWalletData withPendingScanFrom(int? height) => GrinWalletData( + creationHeight: creationHeight, + pendingScanFrom: height, + slatepackTransactions: slatepackTransactions, ); - GrinWalletData withPendingScanFrom(int? height) => - GrinWalletData(creationHeight: creationHeight, pendingScanFrom: height); + GrinWalletData withSlatepackTransactions(Map metadata) => + GrinWalletData( + creationHeight: creationHeight, + pendingScanFrom: pendingScanFrom, + slatepackTransactions: metadata, + ); @override String toString() => "GrinWalletData(creationHeight: $creationHeight, " - "pendingScanFrom: $pendingScanFrom)"; + "pendingScanFrom: $pendingScanFrom, " + "slatepackTransactions: ${slatepackTransactions.length})"; } diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart index 9f8c7cd59a..c8bcd861f3 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -24,6 +24,12 @@ mixin SlatepackInterface on Wallet { > _pendingSlateTransactions = {}; + // WalletInfo updates replace the persisted Isar object, so a wallet's + // already-open `info` instance may continue to expose the previous value. + // Keep results observed by this process authoritative until the wallet is + // reopened and reads the durable copy. + final Map _observedBroadcastStatuses = {}; + /// Methods the send and receive screens offer. The first is the default. List get supportedMethods; @@ -37,6 +43,10 @@ mixin SlatepackInterface on Wallet { bool get hasSlatepackMethodToggle => supportedMethods.any((method) => method != SlatepackMethod.slatepack); + bool get supportsInvoices => false; + + bool get supportsPaymentProofs => false; + /// "slate" or "slatepack" wording for this coin. SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; @@ -56,7 +66,8 @@ mixin SlatepackInterface on Wallet { (await getCurrentReceivingAddress())?.value ?? ""; /// Decode [armored] without changing wallet state. - Future decodeSlatepack(String armored); + Future decodeSlatepack(String armored) => + throw UnsupportedError("decodeSlatepack"); /// Reject text that is clearly not this coin's slate format before doing /// native work. Epic's JSON slates need no additional framing check. @@ -129,7 +140,7 @@ mixin SlatepackInterface on Wallet { .findAll(), slateId, ); - final pending = pendingSlateSendMatching( + final pending = pendingSlateTransactionMatching( slatepackTransactionMetadata, slateId, fractionDigits: cryptoCurrency.fractionDigits, @@ -154,7 +165,19 @@ mixin SlatepackInterface on Wallet { /// Persists ownership as soon as an S1 is created, before a refresh can /// copy the native transaction into Isar. @protected - Future rememberPendingSlateSend(SlatepackResult result) async { + Future rememberPendingSlateSend(SlatepackResult result) => + _rememberPendingSlateTransaction(result, isSend: true); + + /// Records an S2 or issued I1 immediately, before native history is copied + /// into Isar. These are receives from this wallet's point of view. + @protected + Future rememberPendingSlateReceive(SlatepackResult result) => + _rememberPendingSlateTransaction(result, isSend: false); + + Future _rememberPendingSlateTransaction( + SlatepackResult result, { + required bool isSend, + }) async { final slateId = result.slateId; final amount = result.amount; final fee = result.fee; @@ -165,7 +188,7 @@ mixin SlatepackInterface on Wallet { _pendingSlateTransactions[slateId] = ( amount: amount, fee: fee, - isSend: true, + isSend: isSend, isCancelled: false, ); @@ -177,7 +200,7 @@ mixin SlatepackInterface on Wallet { entry.addAll({ 'amount': amount.raw.toString(), 'fee': fee.raw.toString(), - 'isSend': true, + 'isSend': isSend, 'isCancelled': false, }); metadata[slateId] = entry; @@ -232,6 +255,47 @@ mixin SlatepackInterface on Wallet { } } + /// Persists the result of a finalize/repost broadcast without refreshing + /// native history. This lets details offer Cancel after a known rejection + /// without offering it after a successful or unknown broadcast. + @protected + Future rememberSlateBroadcastStatus( + String? slateId, + bool? posted, + ) async { + if (slateId == null || slateId.isEmpty || posted == null) return; + + _observedBroadcastStatuses[slateId] = posted; + + final metadata = Map.from(slatepackTransactionMetadata); + final raw = metadata[slateId]; + final entry = raw is Map + ? Map.from(raw) + : {}; + entry['broadcastPosted'] = posted; + metadata[slateId] = entry; + try { + await updateSlatepackTransactionMetadata(metadata); + } catch (e, s) { + Logging.instance.w( + "Could not persist broadcast status for slate $slateId", + error: e, + stackTrace: s, + ); + } + } + + @protected + bool? slateBroadcastStatus(String? slateId) { + if (slateId == null || slateId.isEmpty) return null; + final observed = _observedBroadcastStatuses[slateId]; + if (observed != null) return observed; + final raw = slatepackTransactionMetadata[slateId]; + return raw is Map && raw['broadcastPosted'] is bool + ? raw['broadcastPosted'] as bool + : null; + } + /// State, id, amount and fee for a native slate JSON result. @protected SlateInspection? inspectSlateJsonString(String? slateJson) { @@ -256,6 +320,7 @@ mixin SlatepackInterface on Wallet { required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }); /// Answer an S1 with an S2. @@ -272,6 +337,67 @@ mixin SlatepackInterface on Wallet { /// Returns an empty String on success, error message on failure. Future cancelPendingTransactionAndPost(String slateId); + + /// The stored S1 or I1 for an unfinished transaction, to show again. + Future pendingSlatepackFor(String txid) async => null; + + bool get supportsRepost => false; + + Future repost(String txid) => throw UnsupportedError("repost"); + + /// Whether [txid] is finalized, stored and unconfirmed, so it can be + /// posted again. + Future canRepost(String txid) async => false; + + Future issueInvoice({ + required Amount amount, + String? payerAddress, + }) => throw UnsupportedError("invoices"); + + Future processInvoice( + String i1, { + required Amount confirmedAmount, + }) => throw UnsupportedError("invoices"); + + Future finalizeInvoice(String i2) => + throw UnsupportedError("invoices"); + + Future exportPaymentProof(String txid) => + throw UnsupportedError("proofs"); + + /// Checks a payment proof (JSON) through the wallet's node. + Future verifyPaymentProof(String proofJson) => + throw UnsupportedError("proofs"); + + /// A slatepack send can name a recipient address to encrypt to. + bool get supportsSlatepackRecipient => false; + + /// Returns the manual-slate recipient represented by a direct-send address. + /// + /// Most wallets keep their manual and direct transports disjoint. Grin + /// addresses are also Slatepack encryption recipients, though, so entering + /// one on the Address tab must use the same no-estimate, no-confirmation + /// manual flow as the Slatepack tab. + String? manualSlatepackRecipientForAddress(String address) => null; + + /// Hint for the address field of a direct send, if the coin wants one. + String? get directSendAddressHint => null; + + /// The receive QR code holds the bare address instead of a URI. + bool get receiveQrIsRawAddress => false; + + /// Shown under the receive address. + String? get receiveAddressNote => null; + + /// Funds held by unfinished transactions, when the coin reports them. + Amount? get amountLocked => null; + + /// What has to be asked or refused before a direct send to [address]. + SlatepackHttpPolicy httpSendPolicy(String address) => + const SlatepackHttpPolicy(); + + /// Slatepack details of [tx], or null when there are none to show. + SlatepackTxInfo? slatepackTxInfo(TransactionV2 tx) => null; } /// Key in [TxData.otherData] that records the selected slatepack transport. @@ -308,16 +434,17 @@ extension SlatepackTxData on TxData { bool get isSlatepackSend => slatepackMethod == SlatepackMethod.slatepack; } -/// Reads the small durable record written when a wallet creates an S1. +/// Reads the small durable record written when a wallet creates or answers a +/// Slatepack before native history reaches Isar. @visibleForTesting ({Amount amount, Amount fee, bool isSend, bool isCancelled})? -pendingSlateSendMatching( +pendingSlateTransactionMatching( Map metadata, String slateId, { required int fractionDigits, }) { final raw = metadata[slateId]; - if (raw is! Map || raw['isSend'] != true) return null; + if (raw is! Map || raw['isSend'] is! bool) return null; final amount = BigInt.tryParse(raw['amount']?.toString() ?? ''); final fee = BigInt.tryParse(raw['fee']?.toString() ?? ''); @@ -326,11 +453,27 @@ pendingSlateSendMatching( return ( amount: Amount(rawValue: amount, fractionDigits: fractionDigits), fee: Amount(rawValue: fee, fractionDigits: fractionDigits), - isSend: true, + isSend: raw['isSend'] as bool, isCancelled: raw['isCancelled'] == true, ); } +/// Backwards-compatible send-only view used by cancellation handling. +@visibleForTesting +({Amount amount, Amount fee, bool isSend, bool isCancelled})? +pendingSlateSendMatching( + Map metadata, + String slateId, { + required int fractionDigits, +}) { + final pending = pendingSlateTransactionMatching( + metadata, + slateId, + fractionDigits: fractionDigits, + ); + return pending?.isSend == true ? pending : null; +} + /// Inspect Epic/MWC slate JSON without invoking either native wallet. @visibleForTesting SlateInspection inspectSlateJson( diff --git a/lib/widgets/choose_coin_view.dart b/lib/widgets/choose_coin_view.dart index b44f7152a1..ba3cf45e70 100644 --- a/lib/widgets/choose_coin_view.dart +++ b/lib/widgets/choose_coin_view.dart @@ -13,10 +13,13 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; + import '../providers/providers.dart'; import '../app_config.dart'; +import '../pages/settings_views/global_settings_view/advanced_views/manage_explorer_view.dart'; import '../themes/coin_icon_provider.dart'; import '../themes/stack_colors.dart'; +import '../utilities/block_explorers.dart'; import '../utilities/constants.dart'; import '../utilities/text_styles.dart'; import '../wallets/crypto_currency/crypto_currency.dart'; @@ -59,6 +62,9 @@ class _ChooseCoinViewState extends ConsumerState { _coins.removeWhere( (e) => e.identifier == Firo(CryptoCurrencyNetwork.test).identifier, ); + if (widget.nextRouteName == ManageExplorerView.routeName) { + _coins.removeWhere((e) => !hasDefaultBlockExplorer(e)); + } super.initState(); } @@ -75,11 +81,7 @@ class _ChooseCoinViewState extends ConsumerState { final List coins = showTestNet ? _coins - : _coins - .where( - (e) => e.network == CryptoCurrencyNetwork.main, - ) - .toList(); + : _coins.where((e) => e.network == CryptoCurrencyNetwork.main).toList(); return Background( child: Scaffold( @@ -90,73 +92,57 @@ class _ChooseCoinViewState extends ConsumerState { Navigator.of(context).pop(); }, ), - title: Text( - widget.title, - style: STextStyles.navBarTitle(context), - ), + title: Text(widget.title, style: STextStyles.navBarTitle(context)), ), body: Padding( - padding: const EdgeInsets.only( - top: 12, - left: 12, - right: 12, - ), + padding: const EdgeInsets.only(top: 12, left: 12, right: 12), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - ...coins.map( - (coin) { - return Padding( - padding: const EdgeInsets.all(4), - child: RoundedWhiteContainer( - padding: const EdgeInsets.all(0), - child: RawMaterialButton( - // splashColor: Theme.of(context).extension()!.highlight, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), + ...coins.map((coin) { + return Padding( + padding: const EdgeInsets.all(4), + child: RoundedWhiteContainer( + padding: const EdgeInsets.all(0), + child: RawMaterialButton( + // splashColor: Theme.of(context).extension()!.highlight, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + Constants.size.circularBorderRadius, ), - materialTapTargetSize: - MaterialTapTargetSize.shrinkWrap, - onPressed: () { - Navigator.of(context).pushNamed( - widget.nextRouteName, - arguments: coin, - ); - }, - child: Padding( - padding: const EdgeInsets.all(12), - child: Row( - children: [ - SvgPicture.file( - File( - ref.watch(coinIconProvider(coin)), + ), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + onPressed: () { + Navigator.of(context) + .pushNamed(widget.nextRouteName, arguments: coin); + }, + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + SvgPicture.file( + File(ref.watch(coinIconProvider(coin))), + width: 24, + height: 24, + ), + const SizedBox(width: 12), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "${coin.prettyName} ${widget.coinAdditional}", + style: STextStyles.titleBold12(context), ), - width: 24, - height: 24, - ), - const SizedBox( - width: 12, - ), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "${coin.prettyName} ${widget.coinAdditional}", - style: STextStyles.titleBold12(context), - ), - ], - ), - ], - ), + ], + ), + ], ), ), ), - ); - }, - ), + ), + ); + }), ], ), ), diff --git a/test/address_utils_test.dart b/test/address_utils_test.dart index af615c5b56..0b8039ffb3 100644 --- a/test/address_utils_test.dart +++ b/test/address_utils_test.dart @@ -124,6 +124,12 @@ void main() { expect(result, isNull); }); + test("raw wallet addresses are not payment URIs", () { + const grinAddress = + "grin1l4wxczk3u50mc82cef6xc22c272ndrkxwfawff6tjzpvm2g70lgq3mnw3d"; + expect(AddressUtils.parsePaymentUri(grinAddress), isNull); + }); + test("parse an invalid uri string", () { const uri = "::: 8 \\ %23"; expect(AddressUtils.parsePaymentUri(uri), isNull); @@ -229,7 +235,7 @@ void main() { const jsonString = '{"mnemonic":"hello","word","something","who","green","seven"]}'; - expect(AddressUtils.decodeQRSeedData(jsonString), {}); + expect(AddressUtils.decodeQRSeedData(jsonString), {}); }); test("build a uri string with empty params", () { @@ -454,4 +460,23 @@ void main() { ); }); }); + + test("web URLs are send addresses, not payment URIs", () { + for (final input in [ + "http:", + "http://", + "http://127.0.0.1:3415", + "https://wallet.example.com/v2/foreign", + "HTTPS://wallet.example.com", + ]) { + expect(AddressUtils.parsePaymentUri(input), isNull, reason: input); + } + // Ordinary payment URIs still parse. + expect( + AddressUtils.parsePaymentUri( + "bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa?amount=0.1", + )?.address, + "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", + ); + }); } diff --git a/test/pages/send_view/grin_confirmation_test.dart b/test/pages/send_view/grin_confirmation_test.dart new file mode 100644 index 0000000000..8e14d58087 --- /dev/null +++ b/test/pages/send_view/grin_confirmation_test.dart @@ -0,0 +1,302 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/transaction_note.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/send_view/confirm_transaction_view.dart'; +import 'package:stackwallet/pages/send_view/sub_widgets/sending_transaction_dialog.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/grin_fakes.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +/// A Grin test wallet that does not refresh, so a send can run inside a +/// widget test. +class _QuietWallet extends GrinTestWallet { + _QuietWallet(GrinHarness h) + : super( + testWalletId: h.walletId, + backend: h.backend, + tor: h.tor, + bus: h.bus, + secrets: h.secrets, + testPrefs: h.prefs, + ); + + final reposted = []; + + @override + Future refresh() async {} + + @override + Future repost(String txid) async => reposted.add(txid); +} + +class _Notes extends Fake implements MainDB { + final notes = []; + @override + Future putTransactionNote(TransactionNote note) async => + notes.add(note); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + TxData direct(String address) => TxData( + recipients: [ + TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(1000000000), fractionDigits: 9), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + fee: Amount(rawValue: BigInt.from(23500000), fractionDigits: 9), + otherData: slatepackMethodOtherData(SlatepackMethod.http), + ); + + Future pumpConfirm( + WidgetTester tester, + TxData txData, { + GrinTestWallet? sender, + MainDB? db, + VoidCallback? onSuccess, + Size size = const Size(1400, 2400), + bool mobile = false, + }) async { + final oldPlatform = Util.layoutPlatform; + if (mobile) { + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + } + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(() => Util.layoutPlatform = oldPlatform); + final previousThemesDir = StackFileSystem.themesDir; + addTearDown(() => StackFileSystem.themesDir = previousThemesDir); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + + final wallet = sender ?? h.wallet; + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + if (db != null) mainDBProvider.overrideWithValue(db), + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletCoin(h.walletId).overrideWithValue(coin), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: 9, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: ConfirmTransactionView( + txData: txData, + walletId: h.walletId, + onSuccess: onSuccess ?? () {}, + onSuccessInsteadOfRouteOnSuccess: () {}, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + bool sendEnabled(WidgetTester tester) => tester + .widget(find.widgetWithText(PrimaryButton, 'Send')) + .enabled; + + testWidgets('clearnet https with Tor off needs the IP warning', ( + tester, + ) async { + await pumpConfirm(tester, direct('https://payee.example')); + expect(find.byKey(const Key('slatepackClearnetAck')), findsOneWidget); + expect(find.byKey(const Key('slatepackPlaintextAck')), findsNothing); + expect(sendEnabled(tester), isFalse); + await tester.ensureVisible(find.byKey(const Key('slatepackClearnetAck'))); + await tester.tap(find.byKey(const Key('slatepackClearnetAck'))); + await tester.pumpAndSettle(); + expect(sendEnabled(tester), isTrue); + }); + + testWidgets('plain http with Tor off needs both warnings', (tester) async { + await pumpConfirm(tester, direct('http://payee.example')); + await tester.ensureVisible(find.byKey(const Key('slatepackClearnetAck'))); + await tester.tap(find.byKey(const Key('slatepackClearnetAck'))); + await tester.pumpAndSettle(); + expect(sendEnabled(tester), isFalse); + await tester.ensureVisible(find.byKey(const Key('slatepackPlaintextAck'))); + await tester.tap(find.byKey(const Key('slatepackPlaintextAck'))); + await tester.pumpAndSettle(); + expect(sendEnabled(tester), isTrue); + }); + + testWidgets('plain http over Tor still warns', (tester) async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + await pumpConfirm(tester, direct('http://payee.example')); + expect(find.byKey(const Key('slatepackClearnetAck')), findsNothing); + expect(find.byKey(const Key('slatepackPlaintextAck')), findsOneWidget); + expect(sendEnabled(tester), isFalse); + }); + + testWidgets('transport warnings fit a 320px mobile screen', (tester) async { + await pumpConfirm( + tester, + direct('http://payee.example'), + size: const Size(320, 640), + mobile: true, + ); + expect(tester.takeException(), isNull); + for (final key in const [ + Key('slatepackClearnetAck'), + Key('slatepackPlaintextAck'), + ]) { + await tester.ensureVisible(find.byKey(key)); + await tester.tap(find.byKey(key)); + await tester.pumpAndSettle(); + } + await tester.ensureVisible(find.text('Send')); + expect(sendEnabled(tester), isTrue); + expect(tester.takeException(), isNull); + }); + + testWidgets('a grin1 target without Tor is blocked', (tester) async { + await pumpConfirm(tester, direct('grin1payee')); + expect(find.textContaining('needs Tor'), findsOneWidget); + expect(find.byType(Checkbox), findsNothing); + expect(sendEnabled(tester), isFalse); + }); + + testWidgets('Tor wanted but down blocks everything', (tester) async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + await pumpConfirm(tester, direct('https://payee.example')); + expect(find.textContaining('Tor is not connected'), findsOneWidget); + expect(sendEnabled(tester), isFalse); + }); + + testWidgets('a direct send the node did not take ends the send and offers ' + 'repost', (tester) async { + final wallet = _QuietWallet(h); + await tester.runAsync(wallet.init); + addTearDown(() async { + try { + await wallet.exit(); + } catch (_) {} + }); + h.backend.api.sendError = grinError( + 9, + details: {'slate_id': 'slate-f', 'finalized': true}, + ); + final notes = _Notes(); + var succeeded = false; + await pumpConfirm( + tester, + direct('https://payee.example').copyWith(note: 'for lunch'), + sender: wallet, + db: notes, + onSuccess: () => succeeded = true, + ); + await tester.ensureVisible(find.byKey(const Key('slatepackClearnetAck'))); + await tester.tap(find.byKey(const Key('slatepackClearnetAck'))); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('Send')); + await tester.tap(find.text('Send')); + await tester.pumpAndSettle(); + Navigator.of(tester.element(find.byType(DesktopAuthSend))).pop(true); + for (var i = 0; i < 40; i++) { + await tester.pump(const Duration(milliseconds: 250)); + if (h.backend.api.calls.contains('sendHttp') && + find.byType(SendingTransactionDialog).evaluate().isEmpty) { + break; + } + } + + expect(h.backend.api.calls, contains('sendHttp')); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(find.text('Broadcast transaction failed'), findsNothing); + expect(find.text('Finalized, not broadcast'), findsOneWidget); + expect(succeeded, isFalse); + expect(notes.notes.single.txid, 'slate-f'); + expect(notes.notes.single.value, 'for lunch'); + + await tester.tap(find.text('Later')); + await tester.pumpAndSettle(); + expect(wallet.reposted, isEmpty); + expect(succeeded, isTrue); + expect(tester.takeException(), isNull); + }); + + testWidgets('the confirm screen never offers manual slate creation', ( + tester, + ) async { + await pumpConfirm( + tester, + direct('').copyWith( + otherData: slatepackMethodOtherData(SlatepackMethod.slatepack), + ), + ); + expect(find.byType(Checkbox), findsNothing); + expect( + find.widgetWithText(PrimaryButton, 'Create slatepack'), + findsNothing, + ); + expect(find.widgetWithText(PrimaryButton, 'Send'), findsOneWidget); + }); +} diff --git a/test/pages/send_view/grin_send_form_test.dart b/test/pages/send_view/grin_send_form_test.dart new file mode 100644 index 0000000000..93716120d9 --- /dev/null +++ b/test/pages/send_view/grin_send_form_test.dart @@ -0,0 +1,243 @@ +import 'dart:io'; + +import 'package:decimal/decimal.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/balance.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/send_view/send_view.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart'; +import 'package:stackwallet/providers/global/locale_provider.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/price_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; +import 'package:stackwallet/services/locale_service.dart'; +import 'package:stackwallet/services/price_service.dart'; +import 'package:stackwallet/themes/coin_icon_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/grin_fakes.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +class _Locale extends LocaleService { + @override + String get locale => 'en_US'; +} + +class _Prefs extends ConfirmationPrefs { + @override + bool get enableCoinControl => false; + @override + bool get externalCalls => true; + @override + AmountUnit amountUnit(CryptoCurrency coin) => AmountUnit.normal; + @override + int maxDecimals(CryptoCurrency coin) => coin.fractionDigits; +} + +class _Price extends PriceService { + _Price() : super('USD'); + @override + ({Decimal value, double change24h})? getPrice(CryptoCurrency coin) => + (value: Decimal.one, change24h: 0); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Future mount(WidgetTester tester, {required bool desktop}) async { + final oldPlatform = Util.layoutPlatform; + final oldThemes = StackFileSystem.themesDir; + Util.layoutPlatform = platform.FakePlatform( + operatingSystem: desktop ? 'linux' : 'android', + ); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + tester.view.physicalSize = const Size(1200, 1800); + tester.view.devicePixelRatio = 1; + addTearDown(() { + Util.layoutPlatform = oldPlatform; + StackFileSystem.themesDir = oldThemes; + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + final wallet = h.wallet; + final walletId = h.walletId; + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final amount = Amount( + rawValue: BigInt.from(1000000000), + fractionDigits: coin.fractionDigits, + ); + final zero = Amount.zeroWith(fractionDigits: coin.fractionDigits); + final child = desktop + ? DesktopSend(walletId: walletId) + : SendView(walletId: walletId, coin: coin); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletInfo(walletId).overrideWithValue(wallet.info), + pWalletCoin(walletId).overrideWithValue(coin), + pWalletName(walletId).overrideWithValue(wallet.info.name), + pWalletBalance(walletId).overrideWithValue( + Balance( + total: amount, + spendable: amount, + blockedTotal: zero, + pendingSpendable: zero, + ), + ), + prefsChangeNotifierProvider.overrideWithValue(_Prefs()), + localeServiceChangeNotifierProvider.overrideWithValue(_Locale()), + priceAnd24hChangeNotifierProvider.overrideWithValue(_Price()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + coinIconProvider(coin).overrideWithValue( + File('test/sample_data/light/assets/dummy.svg').absolute.path, + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: desktop + ? Scaffold(body: SingleChildScrollView(child: child)) + : child, + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + addTearDown(() async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }); + } + + for (final desktop in [true, false]) { + testWidgets('manual Slatepack creation does not promise a fee review, ' + 'desktop=$desktop', (tester) async { + await mount(tester, desktop: desktop); + + expect(find.textContaining('Transaction fee'), findsNothing); + expect(find.text('Calculated when reviewing'), findsNothing); + }); + + testWidgets('clearing the send form clears the Slatepack recipient, ' + 'desktop=$desktop', (tester) async { + await mount(tester, desktop: desktop); + final field = find.byKey(const Key('slatepackRecipientFieldKey')); + await tester.ensureVisible(field); + await tester.enterText(field, 'grin1previousrecipient'); + await tester.pump(); + + // What a finished send calls. + final form = tester.state(find.byType(desktop ? DesktopSend : SendView)); + // ignore: avoid_dynamic_calls + (form as dynamic).clearSendForm(); + await tester.pumpAndSettle(); + + expect( + tester.widget(field).controller!.text, + isEmpty, + reason: 'the next Slatepack would be encrypted to the last recipient', + ); + }); + + testWidgets('editing a receiver address keeps the cursor in place, ' + 'desktop=$desktop', (tester) async { + await mount(tester, desktop: desktop); + final form = find.byType(desktop ? DesktopSend : SendView); + ProviderScope.containerOf(tester.element(form)) + .read(pSelectedSlatepackMethod(h.walletId).notifier) + .state = + SlatepackMethod.http; + await tester.pumpAndSettle(); + final field = find.byKey(const Key('sendViewAddressFieldKey')); + await tester.ensureVisible(field); + await tester.showKeyboard(field); + + Future type(String text, int cursor) async { + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: cursor), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + await type('https://receiver.example:3415', 29); + // Then an insertion in the middle of it. + const edited = 'https://my-receiver.example:3415'; + await type(edited, 'https://my-'.length); + + final controller = tester.widget(field).controller!; + expect(controller.text, edited); + expect( + controller.selection, + const TextSelection.collapsed(offset: 'https://my-'.length), + ); + }); + + testWidgets('a Grin address on the Address tab creates a Slatepack, ' + 'desktop=$desktop', (tester) async { + await mount(tester, desktop: desktop); + final form = find.byType(desktop ? DesktopSend : SendView); + ProviderScope.containerOf(tester.element(form)) + .read(pSelectedSlatepackMethod(h.walletId).notifier) + .state = + SlatepackMethod.http; + await tester.pumpAndSettle(); + + await tester.enterText( + find.byKey(const Key('sendViewAddressFieldKey')), + 'grin1recipient', + ); + await tester.enterText( + find.byKey(const Key('amountInputFieldCryptoTextFieldKey')), + '0.1', + ); + await tester.pumpAndSettle(); + + expect(find.text('Create slatepack'), findsOneWidget); + expect(find.textContaining('Transaction fee'), findsNothing); + expect(find.text('Calculated when reviewing'), findsNothing); + expect( + h.wallet.manualSlatepackRecipientForAddress('grin1recipient'), + 'grin1recipient', + ); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/test/pages/send_view/send_views_test.dart b/test/pages/send_view/send_views_test.dart index eecb3bf632..da64ea72fd 100644 --- a/test/pages/send_view/send_views_test.dart +++ b/test/pages/send_view/send_views_test.dart @@ -950,6 +950,85 @@ void main() { } } + for (final view in coinCases) { + testWithoutAnimation( + "a recipient-capable manual slate still bypasses fee confirmation " + "and PIN ($view)", + (tester) async { + final wallet = FakeRecipientSlateWallet(); + await view.pump( + tester, + wallet: wallet, + balance: testBalance("10", 8), + overrides: [ + pSelectedSlatepackMethod(wallet.walletId).overrideWithProvider( + StateProvider( + (_) => SlatepackMethod.slatepack, + ), + ), + ], + ); + await enterAmount(tester, view, "1"); + await enterField( + tester, + const Key("slatepackRecipientFieldKey"), + "grin1recipient", + ); + + await view.preview(tester, label: "Create slate"); + + expect(wallet.slateCreates, 1); + expect(wallet.requestedSlateRecipient, "grin1recipient"); + expect(wallet.prepared, isNull); + expect(wallet.feeEstimates, 0); + expect(find.byType(ConfirmTransactionView), findsNothing); + expect(find.byType(DesktopAuthSend), findsNothing); + expect(find.byType(SlatepackDialog), findsOneWidget); + }, + ); + + testWithoutAnimation( + "a manual-slate address entered on the Address tab uses the same " + "direct flow ($view)", + (tester) async { + final wallet = FakeRecipientSlateWallet(); + await view.pump( + tester, + wallet: wallet, + balance: testBalance("10", 8), + overrides: [ + pSelectedSlatepackMethod(wallet.walletId).overrideWithProvider( + StateProvider((_) => SlatepackMethod.relay), + ), + ], + ); + await enterField( + tester, + view.addressField, + "https://manual-slate.example", + ); + await enterAmount(tester, view, "1"); + + expect(find.text("Create slate"), findsOneWidget); + expect(find.textContaining("Transaction fee"), findsNothing); + expect(find.text("Calculated when reviewing"), findsNothing); + + await view.preview(tester, label: "Create slate"); + + expect(wallet.slateCreates, 1); + expect( + wallet.requestedSlateRecipient, + "https://manual-slate.example", + ); + expect(wallet.prepared, isNull); + expect(wallet.feeEstimates, 0); + expect(find.byType(ConfirmTransactionView), findsNothing); + expect(find.byType(DesktopAuthSend), findsNothing); + expect(find.byType(SlatepackDialog), findsOneWidget); + }, + ); + } + for (final (coin, wallet) in <(String, Wallet Function())>[ ("Epic Cash", FakeEpiccashWallet.new), ("Xelis", FakeXelisWallet.new), diff --git a/test/pages/send_view/slatepack_transport_warnings_test.dart b/test/pages/send_view/slatepack_transport_warnings_test.dart new file mode 100644 index 0000000000..2b2a229960 --- /dev/null +++ b/test/pages/send_view/slatepack_transport_warnings_test.dart @@ -0,0 +1,113 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/send_view/sub_widgets/slatepack_transport_warnings.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; + +import '../../sample_data/theme_json.dart'; + +void main() { + group('allows', () { + test('no policy: not a direct send', () { + expect( + SlatepackTransportWarnings.allows( + null, + clearnetAck: false, + plaintextAck: false, + ), + isTrue, + ); + }); + + test('blocked never allows', () { + const policy = SlatepackHttpPolicy(blockedReason: 'Tor is down.'); + expect( + SlatepackTransportWarnings.allows( + policy, + clearnetAck: true, + plaintextAck: true, + ), + isFalse, + ); + }); + + test('each warning needs its own tick', () { + const policy = SlatepackHttpPolicy( + needsClearnetAck: true, + needsPlaintextAck: true, + ); + bool allows(bool c, bool p) => SlatepackTransportWarnings.allows( + policy, + clearnetAck: c, + plaintextAck: p, + ); + expect(allows(false, false), isFalse); + expect(allows(true, false), isFalse); + expect(allows(false, true), isFalse); + expect(allows(true, true), isTrue); + }); + }); + + group('widget', () { + Future<({List clearnet, List plaintext})> pump( + WidgetTester tester, + SlatepackHttpPolicy policy, + ) async { + final clearnet = []; + final plaintext = []; + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + extensions: [ + StackColors.fromStackColorTheme( + StackTheme.fromJson(json: lightThemeJsonMap), + ), + ], + ), + home: Scaffold( + body: SlatepackTransportWarnings( + policy: policy, + onClearnetAck: clearnet.add, + onPlaintextAck: plaintext.add, + ), + ), + ), + ); + return (clearnet: clearnet, plaintext: plaintext); + } + + testWidgets('blocked shows the reason and no ticks', (tester) async { + await pump( + tester, + const SlatepackHttpPolicy(blockedReason: 'Tor is not connected.'), + ); + expect(find.textContaining('Tor is not connected.'), findsOneWidget); + expect(find.byType(Checkbox), findsNothing); + }); + + testWidgets('clearnet warning reports its tick', (tester) async { + final ticks = await pump( + tester, + const SlatepackHttpPolicy(needsClearnetAck: true), + ); + expect(find.textContaining('IP address'), findsWidgets); + expect(find.byKey(const Key('slatepackPlaintextAck')), findsNothing); + await tester.tap(find.byKey(const Key('slatepackClearnetAck'))); + await tester.pump(); + expect(ticks.clearnet, [true]); + expect(ticks.plaintext, isEmpty); + }); + + testWidgets('plain http warning shows even over Tor', (tester) async { + final ticks = await pump( + tester, + const SlatepackHttpPolicy(needsPlaintextAck: true), + ); + expect(find.byKey(const Key('slatepackClearnetAck')), findsNothing); + await tester.tap(find.byKey(const Key('slatepackPlaintextAck'))); + await tester.pump(); + expect(ticks.plaintext, [true]); + }); + }); +} diff --git a/test/pages/send_view/support/fake_wallets.dart b/test/pages/send_view/support/fake_wallets.dart index 00afa64b4a..dbb80d458c 100644 --- a/test/pages/send_view/support/fake_wallets.dart +++ b/test/pages/send_view/support/fake_wallets.dart @@ -286,14 +286,17 @@ class FakeEpiccashWallet extends FakeWallet FakeEpiccashWallet() : super(Epiccash(CryptoCurrencyNetwork.main), testFees); int slateCreates = 0; + String? requestedSlateRecipient; @override Future createSlatepack({ required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }) async { slateCreates++; + requestedSlateRecipient = recipientAddress; return SlatepackResult( success: true, slatepack: '{"id":"test-slate","amount":"${amount.raw}"}', @@ -317,13 +320,31 @@ class FakeEpiccashWallet extends FakeWallet @override bool get supportsSlatepackEncryption => false; + @override + bool get supportsSlatepackRecipient => false; + + @override + String? manualSlatepackRecipientForAddress(String address) => null; + @override bool get supportsOnChainNote => true; + @override + String? get directSendAddressHint => null; + @override SlatepackTerms get slatepackTerms => SlatepackTerms.slate; } +class FakeRecipientSlateWallet extends FakeEpiccashWallet { + @override + bool get supportsSlatepackRecipient => true; + + @override + String? manualSlatepackRecipientForAddress(String address) => + address == 'https://manual-slate.example' ? address : null; +} + class FakeMimblewimblecoinWallet extends FakeWallet implements MimblewimblecoinWallet { FakeMimblewimblecoinWallet() @@ -336,6 +357,7 @@ class FakeMimblewimblecoinWallet extends FakeWallet required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }) async { slateCreates++; return SlatepackResult( @@ -361,6 +383,12 @@ class FakeMimblewimblecoinWallet extends FakeWallet @override bool get supportsSlatepackEncryption => true; + @override + bool get supportsSlatepackRecipient => false; + + @override + String? manualSlatepackRecipientForAddress(String address) => null; + @override bool get supportsOnChainNote => true; diff --git a/test/pages/settings_views/block_explorer_coins_test.dart b/test/pages/settings_views/block_explorer_coins_test.dart new file mode 100644 index 0000000000..2b3f37578e --- /dev/null +++ b/test/pages/settings_views/block_explorer_coins_test.dart @@ -0,0 +1,104 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/app_config.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/settings_views/global_settings_view/advanced_views/manage_explorer_view.dart'; +import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/themes/coin_icon_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/block_explorers.dart'; +import 'package:stackwallet/utilities/prefs.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/widgets/choose_coin_view.dart'; + +import '../../sample_data/theme_json.dart'; + +class _TestPrefs extends ChangeNotifier implements Prefs { + @override + bool get showTestNetCoins => false; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + final epic = Epiccash(CryptoCurrencyNetwork.main); + final mwc = Mimblewimblecoin(CryptoCurrencyNetwork.main); + final bitcoin = Bitcoin(CryptoCurrencyNetwork.main); + + Future pump(WidgetTester tester, Widget home) async { + tester.view.physicalSize = const Size(1200, 6000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemesDir = StackFileSystem.themesDir; + addTearDown(() => StackFileSystem.themesDir = previousThemesDir); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final icon = File('test/sample_data/light/assets/dummy.svg').absolute.path; + await tester.pumpWidget( + ProviderScope( + overrides: [ + prefsChangeNotifierProvider.overrideWithValue(_TestPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + coinIconProvider.overrideWithProvider((_) => Provider((_) => icon)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: home, + ), + ), + ); + await tester.pump(); + expect(tester.takeException(), isNull); + } + + test('Epic Cash and MWC have no default block explorer', () { + expect(hasDefaultBlockExplorer(epic), isFalse); + expect(hasDefaultBlockExplorer(mwc), isFalse); + expect(hasDefaultBlockExplorer(bitcoin), isTrue); + }); + + test('the app offers Epic Cash, MWC and Bitcoin', () { + expect(AppConfig.coins, containsAll([epic, mwc, bitcoin])); + }); + + testWidgets('the mobile explorer list leaves out coins without an explorer', ( + tester, + ) async { + await pump( + tester, + const ChooseCoinView( + title: 'Manage block explorers', + coinAdditional: 'block explorer', + nextRouteName: ManageExplorerView.routeName, + ), + ); + + expect(find.text('${bitcoin.prettyName} block explorer'), findsOneWidget); + expect(find.text('${epic.prettyName} block explorer'), findsNothing); + expect(find.text('${mwc.prettyName} block explorer'), findsNothing); + }); + + testWidgets( + 'the desktop explorer list leaves out coins without an explorer', + (tester) async { + await pump( + tester, + const Scaffold(body: DesktopManageBlockExplorersDialog()), + ); + + expect(find.text('${bitcoin.prettyName} block explorer'), findsOneWidget); + expect(find.text('${epic.prettyName} block explorer'), findsNothing); + expect(find.text('${mwc.prettyName} block explorer'), findsNothing); + }, + ); +} diff --git a/test/pages/slatepack/grin_repost_details_test.dart b/test/pages/slatepack/grin_repost_details_test.dart new file mode 100644 index 0000000000..281b7c38d5 --- /dev/null +++ b/test/pages/slatepack/grin_repost_details_test.dart @@ -0,0 +1,162 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/input_v2.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/output_v2.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/providers/wallet/transaction_note_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +class _RepostDetailsWallet extends Fake implements GrinWallet { + @override + final cryptoCurrency = Grin(CryptoCurrencyNetwork.main); + + @override + String get walletId => 'grin-repost-details'; + + final reposted = []; + bool broadcastPosted = false; + + @override + bool get supportsOnChainNote => false; + + @override + bool get supportsPaymentProofs => false; + + @override + bool get supportsRepost => true; + + @override + SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; + + @override + Future repost(String txid) async { + reposted.add(txid); + broadcastPosted = true; + } + + @override + SlatepackTxInfo? slatepackTxInfo(TransactionV2 tx) => SlatepackTxInfo( + state: SlateState.s3, + slateId: tx.slateId, + finalizedAwaitingConfirmation: true, + broadcastPosted: broadcastPosted, + canRepost: true, + ); +} + +void main() { + testWidgets('successful repost immediately removes transaction Cancel', ( + tester, + ) async { + final wallet = _RepostDetailsWallet(); + final transaction = TransactionV2( + walletId: wallet.walletId, + blockHash: null, + hash: '08ab', + txid: 'slate-1', + timestamp: 0, + height: null, + inputs: [ + InputV2.isarCantDoRequiredInDefaultConstructor( + scriptSigHex: null, + scriptSigAsm: null, + sequence: null, + outpoint: null, + addresses: const [], + valueStringSats: '1100', + witness: null, + innerRedeemScriptAsm: null, + coinbase: null, + walletOwns: true, + ), + ], + outputs: [ + OutputV2.isarCantDoRequiredInDefaultConstructor( + scriptPubKeyHex: '', + valueStringSats: '1000', + addresses: const [], + walletOwns: false, + ), + ], + version: 0, + type: TransactionType.outgoing, + subType: TransactionSubType.none, + otherData: jsonEncode({ + TxV2OdKeys.isGrinTransaction: true, + TxV2OdKeys.slateId: 'slate-1', + TxV2OdKeys.grinSlateState: 'S3', + TxV2OdKeys.grinHasStoredTx: true, + }), + ); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + tester.view.physicalSize = const Size(1400, 2000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletChainHeight(wallet.walletId).overrideWithValue(0), + pTransactionNote((walletId: wallet.walletId, txid: transaction.txid)) + .overrideWithValue(null), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(wallet.cryptoCurrency).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: wallet.cryptoCurrency, + maxDecimals: 9, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: TransactionV2DetailsView( + transaction: transaction, + walletId: wallet.walletId, + coin: wallet.cryptoCurrency, + ), + ), + ), + ); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + expect(find.text('Cancel transaction'), findsOneWidget); + + await tester.ensureVisible(find.text('Repost')); + await tester.tap(find.text('Repost')); + await tester.pump(const Duration(milliseconds: 400)); + await tester.tap(find.text('Repost').last); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + + expect(wallet.reposted, ['slate-1']); + expect(find.text('Cancel transaction'), findsNothing); + }); +} diff --git a/test/pages/slatepack/grin_slatepack_flow_test.dart b/test/pages/slatepack/grin_slatepack_flow_test.dart new file mode 100644 index 0000000000..0629d2e5a7 --- /dev/null +++ b/test/pages/slatepack/grin_slatepack_flow_test.dart @@ -0,0 +1,563 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/balance.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/pay_invoice_confirm_view.dart'; +import 'package:stackwallet/pages/pinpad_views/lock_screen_view.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_import_flow.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import 'package:stackwallet/widgets/custom_loading_overlay.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/grin_fakes.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +Amount _grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + +/// A Grin test wallet whose Isar reads and refreshes are canned, so the +/// flow can run inside a widget test. +class _FlowWallet extends GrinTestWallet { + _FlowWallet(GrinHarness h) + : super( + testWalletId: h.walletId, + backend: h.backend, + tor: h.tor, + bus: h.bus, + secrets: h.secrets, + testPrefs: h.prefs, + ); + + ({Amount amount, Amount fee, bool isSend, bool isCancelled})? local; + bool repostable = false; + final reposted = []; + var finalizeInvoiceCalls = 0; + var finalizeSlatepackCalls = 0; + FinalizeResult invoiceFinalizeResult = FinalizeResult( + success: true, + slateId: 'slate-x', + posted: true, + ); + FinalizeResult slateFinalizeResult = FinalizeResult( + success: true, + slateId: 'slate-x', + posted: true, + ); + + /// What paying an invoice returns, if not the library's answer. + SlatepackResult? payment; + int paymentCalls = 0; + + /// What a cancel answers: "" or the failure. + String cancelResult = ''; + final cancelled = []; + + @override + Future refresh() async {} + + @override + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async => local; + + @override + Future canRepost(String txid) async => repostable; + + @override + Future repost(String txid) async => reposted.add(txid); + + @override + Future finalizeInvoice(String i2) async { + finalizeInvoiceCalls++; + return invoiceFinalizeResult; + } + + @override + Future finalizeSlatepack( + String s2, { + SlateInspection? inspection, + }) async { + finalizeSlatepackCalls++; + return slateFinalizeResult; + } + + @override + Future processInvoice( + String i1, { + required Amount confirmedAmount, + }) async { + paymentCalls++; + return payment ?? + SlatepackResult( + success: true, + slatepack: 'BEGINSLATEPACK. paid ENDSLATEPACK.', + state: SlateState.i2, + slateId: 'slate-i2', + amount: confirmedAmount, + fee: _grin(23500000), + ); + } + + @override + Future cancelPendingTransactionAndPost(String slateId) async { + cancelled.add(slateId); + return cancelResult; + } +} + +class _FlowPrefs extends ConfirmationPrefs { + @override + bool get isInitialized => true; + + @override + bool get autoPin => false; + + @override + bool get useBiometrics => false; + + @override + bool get randomizePIN => false; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + late _FlowWallet wallet; + var spendable = 100000; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + spendable = 100000; + wallet = _FlowWallet(h); + await wallet.init(); + }); + tearDown(() async { + try { + await wallet.exit(); + } catch (_) {} + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + GrinSlateInfo decoded(GrinSlateState state, {int amount = 0}) => + GrinSlateInfo( + slateId: 'slate-x', + state: state, + amount: BigInt.from(amount), + fee: BigInt.zero, + kernelExcess: null, + sender: 'grin1payee', + recipients: const [], + ttlCutoffHeight: null, + numParticipants: 2, + isEncrypted: false, + slateJson: '{}', + ); + + Future runFlow( + WidgetTester tester, { + Size size = const Size(1400, 2000), + bool mobile = false, + }) async { + final oldPlatform = Util.layoutPlatform; + if (mobile) { + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + } + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(() => Util.layoutPlatform = oldPlatform); + final previousThemesDir = StackFileSystem.themesDir; + addTearDown(() => StackFileSystem.themesDir = previousThemesDir); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletCoin(h.walletId).overrideWithValue(coin), + pWalletBalance(h.walletId).overrideWithValue( + Balance( + total: _grin(spendable), + spendable: _grin(spendable), + blockedTotal: _grin(0), + pendingSpendable: _grin(0), + ), + ), + prefsChangeNotifierProvider.overrideWithValue(_FlowPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: 9, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: 'BEGINSLATEPACK. x ENDSLATEPACK.', + ), + child: const Text('go'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('go')); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + } + + testWidgets('Grin routes an I1 to the pay invoice screen', (tester) async { + expect(wallet, isA()); + h.backend.api.decoded = decoded(GrinSlateState.i1, amount: 5000); + await runFlow(tester); + expect(find.byType(PayInvoiceConfirmView), findsOneWidget); + expect( + find.byWidgetPredicate( + (w) => w is SelectableText && w.data == '0.000005000 GRIN', + ), + findsOneWidget, + ); + // The fee comes from the wallet's estimate; nothing is paid yet. + expect(h.backend.api.calls, contains('estimateFee')); + expect(h.backend.api.calls, isNot(contains('processInvoice'))); + }); + + testWidgets('an invoice created by this wallet cannot be paid here', ( + tester, + ) async { + wallet.local = ( + amount: _grin(5000), + fee: _grin(0), + isSend: false, + isCancelled: false, + ); + h.backend.api.decoded = decoded(GrinSlateState.i1, amount: 5000); + + await runFlow(tester); + + expect(find.text('Cannot pay this invoice'), findsOneWidget); + expect(find.byType(PayInvoiceConfirmView), findsNothing); + expect(h.backend.api.calls, isNot(contains('processInvoice'))); + }); + + Future settle(WidgetTester tester) async { + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + } + + bool payEnabled(WidgetTester tester) => tester + .widget(find.byKey(const Key('payInvoiceButton'))) + .enabled; + + /// Opens the pay screen on an invoice the wallet can afford. + Future openInvoice( + WidgetTester tester, { + Size size = const Size(1400, 2000), + bool mobile = false, + }) async { + spendable = 1000000000; + h.backend.api.decoded = decoded(GrinSlateState.i1, amount: 5000); + await runFlow(tester, size: size, mobile: mobile); + expect(find.byType(PayInvoiceConfirmView), findsOneWidget); + } + + /// Presses Pay and passes the unlock step. + Future pay(WidgetTester tester) async { + await tester.tap(find.byKey(const Key('payInvoiceButton'))); + await settle(tester); + final desktopAuth = find.byType(DesktopAuthSend); + final auth = desktopAuth.evaluate().isNotEmpty + ? desktopAuth + : find.byType(LockscreenView); + Navigator.of(tester.element(auth)).pop(true); + await settle(tester); + } + + SlatepackResult paidWith({required int fee, String? slateId}) => + SlatepackResult( + success: true, + slatepack: 'BEGINSLATEPACK. paid ENDSLATEPACK.', + state: SlateState.i2, + slateId: slateId, + amount: _grin(5000), + fee: _grin(fee), + ); + + testWidgets('a failed fee estimate can be tried again', (tester) async { + h.backend.api.estimateError = grinError(9); + await openInvoice(tester); + expect(find.text('Could not estimate'), findsOneWidget); + expect(find.byKey(const Key('payInvoiceButton')), findsNothing); + + h.backend.api.estimateError = null; + await tester.tap(find.byKey(const Key('payInvoiceRetryEstimate'))); + await settle(tester); + expect(find.text('Could not estimate'), findsNothing); + expect(find.byKey(const Key('payInvoiceRetryEstimate')), findsNothing); + expect(payEnabled(tester), isTrue); + }); + + testWidgets('paying at the estimated fee shows the payment Slatepack', ( + tester, + ) async { + await openInvoice(tester); + await pay(tester); + expect(wallet.paymentCalls, 1); + expect(find.text('Higher fee'), findsNothing); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect(wallet.cancelled, isEmpty); + }); + + testWidgets('mobile waits for PIN dismissal before starting payment', ( + tester, + ) async { + await openInvoice(tester, mobile: true); + await tester.tap(find.byKey(const Key('payInvoiceButton'))); + await settle(tester); + final lock = find.byType(LockscreenView); + expect(lock, findsOneWidget); + + Navigator.of(tester.element(lock)).pop(true); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(find.byType(LockscreenView), findsOneWidget); + expect(find.byType(CustomLoadingOverlay), findsNothing); + expect(wallet.paymentCalls, 0); + + await settle(tester); + expect(find.byType(LockscreenView), findsNothing); + expect(wallet.paymentCalls, 1); + }); + + testWidgets('declining a higher fee cancels the payment', (tester) async { + wallet.payment = paidWith(fee: 30000000, slateId: 'slate-p'); + await openInvoice(tester); + await pay(tester); + expect(find.text('Higher fee'), findsOneWidget); + await tester.tap(find.text('Cancel payment')); + await settle(tester); + + expect(wallet.cancelled, ['slate-p']); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.text('Payment cancelled'), findsOneWidget); + await tester.tap(find.text('OK')); + await settle(tester); + expect(find.byType(PayInvoiceConfirmView), findsNothing); + }); + + testWidgets('invoice and higher-fee UI fit a 320px mobile screen', ( + tester, + ) async { + wallet.payment = paidWith(fee: 30000000, slateId: 'slate-p'); + await openInvoice(tester, size: const Size(320, 640), mobile: true); + expect(tester.takeException(), isNull); + await tester.ensureVisible(find.byKey(const Key('payInvoiceButton'))); + await pay(tester); + expect(find.text('Higher fee'), findsOneWidget); + await tester.ensureVisible(find.text('Cancel')); + expect(tester.takeException(), isNull); + await tester.tap(find.text('Cancel')); + await settle(tester); + expect(wallet.cancelled, ['slate-p']); + }); + + testWidgets('leaving during the higher-fee question still cancels', ( + tester, + ) async { + wallet.payment = paidWith(fee: 30000000, slateId: 'slate-p'); + await openInvoice(tester); + await pay(tester); + expect(find.text('Higher fee'), findsOneWidget); + + await tester.pumpWidget(const MaterialApp(home: SizedBox.shrink())); + await settle(tester); + + expect(wallet.cancelled, ['slate-p']); + }); + + for (final slateId in [null, 'slate-p']) { + testWidgets('a payment that could not be cancelled closes the screen and ' + 'points at the transaction details, slate id $slateId', (tester) async { + wallet.payment = paidWith(fee: 30000000, slateId: slateId); + wallet.cancelResult = 'The node did not answer.'; + await openInvoice(tester); + await pay(tester); + await tester.tap(find.text('Cancel payment')); + await settle(tester); + + expect(wallet.cancelled, slateId == null ? isEmpty : ['slate-p']); + expect(find.text('Cancel failed'), findsOneWidget); + expect( + find.textContaining( + slateId == null + ? 'Could not cancel automatically.' + : 'The node did not answer.', + ), + findsOneWidget, + ); + expect( + find.textContaining('Cancel the payment from the transaction details'), + findsOneWidget, + ); + await tester.tap(find.text('OK')); + await settle(tester); + // Paying again from here would be a second payment. + expect(find.byType(PayInvoiceConfirmView), findsNothing); + }); + } + + testWidgets('a payment that failed after the wallet recorded it closes the ' + 'screen', (tester) async { + wallet.payment = SlatepackResult( + success: false, + error: 'The payment failed. Open it in the transaction history.', + slateId: 'slate-p', + ); + await openInvoice(tester); + await pay(tester); + + expect(find.text('Invoice payment failed'), findsOneWidget); + expect(find.textContaining('transaction history'), findsOneWidget); + expect(find.byType(SlatepackDialog), findsNothing); + expect(wallet.cancelled, isEmpty); + await tester.tap(find.text('OK')); + await settle(tester); + expect(find.byType(PayInvoiceConfirmView), findsNothing); + }); + + testWidgets('a payment that failed and left nothing keeps the screen', ( + tester, + ) async { + wallet.payment = SlatepackResult(success: false, error: 'No.'); + await openInvoice(tester); + await pay(tester); + + expect(find.text('Invoice payment failed'), findsOneWidget); + await tester.tap(find.text('OK')); + await settle(tester); + expect(find.byType(PayInvoiceConfirmView), findsOneWidget); + expect(payEnabled(tester), isTrue); + }); + + testWidgets('an I1 without an amount is refused', (tester) async { + h.backend.api.decoded = decoded(GrinSlateState.i1); + await runFlow(tester); + expect(find.byType(PayInvoiceConfirmView), findsNothing); + expect( + find.text('This invoice does not say how much to pay.'), + findsOneWidget, + ); + }); + + testWidgets('Grin finalizes an I2 with the issued invoice as summary', ( + tester, + ) async { + h.backend.api.decoded = decoded(GrinSlateState.i2); + wallet.local = ( + amount: _grin(5000), + fee: _grin(0), + isSend: false, + isCancelled: false, + ); + await runFlow(tester); + expect(find.text('Finalize invoice'), findsOneWidget); + expect(find.text('0.000005000 GRIN'), findsOneWidget); + await tester.tap(find.text('Finalize')); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + expect(wallet.finalizeInvoiceCalls, 1); + expect(wallet.finalizeSlatepackCalls, 0); + }); + + testWidgets('a finalize the node refused offers repost', (tester) async { + h.backend.api.decoded = decoded(GrinSlateState.s2); + wallet.slateFinalizeResult = FinalizeResult( + success: true, + slateId: 'slate-x', + posted: false, + ); + wallet.local = ( + amount: _grin(5000), + fee: _grin(100), + isSend: true, + isCancelled: false, + ); + await runFlow(tester); + await tester.tap(find.text('Finalize')); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + expect(find.text('Finalized, not broadcast'), findsOneWidget); + await tester.tap(find.text('Repost')); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + expect(wallet.reposted, ['slate-x']); + }); + + testWidgets('an S3 with a stored transaction offers repost', (tester) async { + h.backend.api.decoded = decoded(GrinSlateState.s3); + wallet.repostable = true; + await runFlow(tester); + expect(find.text('Already finalized'), findsOneWidget); + expect(find.text('Repost'), findsOneWidget); + await tester.tap(find.text('Later')); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.reposted, isEmpty); + }); + + testWidgets('an S3 without a stored transaction is only a message', ( + tester, + ) async { + h.backend.api.decoded = decoded(GrinSlateState.s3); + await runFlow(tester); + expect(find.text('Already finalized'), findsOneWidget); + expect(find.text('Repost'), findsNothing); + }); +} diff --git a/test/pages/slatepack/grin_tx_details_and_proof_test.dart b/test/pages/slatepack/grin_tx_details_and_proof_test.dart new file mode 100644 index 0000000000..c05dda8387 --- /dev/null +++ b/test/pages/slatepack/grin_tx_details_and_proof_test.dart @@ -0,0 +1,438 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/verify_payment_proof_view.dart'; +import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/slatepack_tx_details.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/clipboard_interface.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/grin_fakes.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +class _DetailsWallet extends GrinTestWallet { + _DetailsWallet(GrinHarness h) + : super( + testWalletId: h.walletId, + backend: h.backend, + tor: h.tor, + bus: h.bus, + secrets: h.secrets, + testPrefs: h.prefs, + ); + + final reposted = []; + final exported = []; + + @override + Future refresh() async {} + + @override + Future repost(String txid) async => reposted.add(txid); + + @override + Future exportPaymentProof(String txid) async { + exported.add(txid); + return '{"amount":1,"excess":"08ab"}'; + } + + @override + Future pendingSlatepackFor(String txid) async => + 'BEGINSLATEPACK. again ENDSLATEPACK.'; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + late _DetailsWallet wallet; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + wallet = _DetailsWallet(h); + await wallet.init(); + }); + tearDown(() async { + try { + await wallet.exit(); + } catch (_) {} + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + final tx = TransactionV2( + walletId: 'w', + blockHash: null, + hash: '08ab', + txid: 'slate-1', + timestamp: 0, + height: null, + inputs: const [], + outputs: const [], + version: 0, + type: TransactionType.outgoing, + subType: TransactionSubType.none, + otherData: null, + ); + + Future pump( + WidgetTester tester, + Widget child, { + Size size = const Size(1400, 2000), + bool mobile = false, + }) async { + final oldPlatform = Util.layoutPlatform; + if (mobile) { + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + } + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(() => Util.layoutPlatform = oldPlatform); + final previousThemesDir = StackFileSystem.themesDir; + addTearDown(() => StackFileSystem.themesDir = previousThemesDir); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: 9, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold(body: SingleChildScrollView(child: child)), + ), + ), + ); + await tester.pump(); + } + + Future settle(WidgetTester tester) async { + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + } + + testWidgets('finalized, awaiting confirmation: rows and repost', ( + tester, + ) async { + await pump( + tester, + SlatepackTxDetails( + wallet: wallet, + transaction: tx, + info: const SlatepackTxInfo( + state: SlateState.s3, + slateId: 'slate-1', + kernelExcess: '08ab', + counterpartyAddress: 'grin1friend', + ttlCutoffHeight: 2500, + finalizedAwaitingConfirmation: true, + canRepost: true, + hasPaymentProof: true, + ), + ), + ); + expect(find.text('Finalized, awaiting confirmation'), findsOneWidget); + expect(find.text('08ab'), findsOneWidget); + expect(find.text('grin1friend'), findsOneWidget); + expect(find.text('2500'), findsOneWidget); + expect(find.textContaining('again'), findsNothing); + + await tester.tap(find.text('Repost')); + await tester.pump(const Duration(milliseconds: 400)); + // Confirm in the dialog. + await tester.tap(find.text('Repost').last); + await settle(tester); + expect(wallet.reposted, ['slate-1']); + }); + + testWidgets('a mined transaction does not show its expiry block', ( + tester, + ) async { + final mined = TransactionV2( + walletId: 'w', + blockHash: null, + hash: '08ab', + txid: 'slate-1', + timestamp: 0, + height: 1200, + inputs: const [], + outputs: const [], + version: 0, + type: TransactionType.outgoing, + subType: TransactionSubType.none, + otherData: null, + ); + await pump( + tester, + SlatepackTxDetails( + wallet: wallet, + transaction: mined, + info: const SlatepackTxInfo( + state: SlateState.s3, + slateId: 'slate-1', + kernelExcess: '08ab', + ttlCutoffHeight: 2500, + hasPaymentProof: true, + ), + ), + ); + expect(find.text('Expires at block'), findsNothing); + expect(find.text('2500'), findsNothing); + expect(find.text('08ab'), findsOneWidget); + }); + + testWidgets('a proof can be exported', (tester) async { + await pump( + tester, + SlatepackTxDetails( + wallet: wallet, + transaction: tx, + info: const SlatepackTxInfo(slateId: 'slate-1', hasPaymentProof: true), + ), + ); + expect(find.text('Repost'), findsNothing); + await tester.tap(find.text('Export payment proof')); + await settle(tester); + expect(wallet.exported, ['slate-1']); + expect(find.text('Payment proof'), findsOneWidget); + expect(find.textContaining('"excess": "08ab"'), findsOneWidget); + }); + + testWidgets('repost and proof dialogs fit a 320px mobile screen', ( + tester, + ) async { + await pump( + tester, + SlatepackTxDetails( + wallet: wallet, + transaction: tx, + info: const SlatepackTxInfo( + slateId: 'slate-1', + canRepost: true, + hasPaymentProof: true, + ), + ), + size: const Size(320, 640), + mobile: true, + ); + await tester.ensureVisible(find.text('Repost')); + await tester.tap(find.text('Repost')); + await settle(tester); + expect(tester.takeException(), isNull); + await tester.ensureVisible(find.text('Later')); + await tester.tap(find.text('Later')); + await settle(tester); + + await tester.ensureVisible(find.text('Export payment proof')); + await tester.tap(find.text('Export payment proof')); + await settle(tester); + expect(find.text('Payment proof'), findsOneWidget); + await tester.ensureVisible(find.text('Save')); + expect(tester.takeException(), isNull); + }); + + testWidgets('rows and proofs are copied through the given clipboard', ( + tester, + ) async { + final clipboard = FakeClipboard(); + await pump( + tester, + SlatepackTxDetails( + wallet: wallet, + transaction: tx, + clipboard: clipboard, + info: const SlatepackTxInfo( + slateId: 'slate-1', + kernelExcess: '08ab', + hasPaymentProof: true, + ), + ), + ); + await tester.tap(find.byTooltip('Copy').first); + await settle(tester); + expect((await clipboard.getData('text/plain'))!.text, '08ab'); + // The notice is gone before the next step. + await tester.pump(const Duration(seconds: 5)); + await settle(tester); + + await tester.tap(find.text('Export payment proof')); + await settle(tester); + await tester.tap(find.text('Copy')); + await settle(tester); + expect( + (await clipboard.getData('text/plain'))!.text, + contains('"excess": "08ab"'), + ); + await tester.pump(const Duration(seconds: 5)); + await settle(tester); + }); + + group('what cancelling says', () { + SlatepackCancelPrompt prompt(SlateState? state, {required bool incoming}) => + SlatepackCancelPrompt.of( + state == null ? null : SlatepackTxInfo(state: state), + incoming: incoming, + ); + const ends = 'The other party can no longer complete it'; + + test('a send or an invoice this wallet still has to finalize ends ' + 'with the cancel', () { + expect(prompt(SlateState.s1, incoming: false).message, contains(ends)); + expect(prompt(SlateState.i1, incoming: true).message, contains(ends)); + expect(prompt(null, incoming: false).message, contains(ends)); + expect( + prompt(SlateState.s1, incoming: false).confirmLabel, + 'Yes, cancel', + ); + }); + + test('a paid invoice can still be completed by the payee', () { + final p = prompt(SlateState.i2, incoming: false); + expect(p.title, 'Cancel this transaction?'); + expect(p.message, isNot(contains(ends))); + expect(p.message, contains('changes this wallet only')); + expect(p.message, contains('they can still complete it')); + }); + + test('an answered payment can still be completed by the sender', () { + for (final p in [ + prompt(SlateState.s2, incoming: true), + // Wallets that keep no slate state answer what they receive. + prompt(null, incoming: true), + prompt(SlateState.unknown, incoming: true), + ]) { + expect(p.message, isNot(contains(ends))); + expect(p.message, contains('this wallet only')); + expect(p.message, contains('they can still complete the payment')); + } + }); + + test('only pending Slatepack states are offered cancellation', () { + for (final state in [ + SlateState.s1, + SlateState.s2, + SlateState.i1, + SlateState.i2, + SlateState.unknown, + ]) { + expect(SlatepackTxInfo(state: state).canCancel, isTrue); + } + expect(const SlatepackTxInfo(state: SlateState.s3).canCancel, isFalse); + expect(const SlatepackTxInfo(state: SlateState.i3).canCancel, isFalse); + expect( + const SlatepackTxInfo( + state: SlateState.s2, + finalizedAwaitingConfirmation: true, + ).canCancel, + isFalse, + ); + expect( + const SlatepackTxInfo( + state: SlateState.s3, + finalizedAwaitingConfirmation: true, + broadcastPosted: true, + ).canCancel, + isFalse, + ); + expect( + const SlatepackTxInfo( + state: SlateState.s3, + finalizedAwaitingConfirmation: true, + broadcastPosted: false, + ).canCancel, + isTrue, + ); + }); + + test('a rejected finalized transaction explains safe cancellation', () { + final prompt = SlatepackCancelPrompt.of( + const SlatepackTxInfo( + state: SlateState.s3, + finalizedAwaitingConfirmation: true, + broadcastPosted: false, + ), + incoming: false, + ); + expect(prompt.message, contains('node did not accept')); + expect(prompt.message, contains('can still confirm')); + }); + }); + + testWidgets('an S1 waiting for an answer can be shown again', (tester) async { + await pump( + tester, + SlatepackTxDetails( + wallet: wallet, + transaction: tx, + info: const SlatepackTxInfo( + state: SlateState.s1, + slateId: 'slate-1', + canShowSlatepack: true, + ), + ), + ); + await tester.tap(find.text('Show Slatepack again')); + await settle(tester); + expect(find.text('Send Slatepack'), findsOneWidget); + expect(find.text('Not encrypted'), findsNothing); + expect(find.text("Encrypted to the other party's address"), findsNothing); + }); + + testWidgets('verify shows the node caveat and both sides', (tester) async { + await pump(tester, VerifyPaymentProofView(walletId: h.walletId)); + await tester.enterText( + find.byType(TextField), + '{"amount": 1000, "excess": "08ab", ' + '"recipient_address": "grin1recipient", ' + '"sender_address": "grin1ownaddress", ' + '"recipient_sig": "r", "sender_sig": "s"}', + ); + await tester.pump(); + await tester.tap(find.byKey(const Key('verifyPaymentProofButton'))); + await settle(tester); + expect(h.backend.api.calls, contains('verifyPaymentProof')); + expect( + find.textContaining('Kernel presence as reported by your node'), + findsOneWidget, + ); + expect(find.text('grin1recipient'), findsOneWidget); + expect(find.text('0.000001000 GRIN'), findsOneWidget); + }); +} diff --git a/test/pages/slatepack/invoice_dialog_layout_test.dart b/test/pages/slatepack/invoice_dialog_layout_test.dart new file mode 100644 index 0000000000..7fa9dab18c --- /dev/null +++ b/test/pages/slatepack/invoice_dialog_layout_test.dart @@ -0,0 +1,168 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/balance.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_import_flow.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/grin_fakes.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +Amount _grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + +/// A Grin test wallet whose Isar reads and refreshes are canned, so the +/// flow can run inside a widget test. +class _FlowWallet extends GrinTestWallet { + _FlowWallet(GrinHarness h) + : super( + testWalletId: h.walletId, + backend: h.backend, + tor: h.tor, + bus: h.bus, + secrets: h.secrets, + testPrefs: h.prefs, + ); + + ({Amount amount, Amount fee, bool isSend, bool isCancelled})? local; + bool repostable = false; + final reposted = []; + + @override + Future refresh() async {} + + @override + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async => local; + + @override + Future canRepost(String txid) async => repostable; + + @override + Future repost(String txid) async => reposted.add(txid); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + late _FlowWallet wallet; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + wallet = _FlowWallet(h); + await wallet.init(); + }); + tearDown(() async { + try { + await wallet.exit(); + } catch (_) {} + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + GrinSlateInfo decoded(GrinSlateState state, {int amount = 0}) => + GrinSlateInfo( + slateId: 'slate-x', + state: state, + amount: BigInt.from(amount), + fee: BigInt.zero, + kernelExcess: null, + sender: 'grin1payee', + recipients: const [], + ttlCutoffHeight: null, + numParticipants: 2, + isEncrypted: false, + slateJson: '{}', + ); + + Future runFlow(WidgetTester tester) async { + tester.view.physicalSize = const Size(1220, 750); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemesDir = StackFileSystem.themesDir; + addTearDown(() => StackFileSystem.themesDir = previousThemesDir); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletCoin(h.walletId).overrideWithValue(coin), + pWalletBalance(h.walletId).overrideWithValue( + Balance( + total: _grin(100000), + spendable: _grin(100000), + blockedTotal: _grin(0), + pendingSpendable: _grin(0), + ), + ), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: 9, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: 'BEGINSLATEPACK. x ENDSLATEPACK.', + ), + child: const Text('go'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('go')); + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 400)); + } + } + + testWidgets('invoice dialog fits the desktop window', (tester) async { + h.backend.api.decoded = decoded(GrinSlateState.i1, amount: 5000); + await runFlow(tester); + expect(tester.takeException(), isNull); + final button = find.byKey(const Key('payInvoiceButton')); + await tester.ensureVisible(button); + await tester.pump(); + expect(tester.getRect(button).bottom, lessThanOrEqualTo(750)); + }); +} diff --git a/test/pages/slatepack/request_invoice_view_test.dart b/test/pages/slatepack/request_invoice_view_test.dart new file mode 100644 index 0000000000..686e0915c1 --- /dev/null +++ b/test/pages/slatepack/request_invoice_view_test.dart @@ -0,0 +1,168 @@ +import 'dart:io'; + +import 'package:stackwallet/pages/slatepack/request_invoice_view.dart'; +import 'package:stackwallet/providers/global/price_provider.dart'; +import 'package:stackwallet/services/price_service.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/grin_fakes.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + await h.wallet.init(); + }); + tearDown(() async { + try { + await h.dispose(); + } catch (_) {} + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Future pump(WidgetTester tester, Widget child) async { + tester.view.physicalSize = const Size(1400, 2000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemesDir = StackFileSystem.themesDir; + addTearDown(() => StackFileSystem.themesDir = previousThemesDir); + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + final coin = h.wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(h.wallet)), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + priceAnd24hChangeNotifierProvider.overrideWithValue( + PriceService('USD'), + ), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: 9, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold(body: SingleChildScrollView(child: child)), + ), + ), + ); + await tester.pump(); + } + + testWidgets('invoice address edits update the create button', (tester) async { + await pump(tester, RequestInvoiceView(walletId: h.walletId)); + await tester.enterText( + find.byKey(const Key('slatepackRecipientFieldKey')), + 'invalid', + ); + await tester.enterText(find.byKey(const Key('requestInvoiceAmount')), '1'); + await tester.pump(); + expect( + tester + .widget(find.byKey(const Key('requestInvoiceCreate'))) + .enabled, + isFalse, + ); + await tester.enterText( + find.byKey(const Key('slatepackRecipientFieldKey')), + '', + ); + await tester.pump(); + expect( + tester + .widget(find.byKey(const Key('requestInvoiceCreate'))) + .enabled, + isTrue, + ); + }); + + testWidgets('invoice address edits disable the create button', ( + tester, + ) async { + await pump(tester, RequestInvoiceView(walletId: h.walletId)); + await tester.enterText(find.byKey(const Key('requestInvoiceAmount')), '1'); + await tester.pump(); + expect( + tester + .widget(find.byKey(const Key('requestInvoiceCreate'))) + .enabled, + isTrue, + ); + await tester.enterText( + find.byKey(const Key('slatepackRecipientFieldKey')), + 'invalid', + ); + await tester.pump(); + expect( + tester + .widget(find.byKey(const Key('requestInvoiceCreate'))) + .enabled, + isFalse, + ); + }); + testWidgets('invoice payer accepts only a slatepack address', (tester) async { + await pump(tester, RequestInvoiceView(walletId: h.walletId)); + await tester.enterText(find.byKey(const Key('requestInvoiceAmount')), '1'); + for (final address in ['https://payer.example', 'http://payer.onion']) { + await tester.enterText( + find.byKey(const Key('slatepackRecipientFieldKey')), + address, + ); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const Key('requestInvoiceCreate')), + ) + .enabled, + isFalse, + ); + } + await tester.enterText( + find.byKey(const Key('slatepackRecipientFieldKey')), + 'grin1payer', + ); + await tester.pump(); + expect( + tester + .widget(find.byKey(const Key('requestInvoiceCreate'))) + .enabled, + isTrue, + ); + }); +} diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 6aa58c649f..ce0ef9b4c7 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -4,10 +4,12 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/balance.dart'; import 'package:stackwallet/models/isar/stack_theme.dart'; import 'package:stackwallet/models/slatepack_models.dart'; import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; import 'package:stackwallet/pages/slatepack/slatepack_import_flow.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -16,6 +18,7 @@ import 'package:stackwallet/utilities/amount/amount_unit.dart'; import 'package:stackwallet/utilities/slatepack_text.dart'; import 'package:stackwallet/utilities/stack_file_system.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; @@ -23,12 +26,14 @@ import 'package:stackwallet/widgets/custom_loading_overlay.dart'; import 'package:stackwallet/widgets/rounded_container.dart'; import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; /// Epic Cash wallet whose inspection is canned, so run() can be driven /// without a native wallet. class _InspectOnlyWallet extends EpiccashWallet { _InspectOnlyWallet( this.state, { + this.invoices = false, this.localIsSend, this.localIsCancelled = false, this.localGate, @@ -45,7 +50,14 @@ class _InspectOnlyWallet extends EpiccashWallet { final String? senderAddress; final FinalizeResult? finalizeResult; + @override + String get walletId => "test-wallet"; + final SlateState state; + final bool invoices; + + @override + bool get supportsInvoices => invoices; /// Direction of the wallet's own transaction for the slate. Null when the /// wallet has none. @@ -137,6 +149,9 @@ class _SynchronousMwcWallet extends MimblewimblecoinWallet { final SlateState state; final Completer? localGate; + @override + String get walletId => "test-wallet"; + @override Future inspectSlatepack(String armored) { onInspect(); @@ -154,35 +169,60 @@ class _SynchronousMwcWallet extends MimblewimblecoinWallet { void main() { group("routeFor", () { test("standard send states", () { + for (final invoices in [true, false]) { + expect( + SlatepackImportFlow.routeFor( + SlateState.s1, + supportsInvoices: invoices, + ), + SlatepackRoute.receive, + ); + expect( + SlatepackImportFlow.routeFor( + SlateState.s2, + supportsInvoices: invoices, + ), + SlatepackRoute.finalizeSend, + ); + expect( + SlatepackImportFlow.routeFor( + SlateState.s3, + supportsInvoices: invoices, + ), + SlatepackRoute.alreadyFinalized, + ); + expect( + SlatepackImportFlow.routeFor( + SlateState.i3, + supportsInvoices: invoices, + ), + SlatepackRoute.alreadyFinalized, + ); + expect( + SlatepackImportFlow.routeFor( + SlateState.unknown, + supportsInvoices: invoices, + ), + SlatepackRoute.unsupported, + ); + } + }); + + test("invoice states depend on supportsInvoices", () { expect( - SlatepackImportFlow.routeFor(SlateState.s1), - SlatepackRoute.receive, - ); - expect( - SlatepackImportFlow.routeFor(SlateState.s2), - SlatepackRoute.finalizeSend, - ); - expect( - SlatepackImportFlow.routeFor(SlateState.s3), - SlatepackRoute.alreadyFinalized, - ); - expect( - SlatepackImportFlow.routeFor(SlateState.i3), - SlatepackRoute.alreadyFinalized, + SlatepackImportFlow.routeFor(SlateState.i1, supportsInvoices: true), + SlatepackRoute.payInvoice, ); expect( - SlatepackImportFlow.routeFor(SlateState.unknown), - SlatepackRoute.unsupported, + SlatepackImportFlow.routeFor(SlateState.i2, supportsInvoices: true), + SlatepackRoute.finalizeInvoice, ); - }); - - test("invoice states are unsupported", () { expect( - SlatepackImportFlow.routeFor(SlateState.i1), + SlatepackImportFlow.routeFor(SlateState.i1, supportsInvoices: false), SlatepackRoute.invoicesUnsupported, ); expect( - SlatepackImportFlow.routeFor(SlateState.i2), + SlatepackImportFlow.routeFor(SlateState.i2, supportsInvoices: false), SlatepackRoute.invoicesUnsupported, ); }); @@ -281,6 +321,9 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletBalance(wallet.walletId) + .overrideWithValue(Balance.zeroFor(currency: coin)), themeProvider.overrideWithProvider(StateProvider((ref) => theme)), pAmountFormatter(coin).overrideWithValue( AmountFormatter( @@ -839,5 +882,12 @@ void main() { expect(done, isFalse); expect(tester.takeException(), isNull); }); + testWidgets("invoice with invoice support opens the payment review", ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.i1, invoices: true); + await runFlow(tester, wallet); + expect(find.text("Pay invoice"), findsWidgets); + }); }); } diff --git a/test/pages/slatepack/slatepack_send_flow_test.dart b/test/pages/slatepack/slatepack_send_flow_test.dart index b5bbbb2a23..28072b24d8 100644 --- a/test/pages/slatepack/slatepack_send_flow_test.dart +++ b/test/pages/slatepack/slatepack_send_flow_test.dart @@ -50,6 +50,9 @@ class _Wallet extends EpiccashWallet { int created = 0; int refreshed = 0; final cancelled = []; + Amount? requestedAmount; + String? requestedRecipient; + bool? requestedSendAll; @override String get walletId => 'wallet-1'; @@ -67,8 +70,12 @@ class _Wallet extends EpiccashWallet { required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }) async { created++; + requestedAmount = amount; + requestedRecipient = recipientAddress; + requestedSendAll = sendAll; await gate?.future; if (createError != null) { return SlatepackResult(success: false, error: createError); @@ -108,6 +115,7 @@ class _SynchronousMwcWallet extends MimblewimblecoinWallet { required Amount amount, String? recipientAddress, String? message, + bool sendAll = false, }) async { onCreate(); await gate.future; @@ -149,6 +157,9 @@ Future> _pumpSend( WidgetTester tester, SlatepackInterface wallet, { MainDB? db, + Amount? creationAmount, + String? recipientAddress, + bool sendAll = false, }) async { tester.view.physicalSize = const Size(1400, 2400); tester.view.devicePixelRatio = 1; @@ -178,6 +189,9 @@ Future> _pumpSend( context: context, wallet: wallet, amount: _amount(100), + creationAmount: creationAmount, + recipientAddress: recipientAddress, + sendAll: sendAll, message: 'on-chain note', localNote: 'local note', db: db ?? _Notes(), @@ -198,6 +212,25 @@ Future> _pumpSend( } void main() { + testWidgets('creation options are forwarded but the confirmed amount is ' + 'still checked', (tester) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 1); + + await _pumpSend( + tester, + wallet, + creationAmount: _amount(110), + recipientAddress: 'grin1recipient', + sendAll: true, + ); + await tester.pumpAndSettle(); + + expect(wallet.requestedAmount, _amount(110)); + expect(wallet.requestedRecipient, 'grin1recipient'); + expect(wallet.requestedSendAll, isTrue); + expect(find.byType(SlatepackDialog), findsOneWidget); + }); + testWidgets('native creation starts after the progress route is visible', ( tester, ) async { diff --git a/test/themes/default_theme_grin_test.dart b/test/themes/default_theme_grin_test.dart new file mode 100644 index 0000000000..fa282610ac --- /dev/null +++ b/test/themes/default_theme_grin_test.dart @@ -0,0 +1,52 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:archive/archive_io.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; + +/// The default themes are binary archives, so a coin missing from them only +/// shows as a placeholder icon at runtime. +void main() { + // Themes are keyed by the coin's main net id. + final grin = Grin(CryptoCurrencyNetwork.main).mainNetId; + + for (final app in ["stack_wallet", "stack_duo"]) { + for (final name in ["light", "dark"]) { + test("the $app $name theme has Grin's colour and icons", () { + final archive = ZipDecoder().decodeBytes( + File("asset_sources/default_themes/$app/$name.zip").readAsBytesSync(), + ); + final files = { + for (final f in archive.files) + if (f.isFile) f.name, + }; + final json = jsonDecode( + utf8.decode( + archive.files.singleWhere((f) => f.name == "theme.json").content + as List, + ), + ) as Map; + + // Installed themes older than the app's default version are replaced + // on startup; the archive has to carry the version that added Grin. + expect(json["version"], greaterThanOrEqualTo(19)); + + final colors = (json["colors"] as Map)["coin"] as Map; + expect(colors[grin], matches(RegExp(r"^0x[0-9A-Fa-f]{8}$"))); + + final coins = (json["assets"] as Map)["coins"] as Map; + expect(coins, isNotEmpty); + for (final entry in coins.entries) { + final path = (entry.value as Map)[grin] as String?; + expect(path, isNotNull, reason: "${entry.key} has no grin entry"); + expect( + files, + contains("assets/$path"), + reason: "${entry.key} points at a file the archive lacks", + ); + } + }); + } + } +} diff --git a/test/wallets/grin/grin_errors_test.dart b/test/wallets/grin/grin_errors_test.dart index 316d9998d6..01c3ed9a3f 100644 --- a/test/wallets/grin/grin_errors_test.dart +++ b/test/wallets/grin/grin_errors_test.dart @@ -2,8 +2,8 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; -import 'package:grin_native/grin_native.dart'; import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; import 'package:stackwallet/exceptions/wallet/insufficient_balance_exception.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -52,7 +52,7 @@ void main() { test('a node error with a slate id means finalized, not broadcast', () { final safe = sanitizeGrinError( - grinError(9, details: {'slate_id': 's'}), + grinError(9, details: {'slate_id': 's', 'finalized': true}), ) as GrinWalletException; expect(safe.finalizedNotBroadcast, isTrue); expect( @@ -63,6 +63,33 @@ void main() { ); }); + test('a slate id alone means a transaction was left behind', () { + final safe = sanitizeGrinError( + grinError(12, details: {'slate_id': 's'}), + ) as GrinWalletException; + expect(safe.leftPendingTransaction, isTrue); + expect(safe.finalizedNotBroadcast, isFalse); + expect(safe.message, endsWith(grinLeftPendingNote)); + }); + + test('released means nothing is locked', () { + final safe = sanitizeGrinError( + grinError(12, details: {'slate_id': 's', 'released': true}), + ) as GrinWalletException; + expect(safe.released, isTrue); + expect(safe.leftPendingTransaction, isFalse); + expect(safe.message, grinReleasedMessage); + }); + + test('the flags mean nothing without a slate id', () { + final safe = sanitizeGrinError( + grinError(9, details: {'finalized': true, 'released': true}), + ) as GrinWalletException; + expect(safe.finalized, isFalse); + expect(safe.released, isFalse); + expect(safe.message, 'Could not reach the Grin node.'); + }); + test('other errors keep only their type', () { final safe = sanitizeGrinError(const FormatException(remoteText)); expect(safe.toString(), isNot(contains(remoteText))); @@ -139,7 +166,7 @@ void main() { final s1 = await h.wallet.receiveSlatepack( 'BEGINSLATEPACK. incoming ENDSLATEPACK.', ); - expect(s1.state, GrinSlateState.s2); + expect(s1.state, SlateState.s2); expect(password, isNotEmpty); shown.add(password); diff --git a/test/wallets/grin/grin_invoice_test.dart b/test/wallets/grin/grin_invoice_test.dart index 4d45f3648f..2f9bd85d44 100644 --- a/test/wallets/grin/grin_invoice_test.dart +++ b/test/wallets/grin/grin_invoice_test.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:grin_native/grin_native.dart'; import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; @@ -35,30 +36,35 @@ void main() { test('an amount mismatch never reaches processInvoice', () async { h.backend.api.decoded = slateInfoOf(GrinSlateState.i1, amount: 2000); - await expectLater( - h.wallet.processInvoice('i1', confirmedAmount: grin(1000)), - throwsA(isA()), + final result = await h.wallet.processInvoice( + 'i1', + confirmedAmount: grin(1000), ); + expect(result.success, isFalse); + expect(result.error, contains('does not match')); expect(h.backend.api.calls, isNot(contains('processInvoice'))); }); test('a slate that is not an I1 never reaches processInvoice', () async { for (final state in [GrinSlateState.s1, GrinSlateState.i2]) { h.backend.api.decoded = slateInfoOf(state, amount: 1000); - await expectLater( - h.wallet.processInvoice('x', confirmedAmount: grin(1000)), - throwsA(isA()), + final result = await h.wallet.processInvoice( + 'x', + confirmedAmount: grin(1000), ); + expect(result.success, isFalse); } expect(h.backend.api.calls, isNot(contains('processInvoice'))); }); test('an unreadable invoice never reaches processInvoice', () async { h.backend.api.decoded = null; - await expectLater( - h.wallet.processInvoice('garbage', confirmedAmount: grin(1000)), - throwsA(isA()), + final result = await h.wallet.processInvoice( + 'garbage', + confirmedAmount: grin(1000), ); + expect(result.success, isFalse); + expect(result.error, isNot(contains(remoteText))); expect(h.backend.api.calls, isNot(contains('processInvoice'))); }); @@ -70,7 +76,10 @@ void main() { 'i1', confirmedAmount: grin(1000), ); - expect(i2.state, GrinSlateState.i2); + expect(i2.success, isTrue); + expect(i2.state, SlateState.i2); + expect(i2.slatepack, startsWith('BEGINSLATEPACK.')); + expect((await h.wallet.localTxForSlate(i2.slateId!))?.isSend, isTrue); final args = h.backend.api.invoicePayments.single; expect(args.expectedAmount, BigInt.from(1000)); expect(args.ttlBlocks, GrinWallet.slatepackTtlBlocks); @@ -78,13 +87,39 @@ void main() { }, ); + test('a payment that failed after it was recorded names its slate', () async { + final api = h.backend.api; + api.decoded = slateInfoOf(GrinSlateState.i1, amount: 1000); + api.invoiceError = grinError(11, details: {'slate_id': 'slate-p'}); + final kept = await h.wallet.processInvoice( + 'i1', + confirmedAmount: grin(1000), + ); + expect(kept.success, isFalse); + expect(kept.slateId, 'slate-p'); + expect(kept.error, contains(grinLeftPendingNote)); + expect(kept.error, isNot(contains(remoteText))); + + api.invoiceError = grinError(11); + final nothing = await h.wallet.processInvoice( + 'i1', + confirmedAmount: grin(1000), + ); + expect(nothing.success, isFalse); + expect(nothing.slateId, isNull); + }); + test('issuing and finalizing an invoice', () async { final i1 = await h.wallet.issueInvoice( amount: grin(1000), payerAddress: 'grin1payer', ); - expect(i1.state, GrinSlateState.i1); + expect(i1.state, SlateState.i1); + expect(i1.amount, grin(1000)); + expect((await h.wallet.localTxForSlate(i1.slateId!))?.isSend, isFalse); final done = await h.wallet.finalizeInvoice('i2'); + expect(done.success, isTrue); expect(done.posted, isTrue); + expect(done.kernelExcess, '08ab'); }); } diff --git a/test/wallets/grin/grin_lifecycle_test.dart b/test/wallets/grin/grin_lifecycle_test.dart index e0bfe2c957..a4c2035a2a 100644 --- a/test/wallets/grin/grin_lifecycle_test.dart +++ b/test/wallets/grin/grin_lifecycle_test.dart @@ -165,7 +165,12 @@ void main() { final next = r.newWallet(); addTearDown(next.exit); await next.recover(isRescan: true); - expect(r.backend.calls, ['create', 'open', 'create']); + // The first wallet's refresh after its scan asked the node for its height. + expect(r.backend.calls.where((c) => c != 'testNodeConnection'), [ + 'create', + 'open', + 'create', + ]); expect(await isar.transactionV2s.count(), 0); expect(next.info.grinData!.pendingScanFrom, 1000); await eventually(() => r.backend.api.calls.contains('scan:1000:false')); diff --git a/test/wallets/grin/grin_scan_test.dart b/test/wallets/grin/grin_scan_test.dart index 457bb14946..3105d5e905 100644 --- a/test/wallets/grin/grin_scan_test.dart +++ b/test/wallets/grin/grin_scan_test.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/widgets.dart'; import 'package:grin_native/grin_native.dart'; import 'package:isar_community/isar.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; @@ -129,6 +130,36 @@ void main() { ]); }); + test('a paused restore continues when the app resumes', () async { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + h.wallet.mobileScanLifecycle = true; + final api = await restore(); + await eventually(() => api.scanRunning, reason: 'initial restore starts'); + api.cancelScannedHeight = 1500; + + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await eventually( + () => h.wallet.info.grinData!.pendingScanFrom == 1501, + reason: 'pause saves progress', + ); + await pumpEventQueue(); + await h.wallet.refresh(); + await pumpEventQueue(); + expect(api.calls.where((c) => c.startsWith('scan:')), ['scan:1000:false']); + + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await eventually( + () => api.calls.contains('scan:1501:false'), + reason: 'resume starts the next scan', + ); + expect(api.scanRunning, isTrue); + }); + test('a node change continues a pending restore', () async { await h.wallet.init(isRestore: true); h.wallet.shouldAutoSync = true; diff --git a/test/wallets/grin/grin_slatepack_interface_test.dart b/test/wallets/grin/grin_slatepack_interface_test.dart new file mode 100644 index 0000000000..ff04e4df2f --- /dev/null +++ b/test/wallets/grin/grin_slatepack_interface_test.dart @@ -0,0 +1,513 @@ +import 'dart:io'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_scan_pause_observer.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + await h.wallet.init(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Amount grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + + GrinSlateInfo info( + GrinSlateState state, { + int amount = 0, + int fee = 0, + bool encrypted = false, + }) => GrinSlateInfo( + slateId: 'slate-in', + state: state, + amount: BigInt.from(amount), + fee: BigInt.from(fee), + kernelExcess: null, + sender: 'grin1sender', + recipients: encrypted ? const ['grin1ownaddress'] : const [], + ttlCutoffHeight: 2000, + numParticipants: 2, + isEncrypted: encrypted, + slateJson: '{}', + ); + + Future storeHistory(List entries) async { + h.backend.api.transactions = GrinTxList( + refreshedFromNode: true, + transactions: entries, + ); + await h.wallet.updateTransactions(); + } + + test('GrinWallet is a SlatepackInterface with the Grin capabilities', () { + final SlatepackInterface wallet = h.wallet; + expect(wallet.supportedMethods, [ + SlatepackMethod.slatepack, + SlatepackMethod.http, + ]); + expect(wallet.supportsOnChainNote, isFalse); + expect(wallet.supportsInvoices, isTrue); + expect(wallet.supportsPaymentProofs, isTrue); + expect(wallet.supportsRepost, isTrue); + expect(wallet.receiveQrIsRawAddress, isTrue); + expect(wallet.receiveAddressNote, isNotNull); + }); + + test('the direct send hint names the address prefix of the network', () { + expect(h.wallet.directSendAddressHint, startsWith('grin1 ')); + final testnet = GrinWallet( + CryptoCurrencyNetwork.test, + backend: h.backend, + torService: h.tor, + eventBus: h.bus, + ); + expect(testnet.directSendAddressHint, startsWith('tgrin1 ')); + }); + + group('inspectSlatepack', () { + test('an S1 carries amount, sender, encryption and TTL', () async { + h.backend.api.decoded = info( + GrinSlateState.s1, + amount: 5000, + fee: 300, + encrypted: true, + ); + final inspection = await h.wallet.inspectSlatepack('s1'); + expect(inspection.state, SlateState.s1); + expect(inspection.slateId, 'slate-in'); + expect(inspection.amount, grin(5000)); + expect(inspection.fee, grin(300)); + expect(inspection.senderAddress, 'grin1sender'); + expect(inspection.isEncrypted, isTrue); + expect(inspection.ttlCutoffHeight, 2000); + }); + + test('S2 and I2 leave the amount to the local transaction', () async { + for (final state in [GrinSlateState.s2, GrinSlateState.i2]) { + h.backend.api.decoded = info(state, fee: 300); + final inspection = await h.wallet.inspectSlatepack('x'); + expect(inspection.amount, isNull); + expect(inspection.state, SlateState.fromCode(state.wireName)); + } + }); + + test('an I1 has no fee yet', () async { + h.backend.api.decoded = info(GrinSlateState.i1, amount: 7000); + final inspection = await h.wallet.inspectSlatepack('i1'); + expect(inspection.state, SlateState.i1); + expect(inspection.amount, grin(7000)); + expect(inspection.fee, isNull); + }); + + test('an unreadable slatepack throws a sanitized error', () async { + h.backend.api.decoded = null; + await expectLater( + h.wallet.inspectSlatepack('junk'), + throwsA( + isA().having( + (e) => e.message, + 'message', + isNot(contains(remoteText)), + ), + ), + ); + }); + }); + + test('localTxForSlate reads the stored send', () async { + h.backend.api.transactionRefreshes.clear(); + expect(await h.wallet.localTxForSlate('slate-1'), isNull); + expect( + h.backend.api.transactionRefreshes, + everyElement(isFalse), + reason: 'a Slatepack import must not wait for the node', + ); + await storeHistory([ + entryOf(id: 1, debited: 3000, credited: 1000, fee: 100), + ]); + final local = await h.wallet.localTxForSlate('slate-1'); + expect(local, isNotNull); + expect(local!.fee, grin(100)); + expect(local.amount, grin(1900)); + expect(local.isSend, isTrue); + }); + + group('createSlatepack', () { + test('encrypts to a recipient and honours send all', () async { + h.backend.api.transactionRefreshes.clear(); + h.backend.api.balanceRefreshes.clear(); + final result = await h.wallet.createSlatepack( + amount: grin(5000), + recipientAddress: 'grin1friend', + sendAll: true, + ); + expect(result.success, isTrue); + expect(result.state, SlateState.s1); + expect(result.slateId, 'slate-S1'); + expect(result.slatepack, startsWith('BEGINSLATEPACK.')); + final args = h.backend.api.initSends.single; + expect(args.recipientAddress, 'grin1friend'); + expect(args.amount, BigInt.from(5000)); + expect(args.selectionStrategyIsAll, isTrue); + expect(args.amountIncludesFee, isTrue); + expect(args.ttlBlocks, GrinWallet.slatepackTtlBlocks); + await eventually( + () => + h.backend.api.transactionRefreshes.isNotEmpty && + h.backend.api.balanceRefreshes.isNotEmpty, + ); + expect(h.backend.api.transactionRefreshes, everyElement(isFalse)); + expect(h.backend.api.balanceRefreshes, everyElement(isFalse)); + expect(h.backend.api.transactionRefreshes, isNotEmpty); + expect(h.backend.api.balanceRefreshes, isNotEmpty); + }); + + test('without a recipient the S1 is plain', () async { + final result = await h.wallet.createSlatepack(amount: grin(5000)); + expect(result.success, isTrue); + expect(h.backend.api.initSends.single.recipientAddress, isNull); + expect(h.backend.api.initSends.single.selectionStrategyIsAll, isFalse); + }); + + test('a recipient that is not a grin1 address locks nothing', () async { + final result = await h.wallet.createSlatepack( + amount: grin(5000), + recipientAddress: 'https://x.example', + ); + expect(result.success, isFalse); + expect(h.backend.api.calls, isNot(contains('initSend'))); + }); + }); + + test('receiveSlatepack returns the S2', () async { + h.backend.api.transactionRefreshes.clear(); + h.backend.api.balanceRefreshes.clear(); + final result = await h.wallet.receiveSlatepack('s1'); + expect(result.success, isTrue); + expect(result.state, SlateState.s2); + expect(result.slatepack, isNotNull); + final local = await h.wallet.localTxForSlate(result.slateId!); + expect(local?.isSend, isFalse); + await eventually( + () => + h.backend.api.transactionRefreshes.isNotEmpty && + h.backend.api.balanceRefreshes.isNotEmpty, + ); + expect(h.backend.api.transactionRefreshes, everyElement(isFalse)); + expect(h.backend.api.balanceRefreshes, everyElement(isFalse)); + expect(h.backend.api.transactionRefreshes, isNotEmpty); + expect(h.backend.api.balanceRefreshes, isNotEmpty); + }); + + group('finalizeSlatepack', () { + test('posted with the kernel excess', () async { + h.backend.api.transactionRefreshes.clear(); + final result = await h.wallet.finalizeSlatepack('s2'); + expect(result.success, isTrue); + expect(result.posted, isTrue); + expect(result.kernelExcess, '08ab'); + expect(result.slateId, 'slate-S3'); + await eventually(() => h.backend.api.transactionRefreshes.isNotEmpty); + expect(h.backend.api.transactionRefreshes, everyElement(isFalse)); + expect(h.backend.api.transactionRefreshes, isNotEmpty); + }); + + test('a node error naming the slate is finalized, not posted', () async { + h.backend.api.finalizeError = grinError( + 9, + details: {'slate_id': 'slate-1', 'finalized': true}, + ); + final result = await h.wallet.finalizeSlatepack('s2'); + expect(result.success, isTrue); + expect(result.posted, isFalse); + expect(result.slateId, 'slate-1'); + expect(result.error, contains('repost')); + expect(result.error, isNot(contains(remoteText))); + + await storeHistory([ + entryOf(id: 9, state: GrinSlateState.s3, hasStoredTx: true), + ]); + final tx = (await isar.transactionV2s.where().findAll()).single; + final details = h.wallet.slatepackTxInfo(tx)!; + expect(details.broadcastPosted, isFalse); + expect(details.canCancel, isTrue); + + await h.wallet.repost('slate-1'); + final reposted = h.wallet.slatepackTxInfo(tx)!; + expect(reposted.broadcastPosted, isTrue); + expect(reposted.canCancel, isFalse); + }); + + test('a node error before finalizing is a failure', () async { + h.backend.api.finalizeError = grinError(9); + final result = await h.wallet.finalizeSlatepack('s2'); + expect(result.success, isFalse); + }); + + test('not found means not a pending send from this wallet', () async { + h.backend.api.finalizeError = grinError(13); + final result = await h.wallet.finalizeSlatepack('s2'); + expect(result.success, isFalse); + expect(result.error, 'This is not a pending send from this wallet.'); + }); + + test('an invoice node error is offered for repost too', () async { + h.backend.api.finalizeError = grinError( + 9, + details: {'slate_id': 'slate-i', 'finalized': true}, + ); + final result = await h.wallet.finalizeInvoice('i2'); + expect(result.success, isTrue); + expect(result.posted, isFalse); + }); + }); + + group('stored transactions', () { + test('repost needs a stored finalized transaction', () async { + await storeHistory([entryOf(id: 3, state: GrinSlateState.s1)]); + await expectLater( + h.wallet.repost('slate-1'), + throwsA(isA()), + ); + expect(h.backend.api.calls, isNot(contains('repost'))); + + await storeHistory([ + entryOf(id: 3, state: GrinSlateState.s3, hasStoredTx: true), + ]); + await h.wallet.repost('slate-1'); + expect(h.backend.api.reposts.single, (txId: 3, slateId: 'slate-1')); + }); + + test('slatepackTxInfo offers repost for finalized, unconfirmed', () async { + await storeHistory([ + entryOf( + id: 4, + state: GrinSlateState.s3, + hasStoredTx: true, + kernelExcess: '08cd', + counterparty: 'grin1friend', + ttl: 2500, + ), + ]); + final tx = (await isar.transactionV2s.where().findAll()).single; + final details = h.wallet.slatepackTxInfo(tx)!; + expect(details.slateId, 'slate-1'); + expect(details.kernelExcess, '08cd'); + expect(details.counterpartyAddress, 'grin1friend'); + expect(details.ttlCutoffHeight, 2500); + expect(details.finalizedAwaitingConfirmation, isTrue); + expect(details.canRepost, isTrue); + expect(details.canShowSlatepack, isFalse); + }); + + test('an S1 waiting for an answer can be shown again', () async { + await storeHistory([ + entryOf(id: 5, state: GrinSlateState.s1, armored: 'BEGINSLATEPACK.'), + ]); + final tx = (await isar.transactionV2s.where().findAll()).single; + final details = h.wallet.slatepackTxInfo(tx)!; + expect(details.canShowSlatepack, isTrue); + expect(details.canRepost, isFalse); + expect(await h.wallet.pendingSlatepackFor('slate-1'), 'BEGINSLATEPACK.'); + }); + + test('a cancelled send offers nothing', () async { + await storeHistory([ + entryOf(id: 6, type: GrinTxType.txSentCancelled, hasStoredTx: true), + ]); + final tx = (await isar.transactionV2s.where().findAll()).single; + final details = h.wallet.slatepackTxInfo(tx)!; + expect(details.canRepost, isFalse); + expect(details.canShowSlatepack, isFalse); + }); + + test('export needs a payment proof', () async { + await storeHistory([entryOf(id: 7, state: GrinSlateState.s3)]); + await expectLater( + h.wallet.exportPaymentProof('slate-1'), + throwsA(isA()), + ); + expect(h.backend.api.calls, isNot(contains('exportPaymentProof'))); + + await storeHistory([ + entryOf( + id: 7, + state: GrinSlateState.s3, + proof: const GrinPaymentProofSummary( + receiverAddress: 'grin1recipient', + senderAddress: 'grin1ownaddress', + receiverSignaturePresent: true, + senderSignaturePresent: true, + ), + ), + ]); + final json = await h.wallet.exportPaymentProof('slate-1'); + expect(json, contains('grin1recipient')); + }); + }); + + group('verifyPaymentProof', () { + const proof = + '{"amount": 1000, "excess": "08ab", ' + '"recipient_address": "grin1recipient", ' + '"sender_address": "grin1ownaddress", ' + '"recipient_sig": "r", "sender_sig": "s"}'; + + test('reports the proof and which side this wallet is', () async { + final check = await h.wallet.verifyPaymentProof(proof); + expect(check.amount, grin(1000)); + expect(check.kernelExcess, '08ab'); + expect(check.senderAddress, 'grin1ownaddress'); + expect(check.recipientAddress, 'grin1recipient'); + expect(check.isSender, isTrue); + expect(check.isRecipient, isFalse); + }); + + test('malformed text never reaches the library', () async { + await expectLater( + h.wallet.verifyPaymentProof('not json'), + throwsA(isA()), + ); + expect(h.backend.api.calls, isNot(contains('verifyPaymentProof'))); + }); + + test('a failed check has fixed text', () async { + h.backend.api.verifyError = grinError(12); + await expectLater( + h.wallet.verifyPaymentProof(proof), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('did not verify'), + ), + ), + ); + }); + }); + + group('httpSendPolicy', () { + test('Tor off: clearnet needs the IP warning, onion is blocked', () { + final https = h.wallet.httpSendPolicy('https://x.example'); + expect(https.isBlocked, isFalse); + expect(https.needsClearnetAck, isTrue); + expect(https.needsPlaintextAck, isFalse); + + final http = h.wallet.httpSendPolicy('http://x.example'); + expect(http.needsClearnetAck, isTrue); + expect(http.needsPlaintextAck, isTrue); + + expect(h.wallet.httpSendPolicy('grin1friend').isBlocked, isTrue); + expect( + h.wallet.httpSendPolicy('http://${'a' * 56}.onion').isBlocked, + isTrue, + ); + }); + + test('Tor on: no IP warning, plain http still warned', () { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + final https = h.wallet.httpSendPolicy('https://x.example'); + expect(https.isBlocked, isFalse); + expect(https.needsClearnetAck, isFalse); + expect( + h.wallet.httpSendPolicy('http://x.example').needsPlaintextAck, + isTrue, + ); + expect(h.wallet.httpSendPolicy('grin1friend').isBlocked, isFalse); + }); + + test('Tor wanted but down blocks everything', () { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + for (final target in [ + 'https://x.example', + 'http://x.example', + 'grin1friend', + ]) { + expect(h.wallet.httpSendPolicy(target).isBlocked, isTrue); + } + }); + }); + + test('an HTTP answer that fails checks says nothing was locked', () async { + h.backend.api.sendError = grinError(11); + await expectLater( + h.wallet.confirmSend( + txData: TxData( + recipients: [ + TxRecipient( + address: 'https://x.example', + amount: grin(1000), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + otherData: slatepackMethodOtherData(SlatepackMethod.http), + grinClearnetAcknowledged: true, + ), + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains("recipient's answer failed checks"), + ), + ), + ); + }); + + test('app pause and resume notify the scan owner', () { + var cancels = 0; + var resumes = 0; + final observer = GrinScanPauseObserver.detached( + cancelScan: () => cancels++, + resumeScan: () => resumes++, + ); + observer.onStateChange(AppLifecycleState.resumed); + observer.onStateChange(AppLifecycleState.inactive); + expect(cancels, 0); + observer.onStateChange(AppLifecycleState.paused); + expect(cancels, 1); + observer.onStateChange(AppLifecycleState.detached); + expect(cancels, 2); + expect(observer.isPaused, isTrue); + expect(resumes, 0); + observer.onStateChange(AppLifecycleState.resumed); + expect(observer.isPaused, isFalse); + expect(resumes, 1); + observer.dispose(); + }); +} diff --git a/test/wallets/grin/grin_tx_failures_test.dart b/test/wallets/grin/grin_tx_failures_test.dart new file mode 100644 index 0000000000..5b440ae3a2 --- /dev/null +++ b/test/wallets/grin/grin_tx_failures_test.dart @@ -0,0 +1,395 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_status_changed_event.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(restoreHeight: 1000); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Amount grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + + TxData send(String address, {SlatepackMethod? method}) => TxData( + recipients: [ + TxRecipient( + address: address, + amount: grin(1000000000), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + otherData: method == null ? null : slatepackMethodOtherData(method), + grinClearnetAcknowledged: true, + ); + + Future failure(Future call) async { + try { + await call; + } on GrinWalletException catch (e) { + return e; + } + fail('the call did not fail'); + } + + /// Whether the history was read again after [call] was made. + bool refreshedAfter(String call) { + final calls = h.backend.api.calls; + return calls.skip(calls.lastIndexOf(call)).contains('getTransactions'); + } + + Future storedTx() async => (await isar.transactionV2s + .where() + .txidWalletIdEqualTo('slate-1', h.wallet.walletId) + .findFirst())!; + + Future storeHistory(List entries) async { + h.backend.api.transactions = GrinTxList( + refreshedFromNode: true, + transactions: entries, + ); + await h.wallet.updateTransactions(); + } + + Future startScan() async { + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await eventually(() => h.backend.api.scanRunning); + return h.backend.api; + } + + group('an HTTP send that fails', () { + const target = 'https://wallet.example'; + + test('before anything is locked says so and changes nothing', () async { + await h.wallet.init(); + h.backend.api.sendError = grinError(11); + final e = await failure(h.wallet.confirmSend(txData: send(target))); + expect(e.message, endsWith('Nothing was sent or locked.')); + expect(e.leftPendingTransaction, isFalse); + await pumpEventQueue(); + expect(refreshedAfter('sendHttp'), isFalse); + }); + + test('and was released again says no funds are locked', () async { + await h.wallet.init(); + h.backend.api.sendError = grinError( + 12, + details: {'slate_id': 'slate-r', 'released': true}, + ); + final e = await failure(h.wallet.confirmSend(txData: send(target))); + expect(e.message, endsWith('Nothing was sent and no funds are locked.')); + expect(e.released, isTrue); + expect(e.leftPendingTransaction, isFalse); + expect(e.finalizedNotBroadcast, isFalse); + expect(e.message, isNot(contains(remoteText))); + await eventually(() => refreshedAfter('sendHttp')); + }); + + test('and could not be released points at the history', () async { + await h.wallet.init(); + h.backend.api.sendError = grinError(11, details: {'slate_id': 'slate-l'}); + final e = await failure(h.wallet.confirmSend(txData: send(target))); + expect(e.message, contains('Nothing was sent.')); + expect(e.message, endsWith(grinLeftPendingNote)); + expect(e.message, isNot(contains('or locked'))); + expect(e.slateId, 'slate-l'); + expect(e.leftPendingTransaction, isTrue); + await eventually(() => refreshedAfter('sendHttp')); + }); + + test('at the broadcast is finalized and can be reposted', () async { + await h.wallet.init(); + h.backend.api.sendError = grinError( + 9, + details: {'slate_id': 'slate-f', 'finalized': true}, + ); + final e = await failure(h.wallet.confirmSend(txData: send(target))); + expect(e.message, grinFinalizedNotBroadcastMessage); + expect(e.finalizedNotBroadcast, isTrue); + expect(e.slateId, 'slate-f'); + expect(e.leftPendingTransaction, isFalse); + await eventually(() => refreshedAfter('sendHttp')); + }); + }); + + group('a fee that changed after the review', () { + GrinFeeEstimate feeOf(int fee) => GrinFeeEstimate( + fee: BigInt.from(fee), + amount: BigInt.zero, + netAmount: BigInt.zero, + total: BigInt.zero, + inputsCount: 2, + changeOutputs: 1, + ); + + test('stops a Slatepack send before anything is locked', () async { + await h.wallet.init(); + final api = h.backend.api; + final prepared = await h.wallet.prepareSend(txData: send('grin1friend')); + api.fee = feeOf(31000000); + final e = await failure(h.wallet.confirmSend(txData: prepared)); + expect(e.message, contains('fee changed')); + expect(api.initSends, isEmpty); + expect(api.cancelled, isEmpty); + }); + + test('stops an HTTP send before the recipient is contacted', () async { + await h.wallet.init(); + final api = h.backend.api; + final prepared = await h.wallet.prepareSend( + txData: send('https://wallet.example'), + ); + api.fee = feeOf(31000000); + final e = await failure(h.wallet.confirmSend(txData: prepared)); + expect(e.message, contains('fee changed')); + expect(api.httpSends, isEmpty); + }); + + test('cancels a Slatepack send that was built with another fee', () async { + await h.wallet.init(); + final api = h.backend.api; + final prepared = await h.wallet.prepareSend(txData: send('grin1friend')); + api.sendFee = BigInt.from(31000000); + final e = await failure(h.wallet.confirmSend(txData: prepared)); + expect(e.message, contains('fee changed')); + expect(api.cancelled.single, (txId: null, slateId: 'slate-S1')); + }); + + test('an unchanged fee sends', () async { + await h.wallet.init(); + final prepared = await h.wallet.prepareSend( + txData: send('grin1friend').copyWith(subtractFeeFromAmount: true), + ); + final sent = await h.wallet.confirmSend(txData: prepared); + expect(sent.txid, 'slate-S1'); + expect(h.backend.api.cancelled, isEmpty); + }); + }); + + group('while a scan is pending', () { + test('receive, invoice, finalize and repost are refused at once', () async { + final api = await startScan(); + await storeHistory([ + entryOf(id: 3, state: GrinSlateState.s3, hasStoredTx: true), + ]); + const wait = 'Wait for the Grin wallet to finish scanning'; + + final received = await h.wallet.receiveSlatepack('s1'); + expect(received.success, isFalse); + expect(received.error, contains(wait)); + + final invoice = await h.wallet.issueInvoice(amount: grin(5)); + expect(invoice.success, isFalse); + expect(invoice.error, contains(wait)); + + for (final result in [ + await h.wallet.finalizeSlatepack('s2'), + await h.wallet.finalizeInvoice('i2'), + ]) { + expect(result.success, isFalse); + expect(result.error, contains(wait)); + } + + final repost = await failure(h.wallet.repost('slate-1')); + expect(repost.message, contains(wait)); + + for (final call in [ + 'receiveSlatepack', + 'issueInvoice', + 'finalizeSlatepack', + 'finalizeInvoice', + 'repost', + ]) { + expect(api.calls, isNot(contains(call))); + } + }); + + test('a Slatepack only the wallet can read says to wait', () async { + final api = await startScan(); + h.backend.decodeError = grinError(11); + final e = await failure( + h.wallet.inspectSlatepack('BEGINSLATEPACK. x ENDSLATEPACK.'), + ); + expect(e.message, contains('while the Grin wallet is scanning')); + expect(api.calls, isNot(contains('decodeSlatepack'))); + }); + }); + + test( + 'receive and invoice are refused while the network is blocked', + () async { + await h.wallet.init(); + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.disconnected; + + final received = await h.wallet.receiveSlatepack('s1'); + expect(received.success, isFalse); + expect(received.error, contains('Tor is not connected')); + final invoice = await h.wallet.issueInvoice(amount: grin(5)); + expect(invoice.success, isFalse); + expect(invoice.error, contains('Tor is not connected')); + + final api = h.backend.api; + expect(api.calls, isNot(contains('receiveSlatepack'))); + expect(api.calls, isNot(contains('issueInvoice'))); + }, + ); + + test( + 'a refresh that changes a transaction tells whoever watches it', + () async { + await h.wallet.init(); + await storeHistory([entryOf(id: 1)]); + final seen = []; + final watch = isar.transactionV2s + .where() + .txidWalletIdEqualTo('slate-1', h.wallet.walletId) + .watch() + .listen((rows) => seen.addAll(rows.map(h.wallet.slatepackTxInfo))); + addTearDown(watch.cancel); + expect(h.wallet.slatepackTxInfo(await storedTx())!.canRepost, isFalse); + + await storeHistory([ + entryOf(id: 1, state: GrinSlateState.s3, hasStoredTx: true), + ]); + await eventually(() => seen.isNotEmpty); + expect(seen.last!.canRepost, isTrue); + expect(seen.last!.canShowSlatepack, isFalse); + }, + ); + + group('cancelling a self-send', () { + Future selfSend() => storeHistory([ + entryOf(id: 1, debited: 1000, credited: 400, fee: 10), + entryOf( + id: 2, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 590, + fee: null, + ), + ]); + + test('goes on to the second entry when the first is gone', () async { + await h.wallet.init(); + await selfSend(); + final api = h.backend.api; + for (final code in [12, 13]) { + api.cancelled.clear(); + api.cancelErrors[1] = grinError(code); + expect(await h.wallet.cancelPendingTransactionAndPost('slate-1'), ''); + expect(api.cancelled, [(txId: 2, slateId: null)], reason: '$code'); + } + }); + + test('fails when neither entry could be cancelled', () async { + await h.wallet.init(); + await selfSend(); + final api = h.backend.api; + api.cancelErrors[1] = grinError(13); + api.cancelErrors[2] = grinError(12); + final result = await h.wallet.cancelPendingTransactionAndPost('slate-1'); + expect(result, isNotEmpty); + expect(result, isNot(contains(remoteText))); + expect(api.cancelled, isEmpty); + }); + }); + + group('Tor starting to connect over a direct connection', () { + Future settle() => pumpEventQueue(times: 50); + + void torConnecting() { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connecting; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connecting, ''), + ); + } + + test('turns the network off until Tor is up', () async { + await h.wallet.init(); + h.wallet.shouldAutoSync = true; + final api = h.backend.api; + + torConnecting(); + await settle(); + final hold = api.networkUpdates.single; + expect(hold.networkEnabled, isFalse); + expect(hold.socksProxy, isNull); + expect(refreshedAfter('updateNetwork'), isFalse); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await settle(); + expect(api.networkUpdates, hasLength(2)); + expect(api.networkUpdates.last.socksProxy, '127.0.0.1:9050'); + expect(api.networkUpdates.last.networkEnabled, isTrue); + await eventually(() => refreshedAfter('updateNetwork')); + }); + + test('stops a running scan, which goes on through Tor', () async { + final api = await startScan(); + h.wallet.shouldAutoSync = true; + api.cancelScannedHeight = 1500; + + torConnecting(); + await settle(); + expect(api.calls, containsAllInOrder(['cancelScan', 'updateNetwork'])); + expect(api.networkUpdates.single.networkEnabled, isFalse); + expect(api.scanRunning, isFalse); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await eventually(() => api.calls.contains('scan:1501:false')); + final proxied = api.calls.lastIndexOf('updateNetwork'); + expect(api.calls.indexOf('scan:1501:false'), greaterThan(proxied)); + expect(api.networkUpdates.last.socksProxy, '127.0.0.1:9050'); + }); + + test('a hold over a proxy or a block changes nothing', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + await h.wallet.init(); + final api = h.backend.api; + torConnecting(); + h.bus.fire(TorPreferenceChangedEvent(status: TorStatus.enabled)); + await settle(); + expect(api.networkUpdates, isEmpty); + }); + }); +} diff --git a/test/wallets/grin/grin_tx_mapping_test.dart b/test/wallets/grin/grin_tx_mapping_test.dart index a6a0fb2a44..b4b0603ee8 100644 --- a/test/wallets/grin/grin_tx_mapping_test.dart +++ b/test/wallets/grin/grin_tx_mapping_test.dart @@ -181,6 +181,30 @@ void main() { ); }); + test('a self-send with one half cancelled is not cancelled yet', () { + GrinTxLogEntry received(GrinTxType type) => entryOf( + id: 2, + type: type, + state: GrinSlateState.s2, + credited: 590, + fee: null, + counterparty: own, + ); + final sent = entryOf( + id: 1, + type: GrinTxType.txSentCancelled, + debited: 1000, + credited: 400, + counterparty: own, + ); + final half = map([sent, received(GrinTxType.txReceived)]).single; + expect(od(half)[TxV2OdKeys.isCancelled], isFalse); + expect(label(half), isNot('Cancelled')); + final both = map([sent, received(GrinTxType.txReceivedCancelled)]).single; + expect(od(both)[TxV2OdKeys.isCancelled], isTrue); + expect(label(both), 'Cancelled'); + }); + test('confirmed', () { expect( label( diff --git a/test/wallets/mimblewimble_slate_inspection_test.dart b/test/wallets/mimblewimble_slate_inspection_test.dart index e10418c0e0..224dcc57ed 100644 --- a/test/wallets/mimblewimble_slate_inspection_test.dart +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -80,10 +80,15 @@ class _LocalLookupWallet extends MimblewimblecoinWallet { } class _PendingLookupWallet extends _LocalLookupWallet { - _PendingLookupWallet({this.failPersistence = false}); + _PendingLookupWallet({ + this.failPersistence = false, + this.keepLiveMetadataStale = false, + }); final bool failPersistence; + final bool keepLiveMetadataStale; Map metadata = {}; + Map? persistedMetadata; @override Map get slatepackTransactionMetadata => metadata; @@ -93,7 +98,8 @@ class _PendingLookupWallet extends _LocalLookupWallet { Map metadata, ) async { if (failPersistence) throw StateError('persistence unavailable'); - this.metadata = metadata; + persistedMetadata = metadata; + if (!keepLiveMetadataStale) this.metadata = metadata; } Future remember(SlatepackResult result) => @@ -101,6 +107,11 @@ class _PendingLookupWallet extends _LocalLookupWallet { Future rememberCancelled(String slateId) => rememberPendingSlateCancelled(slateId); + + Future rememberBroadcast(String slateId, bool posted) => + rememberSlateBroadcastStatus(slateId, posted); + + bool? broadcastStatus(String slateId) => slateBroadcastStatus(slateId); } void main() { @@ -369,6 +380,47 @@ void main() { expect(epicFinalizeBroadcastResult(false), isFalse); }); + test('an observed broadcast survives stale or unwritable metadata', () async { + final wallet = _PendingLookupWallet(keepLiveMetadataStale: true) + ..metadata = { + 'slate': {'broadcastPosted': false}, + }; + + expect(wallet.broadcastStatus('slate'), isFalse); + + await wallet.rememberBroadcast('slate', true); + + expect( + (wallet.persistedMetadata!['slate'] as Map)['broadcastPosted'], + isTrue, + ); + expect( + (wallet.metadata['slate'] as Map)['broadcastPosted'], + isFalse, + reason: 'the open wallet still has its pre-write WalletInfo snapshot', + ); + expect( + wallet.broadcastStatus('slate'), + isTrue, + reason: 'the status observed in this process must remain authoritative', + ); + + final unwritable = _PendingLookupWallet(failPersistence: true) + ..metadata = { + 'slate': {'broadcastPosted': false}, + }; + + await unwritable.rememberBroadcast('slate', true); + + expect( + unwritable.broadcastStatus('slate'), + isTrue, + reason: + 'a completed native post must not leave Cancel enabled merely ' + 'because its best-effort metadata write failed', + ); + }); + test( 'ownership remains local when durable metadata cannot be written', () async { diff --git a/test/wallets/support/grin_fakes.dart b/test/wallets/support/grin_fakes.dart index 9468a590ee..8daa85de2e 100644 --- a/test/wallets/support/grin_fakes.dart +++ b/test/wallets/support/grin_fakes.dart @@ -83,10 +83,21 @@ class FakeGrinWalletApi implements GrinWalletApi { Object? estimateError; Object? sendError; Object? scanError; + Object? finalizeError; + Object? invoiceError; + Object? repostError; + Object? verifyError; + + /// Fails a cancel by log id, or by slate id under the key -1. + final cancelErrors = {}; + + /// The fee initSend reports, if not the estimate's. + BigInt? sendFee; /// Fails the next close once; the wallet stays open. Object? closeError; GrinSlateInfo? decoded; + final reposts = <({int? txId, String? slateId})>[]; int lastScanned = 0; int cancelScannedHeight = 0; @@ -252,7 +263,7 @@ class FakeGrinWalletApi implements GrinWalletApi { _check('initSend'); if (sendError != null) throw sendError!; initSends.add(args); - return slatepackOf(GrinSlateState.s1, amount: args.amount); + return slatepackOf(GrinSlateState.s1, amount: args.amount, fee: sendFee); } @override @@ -283,6 +294,7 @@ class FakeGrinWalletApi implements GrinWalletApi { bool fluff = false, }) async { _check('finalizeSlatepack'); + if (finalizeError != null) throw finalizeError!; return finalizedOf(); } @@ -299,6 +311,7 @@ class FakeGrinWalletApi implements GrinWalletApi { ) async { _check('processInvoice'); invoicePayments.add(args); + if (invoiceError != null) throw invoiceError!; return slatepackOf(GrinSlateState.i2); } @@ -309,17 +322,22 @@ class FakeGrinWalletApi implements GrinWalletApi { bool fluff = false, }) async { _check('finalizeInvoice'); + if (finalizeError != null) throw finalizeError!; return finalizedOf(); } @override Future repost({int? txId, String? slateId, bool fluff = false}) async { _check('repost'); + if (repostError != null) throw repostError!; + reposts.add((txId: txId, slateId: slateId)); } @override Future cancelTransaction({int? txId, String? slateId}) async { _check('cancelTransaction'); + final error = cancelErrors[txId ?? -1]; + if (error != null) throw error; cancelled.add((txId: txId, slateId: slateId)); } @@ -344,6 +362,7 @@ class FakeGrinWalletApi implements GrinWalletApi { GrinPaymentProof proof, ) async { _check('verifyPaymentProof'); + if (verifyError != null) throw verifyError!; return const GrinPaymentProofVerification( isSender: true, isRecipient: false, @@ -392,17 +411,20 @@ GrinBalance balanceOf({ refreshedFromNode: true, ); -GrinSlatepack slatepackOf(GrinSlateState state, {BigInt? amount}) => - GrinSlatepack( - slateId: 'slate-${state.wireName}', - state: state, - armoredSlatepack: 'BEGINSLATEPACK. secret ENDSLATEPACK.', - amount: amount ?? BigInt.zero, - fee: GrinBigInts.fee, - sender: 'grin1sender', - recipients: const [], - isEncrypted: false, - ); +GrinSlatepack slatepackOf( + GrinSlateState state, { + BigInt? amount, + BigInt? fee, +}) => GrinSlatepack( + slateId: 'slate-${state.wireName}', + state: state, + armoredSlatepack: 'BEGINSLATEPACK. secret ENDSLATEPACK.', + amount: amount ?? BigInt.zero, + fee: fee ?? GrinBigInts.fee, + sender: 'grin1sender', + recipients: const [], + isEncrypted: false, +); GrinFinalizeResult finalizedOf() => GrinFinalizeResult( slateId: 'slate-S3', @@ -646,6 +668,11 @@ NodeModel grinNode({ /// A [GrinWallet] wired to fakes and an in-memory set of services. class GrinTestWallet extends GrinWallet { + bool mobileScanLifecycle = false; + + @override + bool get cancelScanOnPause => mobileScanLifecycle; + GrinTestWallet({ required this.testWalletId, required FakeGrinBackend backend, @@ -784,6 +811,7 @@ GrinTxLogEntry entryOf({ bool hasStoredTx = false, String? armored, int? ttl, + GrinPaymentProofSummary? proof, }) => GrinTxLogEntry( id: id, slateId: slateId, @@ -802,7 +830,7 @@ GrinTxLogEntry entryOf({ kernelExcess: kernelExcess, kernelLookupMinHeight: confirmed ? 1 : null, hasStoredTx: hasStoredTx, - paymentProof: null, + paymentProof: proof, counterpartyAddress: counterparty, armoredSlatepack: armored, revertedAfterSecs: null,