diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index 7e1326c909..49f52dd7cc 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -163,6 +163,9 @@ class _ConfirmTransactionViewState final terms = wallet.slatepackTerms; final recipient = widget.txData.recipients!.first; final note = onChainNoteController.text; + final localNote = noteController.text; + final db = ref.read(mainDBProvider); + final format = ref.read(pAmountFormatter(wallet.cryptoCurrency)).format; final result = await wallet.createSlatepack( amount: recipient.amount, @@ -173,11 +176,77 @@ class _ConfirmTransactionViewState throw Exception(result.error ?? "Failed to create ${terms.noun}"); } + // The user confirmed one amount, so a slate for any other amount must not + // be handed over. + final createdAmount = result.amount; + if (createdAmount != null && createdAmount != recipient.amount) { + final slateId = result.slateId; + final cancelError = slateId == null + ? "it has no slate id" + : await wallet.cancelPendingTransactionAndPost(slateId); + final outcome = cancelError.isEmpty + ? "The transaction was cancelled." + : "The transaction could not be cancelled ($cancelError). Cancel it" + " from its details before trying again."; + throw Exception( + "The ${terms.noun} was created for ${format(createdAmount)} instead of" + " the confirmed ${format(recipient.amount)}. $outcome", + ); + } + + // The confirmed fee is an estimate and the wallet may pick other inputs + // when it builds the slate, so a different fee is reported, not refused. + final createdFee = result.fee; + final confirmedFee = widget.txData.fee; + final feeChange = + createdFee != null && confirmedFee != null && createdFee != confirmedFee + ? "The ${terms.noun} pays a fee of ${format(createdFee)} instead of" + " the estimated ${format(confirmedFee)}." + : null; + if (feeChange != null) { + Logging.instance.w("$feeChange Slate id: ${result.slateId}"); + } + + var noteSaved = localNote.isEmpty; + if (!noteSaved && result.slateId != null) { + try { + await db.putTransactionNote( + TransactionNote( + walletId: walletId, + txid: result.slateId!, + value: localNote, + ), + ); + noteSaved = true; + } catch (_) { + // The slate already exists and still needs to reach the recipient. + } + } + unawaited(wallet.refresh()); closeSendingDialog(); if (context.mounted) { + if (!noteSaved || feeChange != null) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: [ + ?feeChange, + if (!noteSaved) + "Transaction created, but the local note could not be saved.", + ].join(" "), + context: context, + ), + ); + } await showSlatepackDialog(context: context, terms: terms, result: result); + } else { + Logging.instance.w( + "Created ${terms.noun} ${result.slateId} but the confirmation view" + " closed before it could be shown. The pending transaction is in the" + " wallet's history and can be cancelled there.", + ); } widget.onSuccess.call(); @@ -195,33 +264,33 @@ class _ConfirmTransactionViewState final coin = wallet.info.coin; final sendProgressController = ProgressAndSuccessController(); - var isSendingDialogOpen = true; + + // Looked up now so the dialog can still be closed if this view is gone by + // the time the send returns. + final navigator = Navigator.of(context, rootNavigator: true); + + // The dialog's own route is kept so that closing it removes that route + // and nothing else, whatever is on top of it by then. + final sendingRoute = DialogRoute( + context: context, + useSafeArea: false, + barrierDismissible: false, + themes: InheritedTheme.capture(from: context, to: navigator.context), + builder: (context) { + return SendingTransactionDialog( + coin: coin, + controller: sendProgressController, + ); + }, + ); void closeSendingDialog() { - if (!context.mounted || !isSendingDialogOpen) { - return; - } - final navigator = Navigator.of(context, rootNavigator: true); - if (navigator.canPop()) { - navigator.pop(); + if (navigator.mounted && sendingRoute.isActive) { + 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), - ); + unawaited(navigator.push(sendingRoute)); final time = Future.delayed(const Duration(milliseconds: 2500)); @@ -334,9 +403,8 @@ class _ConfirmTransactionViewState } } } on BadHttpAddressException catch (_) { + closeSendingDialog(); if (context.mounted) { - // pop building dialog - closeSendingDialog(); unawaited( showFloatingFlushBar( type: FlushBarType.warning, @@ -348,12 +416,15 @@ class _ConfirmTransactionViewState return; } } catch (e, s) { - const message = "Broadcast transaction failed"; + // Nothing is broadcast when a slatepack is created. + final message = + wallet is SlatepackInterface && widget.txData.isSlatepackSend + ? "Could not create the ${wallet.slatepackTerms.noun}" + : "Broadcast transaction failed"; Logging.instance.e(message, error: e, stackTrace: s); // pop sending dialog + closeSendingDialog(); if (context.mounted) { - closeSendingDialog(); - await showDialog( context: context, useSafeArea: false, diff --git a/lib/pages/slatepack/slatepack_dialog.dart b/lib/pages/slatepack/slatepack_dialog.dart index 5a8dc27583..47260064f6 100644 --- a/lib/pages/slatepack/slatepack_dialog.dart +++ b/lib/pages/slatepack/slatepack_dialog.dart @@ -118,10 +118,20 @@ class SlatepackDialog extends StatelessWidget { } } - Future _share() async { + /// [context] is the Share button's. An iPad anchors the share sheet to the + /// button's rect and will not open it without one. + Future _share(BuildContext context) async { + final box = context.findRenderObject(); + final origin = box is RenderBox && box.hasSize + ? box.localToGlobal(Offset.zero) & box.size + : null; try { await SharePlus.instance.share( - ShareParams(text: slatepack, subject: title), + ShareParams( + text: slatepack, + subject: title, + sharePositionOrigin: origin, + ), ); } catch (e, s) { Logging.instance.e( @@ -250,10 +260,12 @@ class SlatepackDialog extends StatelessWidget { if (!isDesktop) ...[ const SizedBox(width: 12), Expanded( - child: SecondaryButton( - label: "Share", - icon: _icon(context, Assets.svg.share), - onPressed: _share, + child: Builder( + builder: (context) => SecondaryButton( + label: "Share", + icon: _icon(context, Assets.svg.share), + onPressed: () => _share(context), + ), ), ), ], diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index b6162bf558..a8d5927eda 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -4,9 +4,12 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; -import '../../utilities/show_loading.dart'; +import '../../utilities/amount/amount.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/logger.dart'; import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/custom_loading_overlay.dart'; import '../../widgets/stack_dialog.dart'; import 'slatepack_dialog.dart'; import 'slatepack_popup.dart'; @@ -57,6 +60,21 @@ abstract final class SlatepackImportFlow { SlateState.unknown => SlatepackRoute.unsupported, }; + static final _armored = RegExp( + r"BEGINSLATE(PACK|_BIN)\.[\s\S]*?ENDSLATE\1\.?", + ); + + /// The slatepack in [text] without what came along with it. A pasted or + /// scanned message often has a greeting, a quote or blank lines around the + /// armored slatepack, so only the part from its begin marker to its end + /// marker is kept. Text without such a frame, like a JSON slate, is only + /// trimmed. + static String normalize(String text) { + final trimmed = text.trim(); + if (trimmed.startsWith("{")) return trimmed; + return _armored.firstMatch(trimmed)?.group(0) ?? trimmed; + } + /// Returns true once the slatepack has been acted on, so the caller can /// clear its input. static Future run({ @@ -65,26 +83,63 @@ abstract final class SlatepackImportFlow { required String text, }) async { final terms = wallet.slatepackTerms; + final slatepack = normalize(text); - final inspection = await _withLoading( + final read = await _withLoading( context, "Reading ${terms.noun}...", - () => wallet.inspectSlatepack(text), + () async { + final inspection = await wallet.inspectSlatepack(slatepack); + final route = routeFor( + inspection.state, + supportsInvoices: wallet.supportsInvoices, + ); + return ( + inspection: inspection, + route: route, + // Only the wallet that started a send can finalize it. + local: route == SlatepackRoute.finalizeSend + ? await wallet.localTxForSlate(inspection.slateId) + : null, + ); + }, errorTitle: "Could not read ${terms.noun}", ); - if (inspection == null || !context.mounted) return false; + if (read == null || !context.mounted) return false; - final route = routeFor( - inspection.state, - supportsInvoices: wallet.supportsInvoices, - ); + final inspection = read.inspection; + final route = read.route; switch (route) { case SlatepackRoute.receive: - return _receive(context, wallet, text, inspection); + return _receive(context, wallet, slatepack, inspection); case SlatepackRoute.finalizeSend: - return _finalize(context, wallet, text, inspection); + final local = read.local; + if (local == null || !local.isSend) { + await _message( + context, + "Cannot finalize this ${terms.noun}", + local == null + ? "This wallet did not start the transaction this " + "${terms.noun} belongs to. Only the wallet that " + "started a send can finalize it. If the send was made " + "here moments ago, let the wallet finish syncing and " + "try again." + : "This ${terms.noun} belongs to a transaction this wallet " + "received, not one it started. Only the wallet that " + "started a send can finalize it.", + ); + return false; + } + return _finalize( + context, + wallet, + slatepack, + inspection, + amount: local.amount, + fee: local.fee, + ); case SlatepackRoute.payInvoice: // TODO(S5): PayInvoiceConfirmView. @@ -161,6 +216,10 @@ abstract final class SlatepackImportFlow { ); if (confirmed != true || !context.mounted) return false; + // Looked up before the wallet is asked, so the response can still be + // shown if the screen that started the import is gone by then. + final root = Navigator.of(context, rootNavigator: true); + final result = await _withLoading( context, "Processing ${terms.noun}...", @@ -173,10 +232,32 @@ abstract final class SlatepackImportFlow { }, errorTitle: "${terms.title} receive error", ); - if (result == null || !context.mounted) return false; + if (result == null) return false; unawaited(wallet.refresh()); - await showSlatepackDialog(context: context, terms: terms, result: result); + + // The transaction is received now and the sender cannot finalize it + // without the response, so the response is shown wherever it still can + // be. + if (context.mounted) { + await showSlatepackDialog(context: context, terms: terms, result: result); + } else if (root.mounted) { + Logging.instance.w( + "Received ${terms.noun} ${result.slateId} after the screen that " + "imported it had closed. Showing the response from the root " + "navigator.", + ); + await showSlatepackDialog( + context: root.context, + terms: terms, + result: result, + ); + } else { + Logging.instance.e( + "Received ${terms.noun} ${result.slateId} but there was nowhere left " + "to show the response.", + ); + } return true; } @@ -184,31 +265,26 @@ abstract final class SlatepackImportFlow { BuildContext context, SlatepackInterface wallet, String text, - SlateInspection inspection, - ) async { + SlateInspection inspection, { + required Amount amount, + required Amount fee, + }) async { final terms = wallet.slatepackTerms; - // An S2 may carry amount 0, so the summary comes from our own record of - // the send when there is one. - final local = await wallet.localTxForSlate(inspection.slateId); - if (!context.mounted) return false; - + // An S2 may carry amount 0, so the summary shows [amount] and [fee] from + // our own record of the send. final confirmed = await showSlatepackPopup( context: context, child: SlatepackSummaryDialog( title: "Finalize ${terms.noun}", coin: wallet.cryptoCurrency, actionLabel: "Finalize", - amount: local?.amount ?? inspection.amount, - fee: local?.fee ?? inspection.fee, + amount: amount, + fee: fee, details: [ if (inspection.slateId.isNotEmpty) ("Slate ID", inspection.slateId), ("Encrypted", inspection.isEncrypted ? "Yes" : "No"), ], - note: local == null - ? "No matching send was found in this wallet's history. " - "Finalizing only works for a send this wallet started." - : null, ), ); if (confirmed != true || !context.mounted) return false; @@ -225,10 +301,18 @@ abstract final class SlatepackImportFlow { }, errorTitle: "${terms.title} finalize error", ); - if (result == null || !context.mounted) return false; + if (result == null) return false; unawaited(wallet.refresh()); + if (!context.mounted) { + Logging.instance.w( + "Finalized ${terms.noun} ${inspection.slateId} after the screen that " + "imported it had closed. Broadcast: ${result.posted}.", + ); + return true; + } + if (result.posted) { unawaited( showFloatingFlushBar( @@ -256,26 +340,52 @@ abstract final class SlatepackImportFlow { Future Function() action, { required String errorTitle, }) async { - Exception? ex; - final result = await showLoading( - // Let the overlay open before the work starts, so an early error - // does not pop the wrong route. - whileFuture: Future.delayed(const Duration(milliseconds: 300)) - .then((_) => action()), + // The overlay is this flow's own route on the root navigator, so it can + // be taken down again even if the screen that started the import is gone + // by the time the wallet answers. + final root = Navigator.of(context, rootNavigator: true); + final overlayColor = Theme.of(context) + .extension()! + .overlay + .withValues(alpha: 0.6); + final overlay = DialogRoute( context: context, - message: message, - rootNavigator: true, - onException: (e) => ex = e, + barrierDismissible: false, + themes: InheritedTheme.capture(from: context, to: root.context), + builder: (_) => PopScope( + canPop: false, + child: Container( + color: overlayColor, + child: CustomLoadingOverlay(message: message, eventBus: null), + ), + ), ); + unawaited(root.push(overlay)); + + T? result; + Object? error; + try { + // Let the overlay paint before the wallet is asked. + await Future.delayed(const Duration(milliseconds: 300)); + result = await action(); + } catch (e, s) { + Logging.instance.w(errorTitle, error: e, stackTrace: s); + error = e; + } + + if (root.mounted && overlay.isActive) { + root.removeRoute(overlay); + } - if (ex != null || result == null) { + if (error != null || result == null) { + // An error is worth showing even after the importing screen closed. + final text = + error?.toString().replaceFirst("Exception: ", "") ?? + "Unexpected result without an error"; if (context.mounted) { - await _message( - context, - errorTitle, - ex?.toString().replaceFirst("Exception: ", "") ?? - "Unexpected result without an error", - ); + await _message(context, errorTitle, text); + } else if (root.mounted) { + await _message(root.context, errorTitle, text); } return null; } diff --git a/lib/pages/slatepack/slatepack_input_field.dart b/lib/pages/slatepack/slatepack_input_field.dart index 4afbe7c80e..154061f86a 100644 --- a/lib/pages/slatepack/slatepack_input_field.dart +++ b/lib/pages/slatepack/slatepack_input_field.dart @@ -55,6 +55,7 @@ class _SlatepackInputFieldState extends ConsumerState { bool get _isEmpty => widget.controller.text.isEmpty; void _set(String text) { + if (!mounted) return; widget.controller.text = text; widget.onChanged?.call(text); setState(() {}); diff --git a/lib/pages/slatepack/slatepack_qr.dart b/lib/pages/slatepack/slatepack_qr.dart index bb438c4bab..30442cf8a1 100644 --- a/lib/pages/slatepack/slatepack_qr.dart +++ b/lib/pages/slatepack/slatepack_qr.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/material.dart'; @@ -7,14 +8,13 @@ import '../../utilities/text_styles.dart'; import '../../widgets/qr.dart'; import '../../widgets/rounded_container.dart'; -/// Longest slatepack shown as a QR code. Measured armored Grin slatepacks -/// (characters): S1 360 plain, 806-955 encrypted; I1 348 plain, 719-855 -/// encrypted; S2 1837-2185; I2 1881-2068; S3 2683-2871. S1 and I1 fit one -/// QR at any error correction level, S2 and I2 only at L or M, so the cap -/// sits above S1/I1 and below S2/I2, which fall back to copy, share or save. -const kSlatepackQrMaxLength = 1000; +/// Most bytes one QR code holds: version 40 in byte mode at error correction +/// level L, which is the level [QR] draws at. Anything up to that is drawn. A +/// code near the limit is dense, and tapping it shows it full size. +const kSlatepackQrMaxBytes = 2953; -bool slatepackFitsQr(String text) => text.length <= kSlatepackQrMaxLength; +bool slatepackFitsQr(String text) => + utf8.encode(text).length <= kSlatepackQrMaxBytes; /// QR code for a slatepack, or a note when it is too long for one. Tapping /// the code shows it full size. diff --git a/lib/pages/slatepack/slatepack_summary_dialog.dart b/lib/pages/slatepack/slatepack_summary_dialog.dart index a13456bd5a..9f0435e82b 100644 --- a/lib/pages/slatepack/slatepack_summary_dialog.dart +++ b/lib/pages/slatepack/slatepack_summary_dialog.dart @@ -4,13 +4,11 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../themes/stack_colors.dart'; import '../../utilities/amount/amount.dart'; import '../../utilities/amount/amount_formatter.dart'; -import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; import '../../wallets/crypto_currency/crypto_currency.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 'slatepack_popup.dart'; @@ -25,7 +23,6 @@ class SlatepackSummaryDialog extends ConsumerWidget { this.amount, this.fee, this.details = const [], - this.note, }); final String title; @@ -37,9 +34,6 @@ class SlatepackSummaryDialog extends ConsumerWidget { /// Extra label and value rows shown under the amount and fee. final List<(String, String)> details; - /// Shown above the buttons, e.g. a warning. - final String? note; - @override Widget build(BuildContext context, WidgetRef ref) { final isDesktop = Util.isDesktop; @@ -72,17 +66,6 @@ class SlatepackSummaryDialog extends ConsumerWidget { ], ), ), - if (note != null) ...[ - const SizedBox(height: 16), - RoundedContainer( - color: colors.warningBackground, - child: Text( - note!, - style: STextStyles.label(context) - .copyWith(color: colors.warningForeground), - ), - ), - ], const SizedBox(height: 24), Row( children: [ diff --git a/lib/pages/slatepack/slatepack_view.dart b/lib/pages/slatepack/slatepack_view.dart index ba60a6f691..0ba05f7803 100644 --- a/lib/pages/slatepack/slatepack_view.dart +++ b/lib/pages/slatepack/slatepack_view.dart @@ -48,22 +48,33 @@ class _SlatepackViewState extends ConsumerState { late final FocusNode _focusNode; late final SlatepackInterface _wallet; + /// True while a slatepack is being imported, so a second press of Continue + /// cannot start the import again. + bool _importing = false; + bool get _hasText => _controller.text.trim().isNotEmpty; Future _continuePressed() async { - if (!Util.isDesktop && _focusNode.hasFocus) { - _focusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - if (!mounted) return; + if (_importing) return; + setState(() => _importing = true); + try { + if (!Util.isDesktop && _focusNode.hasFocus) { + _focusNode.unfocus(); + await Future.delayed(const Duration(milliseconds: 75)); + } + if (!mounted) return; - final done = await SlatepackImportFlow.run( - context: context, - wallet: _wallet, - text: _controller.text, - ); - if (done && mounted) { - setState(() => _controller.text = ""); + final done = await SlatepackImportFlow.run( + context: context, + wallet: _wallet, + text: _controller.text, + ); + if (done && mounted) { + setState(() => _controller.text = ""); + } + } finally { + _importing = false; + if (mounted) setState(() {}); } } @@ -133,7 +144,11 @@ class _SlatepackViewState extends ConsumerState { "Paste, scan or open a ${terms.noun} you were sent. It is " "received or finalized depending on what it is.", style: Util.isDesktop - ? STextStyles.desktopTextExtraSmall(context) + ? STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textSubtitle1, + ) : STextStyles.label(context), ), const SizedBox(height: 12), @@ -148,8 +163,8 @@ class _SlatepackViewState extends ConsumerState { PrimaryButton( label: "Continue", buttonHeight: Util.isDesktop ? ButtonHeight.l : null, - enabled: _hasText, - onPressed: _hasText ? _continuePressed : null, + enabled: _hasText && !_importing, + onPressed: _hasText && !_importing ? _continuePressed : null, ), if (!Util.isDesktop) SizedBox(height: Constants.size.standardPadding), ], 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 c629675f93..c792e140e1 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 @@ -1468,6 +1468,7 @@ class _TransactionV2DetailsViewState ), ), if (isSlatepackWallet && + _transaction.slateId != null && _transaction.getConfirmations(currentHeight) < 1 && _transaction.isCancelled == false) const SizedBox(height: 40), @@ -1478,6 +1479,7 @@ class _TransactionV2DetailsViewState floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: (isSlatepackWallet && + _transaction.slateId != null && _transaction.getConfirmations(currentHeight) < 1 && _transaction.isCancelled == false) ? ConditionalParent( @@ -1515,6 +1517,26 @@ class _TransactionV2DetailsViewState return; } + final proceed = await showDialog( + context: context, + builder: (context) => StackDialog( + title: "Cancel this transaction?", + message: + "The other party can no longer complete it, " + "and any funds it locked become spendable " + "again.", + leftButton: SecondaryButton( + label: "Keep", + onPressed: () => Navigator.of(context).pop(false), + ), + rightButton: PrimaryButton( + label: "Cancel transaction", + onPressed: () => Navigator.of(context).pop(true), + ), + ), + ); + if (proceed != true || !context.mounted) return; + unawaited( showDialog( barrierDismissible: false, @@ -1569,7 +1591,7 @@ class _TransactionV2DetailsViewState } }, child: Text( - "Cancel Transaction", + "Cancel transaction", style: STextStyles.button(context), ), ), diff --git a/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart b/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart index de2abe8ce3..e57b9e3bb3 100644 --- a/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart +++ b/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart @@ -233,28 +233,60 @@ abstract class MimblewimbleWallet extends Bip39Wallet with SlatepackInterface { } @override - Future<({Amount amount, Amount fee})?> localTxForSlate(String slateId) async { + Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( + String slateId, + ) async { if (slateId.isEmpty) return null; - final List candidates = await mainDB.isar.transactionV2s - .where() - .walletIdEqualTo(walletId) - .filter() - .otherDataContains(slateId) - .findAll(); + Future find() async => localTxMatching( + await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .filter() + .otherDataContains(slateId) + .findAll(), + slateId, + ); - for (final TransactionV2 tx in candidates) { - if (tx.slateId != slateId) continue; - final int digits = cryptoCurrency.fractionDigits; - final Amount amount = tx.type == TransactionType.incoming - ? tx.getAmountReceivedInThisWallet(fractionDigits: digits) - : tx.getAmountSentFromThisWallet( + TransactionV2? tx = await find(); + if (tx == null) { + // The stored history only changes on a refresh, and a refresh is + // skipped while another one runs, so a send made moments ago may not be + // in it yet. + await updateTransactions(); + tx = await find(); + } + if (tx == null) return null; + + final int digits = cryptoCurrency.fractionDigits; + final bool isSend = tx.type == TransactionType.outgoing; + return ( + amount: isSend + ? tx.getAmountSentFromThisWallet( fractionDigits: digits, subtractFee: true, - ); - return (amount: amount, fee: tx.getFee(fractionDigits: digits)); + ) + : tx.getAmountReceivedInThisWallet(fractionDigits: digits), + fee: tx.getFee(fractionDigits: digits), + isSend: isSend, + ); + } + + /// The transaction for [slateId] among [candidates]. A wallet that sent to + /// itself holds both sides of the slate, and then the send is the one + /// returned. + @visibleForTesting + static TransactionV2? localTxMatching( + Iterable candidates, + String slateId, + ) { + TransactionV2? match; + for (final TransactionV2 tx in candidates) { + if (tx.slateId != slateId) continue; + if (tx.type == TransactionType.outgoing) return tx; + match ??= tx; } - return null; + return match; } // ================= Native wallet hooks ===================================== diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart index 7b19c01461..5b2b2cbcfe 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -37,9 +37,12 @@ mixin SlatepackInterface on Wallet { /// Throws when the text cannot be decoded at all. Future inspectSlatepack(String armored); - /// Amount and fee of this wallet's transaction for [slateId], or null when - /// the wallet has none. - Future<({Amount amount, Amount fee})?> localTxForSlate(String slateId); + /// Amount, fee and direction of this wallet's transaction for [slateId], or + /// null when the wallet has none. `isSend` is true for a send this wallet + /// started, which is the only kind it can finalize. + Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( + String slateId, + ); /// Start a send (S1). [message] is dropped when [supportsOnChainNote] is /// false. [recipientAddress] encrypts the slatepack to that address where diff --git a/test/pages/send_view/slatepack_confirmation_test.dart b/test/pages/send_view/slatepack_confirmation_test.dart new file mode 100644 index 0000000000..c40dc7db61 --- /dev/null +++ b/test/pages/send_view/slatepack_confirmation_test.dart @@ -0,0 +1,382 @@ +import 'dart:async'; +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/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/models/slatepack_models.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/slatepack/slatepack_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/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/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +class _Info extends Fake implements WalletInfo { + _Info(this.coin); + @override + final CryptoCurrency coin; +} + +class _Wallet extends EpiccashWallet { + _Wallet({ + this.createdAmount, + this.createdFee, + this.createError, + this.cancelResult = '', + this.gate, + }) : super(CryptoCurrencyNetwork.main); + + /// What the created slate reports, in raw units. + final int? createdAmount; + final int? createdFee; + + final String? createError; + final String cancelResult; + + /// When set, creation waits for it. + final Completer? gate; + + int created = 0; + final cancelled = []; + + @override + WalletInfo get info => _Info(cryptoCurrency); + @override + Future refresh({bool doScan = true}) async {} + @override + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + bool sendAll = false, + }) async { + created++; + await gate?.future; + if (createError != null) { + return SlatepackResult(success: false, error: createError); + } + return SlatepackResult( + success: true, + slatepack: '{}', + slateId: 'slate-1', + state: SlateState.s1, + amount: createdAmount == null ? null : _amount(createdAmount!), + fee: createdFee == null ? null : _amount(createdFee!), + ); + } + + @override + Future cancelPendingTransactionAndPost(String txSlateId) async { + cancelled.add(txSlateId); + return cancelResult; + } +} + +/// Outlasts the minimum time the sending dialog is meant to stay up. +const _sendTimer = Duration(seconds: 3); + +Amount _amount(int raw) => + Amount(rawValue: BigInt.from(raw), fractionDigits: 8); + +AmountFormatter _formatter(CryptoCurrency coin) => AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: coin.fractionDigits, +); + +/// Pumps the confirmation of a slate send of 100 with a fee of 1 and presses +/// Send. [shown] takes the view off screen when set to false. +Future _confirmSend( + WidgetTester tester, + _Wallet wallet, { + MainDB? db, + void Function()? onSuccess, + ValueNotifier? shown, +}) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final view = ConfirmTransactionView( + walletId: 'wallet-1', + onSuccess: onSuccess ?? () {}, + onSuccessInsteadOfRouteOnSuccess: () {}, + txData: TxData( + note: 'local note', + fee: _amount(1), + recipients: [ + TxRecipient( + address: '', + amount: _amount(100), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + otherData: slatepackMethodOtherData(SlatepackMethod.slatepack), + ), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + mainDBProvider.overrideWithValue(db ?? _Notes(fail: false)), + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletCoin('wallet-1').overrideWithValue(coin), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue(_formatter(coin)), + ], + child: MaterialApp( + theme: ThemeData(extensions: [StackColors.fromStackColorTheme(theme)]), + home: Scaffold( + body: shown == null + ? view + : ValueListenableBuilder( + valueListenable: shown, + builder: (_, isShown, _) => isShown ? view : const SizedBox(), + ), + ), + ), + ), + ); + 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); +} + +class _Notes extends Fake implements MainDB { + _Notes({required this.fail}); + final bool fail; + final notes = []; + @override + Future putTransactionNote(TransactionNote note) async { + if (fail) throw StateError('note unavailable'); + notes.add(note); + } +} + +void main() { + for (final failNote in [false, true]) { + testWidgets('slate send keeps its result with note failure=$failNote', ( + tester, + ) async { + final wallet = _Wallet(); + final notes = _Notes(fail: failNote); + var succeeded = false; + await _confirmSend( + tester, + wallet, + db: notes, + onSuccess: () => succeeded = true, + ); + await tester.pumpAndSettle(); + expect(wallet.created, 1); + expect(find.byType(SlatepackDialog), findsOneWidget); + if (!failNote) { + expect(notes.notes, hasLength(1)); + expect(notes.notes.single.walletId, 'wallet-1'); + expect(notes.notes.single.txid, 'slate-1'); + expect(notes.notes.single.value, 'local note'); + } else { + expect(notes.notes, isEmpty); + } + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect(succeeded, isTrue); + await tester.pump(const Duration(seconds: 3)); + expect(tester.takeException(), isNull); + }); + } + + for (final cancelResult in ['', 'node unreachable']) { + testWidgets('a slate for another amount is cancelled and refused, cancel ' + 'result "$cancelResult"', (tester) async { + final wallet = _Wallet(createdAmount: 90, cancelResult: cancelResult); + final format = _formatter(wallet.cryptoCurrency).format; + final notes = _Notes(fail: false); + var succeeded = false; + await _confirmSend( + tester, + wallet, + db: notes, + onSuccess: () => succeeded = true, + ); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, ['slate-1']); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(find.text('Could not create the slate'), findsOneWidget); + expect( + find.textContaining( + 'created for ${format(_amount(90))} instead of the confirmed ' + '${format(_amount(100))}', + ), + findsOneWidget, + ); + expect( + find.textContaining( + cancelResult.isEmpty + ? 'The transaction was cancelled.' + : 'could not be cancelled (node unreachable)', + ), + findsOneWidget, + ); + expect(notes.notes, isEmpty); + expect(succeeded, isFalse); + await tester.pump(_sendTimer); + }); + } + + testWidgets('a slate with another fee is shown with a warning', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 3); + final format = _formatter(wallet.cryptoCurrency).format; + await _confirmSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, isEmpty); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect( + find.textContaining( + 'fee of ${format(_amount(3))} instead of the estimated ' + '${format(_amount(1))}', + ), + findsOneWidget, + ); + await tester.pump(const Duration(seconds: 10)); + await tester.pumpAndSettle(); + }); + + testWidgets('a slate matching the confirmation is shown without a warning', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 1); + await _confirmSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, isEmpty); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect(find.textContaining('instead of'), findsNothing); + await tester.pump(_sendTimer); + }); + + testWidgets('a failed creation is not called a broadcast failure', ( + tester, + ) async { + final wallet = _Wallet(createError: 'not enough funds'); + await _confirmSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(find.text('Could not create the slate'), findsOneWidget); + expect(find.text('Broadcast transaction failed'), findsNothing); + expect(find.textContaining('not enough funds'), findsOneWidget); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(wallet.cancelled, isEmpty); + await tester.pump(_sendTimer); + }); + + testWidgets('the sending dialog closes when the view is gone before the ' + 'slate is created', (tester) async { + final gate = Completer(); + final wallet = _Wallet(gate: gate); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + var succeeded = false; + await _confirmSend( + tester, + wallet, + shown: shown, + onSuccess: () => succeeded = true, + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(SendingTransactionDialog), findsOneWidget); + + shown.value = false; + await tester.pump(); + expect(find.byType(ConfirmTransactionView), findsNothing); + + gate.complete(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(find.byType(SlatepackDialog), findsNothing); + expect(succeeded, isTrue); + await tester.pump(_sendTimer); + expect(tester.takeException(), isNull); + }); + + testWidgets('closing the sending dialog leaves a route opened above it ' + 'alone', (tester) async { + final gate = Completer(); + final wallet = _Wallet(gate: gate); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + await _confirmSend(tester, wallet, shown: shown); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(SendingTransactionDialog), findsOneWidget); + + final root = Navigator.of( + tester.element(find.byType(SendingTransactionDialog)), + rootNavigator: true, + ); + unawaited( + root.push( + MaterialPageRoute(builder: (_) => const Text('opened above')), + ), + ); + shown.value = false; + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('opened above'), findsOneWidget); + + gate.complete(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('opened above'), findsOneWidget); + expect( + find.byType(SendingTransactionDialog, skipOffstage: false), + findsNothing, + ); + + root.pop(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('opened above'), findsNothing); + expect(find.byType(SendingTransactionDialog), findsNothing); + await tester.pump(_sendTimer); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/pages/slatepack/slatepack_dialog_test.dart b/test/pages/slatepack/slatepack_dialog_test.dart new file mode 100644 index 0000000000..74fd356693 --- /dev/null +++ b/test/pages/slatepack/slatepack_dialog_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.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/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/utilities/util.dart'; + +import '../../sample_data/theme_json.dart'; + +void main() { + testWidgets("Share anchors the share sheet to the Share button", ( + tester, + ) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + // Share is only offered on the phone layout. + final previousWidth = Util.screenWidth; + Util.screenWidth = 400; + addTearDown(() => Util.screenWidth = previousWidth); + + const channel = MethodChannel("dev.fluttercommunity.plus/share"); + final calls = []; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return ""; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SlatepackDialog( + terms: SlatepackTerms.slate, + slatepack: '{"slate": true}', + state: SlateState.s1, + slateId: "test-slate", + ), + ), + ), + ), + ); + + await tester.tap(find.text("Share")); + await tester.pump(); + + expect(calls, hasLength(1)); + final args = calls.single.arguments as Map; + expect(args["text"], '{"slate": true}'); + final origin = Rect.fromLTWH( + args["originX"] as double, + args["originY"] as double, + args["originWidth"] as double, + args["originHeight"] as double, + ); + expect(origin.isEmpty, isFalse); + expect(origin.contains(tester.getCenter(find.text("Share"))), isTrue); + expect( + (Offset.zero & tester.view.physicalSize).contains(origin.topLeft), + isTrue, + ); + }); +} diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 376642d50b..8a251cadce 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -1,40 +1,95 @@ +import 'dart:async'; +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/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/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/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/widgets/custom_loading_overlay.dart'; import '../../sample_data/theme_json.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}) - : super(CryptoCurrencyNetwork.main); + _InspectOnlyWallet( + this.state, { + this.invoices = false, + this.localIsSend, + this.receiveGate, + this.receiveError, + }) : super(CryptoCurrencyNetwork.main); + + /// When set, receiving waits for it and then succeeds, or throws + /// [receiveError] if that is set. + final Completer? receiveGate; + final Exception? receiveError; final SlateState state; final bool invoices; + + /// Direction of the wallet's own transaction for the slate. Null when the + /// wallet has none. + final bool? localIsSend; int receiveCalls = 0; int finalizeCalls = 0; @override bool get supportsInvoices => invoices; + /// What the flow handed to the wallet. + final seen = []; + + @override + Future inspectSlatepack(String armored) async { + seen.add(armored); + return SlateInspection(state: state, slateId: "test-slate"); + } + @override - Future inspectSlatepack(String armored) async => - SlateInspection(state: state, slateId: "test-slate"); + Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( + String slateId, + ) async => localIsSend == null + ? null + : ( + amount: Amount(rawValue: BigInt.from(100), fractionDigits: 8), + fee: Amount(rawValue: BigInt.one, fractionDigits: 8), + isSend: localIsSend!, + ); @override Future receiveSlatepack(String slatepack) async { receiveCalls++; - return SlatepackResult(success: false, error: "not in tests"); + if (receiveGate == null) { + return SlatepackResult(success: false, error: "not in tests"); + } + await receiveGate!.future; + if (receiveError != null) throw receiveError!; + return SlatepackResult( + success: true, + slatepack: '{"response": true}', + slateId: "test-slate", + state: SlateState.s2, + ); } + @override + Future refresh({bool doScan = true}) async {} + @override Future finalizeSlatepack(String slatepack) async { + seen.add(slatepack); finalizeCalls++; return FinalizeResult(success: false, error: "not in tests"); } @@ -110,32 +165,116 @@ void main() { expect(SlateState.fromCode(null), SlateState.unknown); }); + group("normalize", () { + const armored = + "BEGINSLATEPACK. 4H1qx1wHe668tFW yC2gfL8PPd8kSgv. " + "ENDSLATEPACK."; + + test("trims whitespace", () { + expect(SlatepackImportFlow.normalize(" \n$armored\r\n "), armored); + expect(SlatepackImportFlow.normalize(armored), armored); + }); + + test("drops text around the armored frame", () { + expect( + SlatepackImportFlow.normalize( + "Here is the slatepack:\n\n$armored\n\nSend it back soon.", + ), + armored, + ); + expect(SlatepackImportFlow.normalize("> $armored <"), armored); + }); + + test("keeps line breaks inside the frame", () { + const wrapped = + "BEGINSLATEPACK. 4H1qx1wHe668tFW\nyC2gfL8PPd8kSgv. ENDSLATEPACK."; + expect(SlatepackImportFlow.normalize("Hi\n$wrapped\nBye"), wrapped); + }); + + test("accepts the binary markers and a missing final period", () { + const binary = "BEGINSLATE_BIN. 4H1qx1wHe668tFW. ENDSLATE_BIN."; + expect(SlatepackImportFlow.normalize("x $binary y"), binary); + expect( + SlatepackImportFlow.normalize( + "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK", + ), + "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK", + ); + }); + + test("takes the first of two slatepacks", () { + expect(SlatepackImportFlow.normalize("$armored\n$armored"), armored); + }); + + test("leaves JSON slates alone apart from trimming", () { + const json = '{"id": "abc", "note": "BEGINSLATEPACK. x. ENDSLATEPACK."}'; + expect(SlatepackImportFlow.normalize(" $json\n"), json); + }); + + test("leaves other text alone apart from trimming", () { + expect( + SlatepackImportFlow.normalize(" not a slatepack "), + "not a slatepack", + ); + expect( + SlatepackImportFlow.normalize("BEGINSLATEPACK. cut off"), + "BEGINSLATEPACK. cut off", + ); + expect(SlatepackImportFlow.normalize(" "), ""); + }); + }); + group("run", () { Future runFlow( WidgetTester tester, - _InspectOnlyWallet wallet, - ) async { + _InspectOnlyWallet wallet, { + String text = "{}", + ValueNotifier? shown, + void Function(bool)? onDone, + }) async { bool? outcome; + shown ??= ValueNotifier(true); + final coin = wallet.cryptoCurrency; + // The loading overlay reads its indicator from the theme. + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); await tester.pumpWidget( - MaterialApp( - theme: ThemeData( - extensions: [ - StackColors.fromStackColorTheme( - StackTheme.fromJson(json: lightThemeJsonMap), + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: "en_US", + coin: coin, + maxDecimals: coin.fractionDigits, ), - ], - ), - home: Scaffold( - body: Builder( - builder: (context) => TextButton( - onPressed: () async { - outcome = await SlatepackImportFlow.run( - context: context, - wallet: wallet, - text: "{}", - ); - }, - child: const Text("go"), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: ValueListenableBuilder( + valueListenable: shown, + builder: (context, isShown, _) => !isShown + ? const SizedBox() + : Builder( + builder: (context) => TextButton( + onPressed: () async { + outcome = await SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: text, + ); + onDone?.call(outcome!); + }, + child: const Text("go"), + ), + ), ), ), ), @@ -176,6 +315,142 @@ void main() { await closeDialog(tester); }); + testWidgets("response to a send this wallet did not start", (tester) async { + final wallet = _InspectOnlyWallet(SlateState.s2); + await runFlow(tester, wallet); + expect(find.text("Cannot finalize this slate"), findsOneWidget); + expect( + find.textContaining("This wallet did not start the transaction"), + findsOneWidget, + ); + expect(find.text("Finalize"), findsNothing); + await closeDialog(tester); + expect(wallet.finalizeCalls, 0); + }); + + testWidgets("response to a transaction this wallet received", ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.s2, localIsSend: false); + await runFlow(tester, wallet); + expect(find.text("Cannot finalize this slate"), findsOneWidget); + expect( + find.textContaining("a transaction this wallet received"), + findsOneWidget, + ); + expect(find.text("Finalize"), findsNothing); + await closeDialog(tester); + expect(wallet.finalizeCalls, 0); + }); + + testWidgets("response to this wallet's own send can be finalized", ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.s2, localIsSend: true); + await runFlow(tester, wallet); + expect(find.text("Cannot finalize this slate"), findsNothing); + expect(find.text("Finalize slate"), findsOneWidget); + expect(find.text("0.00000100 EPIC"), findsOneWidget); + await tester.tap(find.text("Finalize")); + // Loading overlay delay, then the canned failure and its dialog. + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.finalizeCalls, 1); + await closeDialog(tester); + }); + + testWidgets("the wallet only sees the slatepack itself", (tester) async { + const armored = "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK."; + final wallet = _InspectOnlyWallet(SlateState.s2, localIsSend: true); + await runFlow(tester, wallet, text: "Here you go:\n$armored\nThanks\n"); + await tester.tap(find.text("Finalize")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + // Once for the inspection and once for the finalize. + expect(wallet.seen, [armored, armored]); + await closeDialog(tester); + }); + + testWidgets("the response is shown even if the importing screen closed " + "while the slate was received", (tester) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gate = Completer(); + final wallet = _InspectOnlyWallet(SlateState.s1, receiveGate: gate); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + bool? done; + await runFlow(tester, wallet, shown: shown, onDone: (v) => done = v); + expect(find.text("Receive slate"), findsOneWidget); + await tester.tap(find.text("Receive")); + // Summary closes, loading overlay delay, then the wallet is asked. + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.receiveCalls, 1); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + + shown.value = false; + await tester.pump(); + expect(find.text("go"), findsNothing); + + gate.complete(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect(find.text('{"response": true}'), findsOneWidget); + + await tester.tap(find.text("Done")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(done, isTrue); + // Nothing is left over the app once the response is closed. + expect( + find.byType(CustomLoadingOverlay, skipOffstage: false), + findsNothing, + ); + expect(find.byType(ModalBarrier), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets("an error is shown even if the importing screen closed " + "while the slate was received", (tester) async { + final gate = Completer(); + final wallet = _InspectOnlyWallet( + SlateState.s1, + receiveGate: gate, + receiveError: Exception("the slate was refused"), + ); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + bool? done; + await runFlow(tester, wallet, shown: shown, onDone: (v) => done = v); + await tester.tap(find.text("Receive")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.receiveCalls, 1); + + shown.value = false; + await tester.pump(); + gate.complete(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text("the slate was refused"), findsOneWidget); + expect( + find.byType(CustomLoadingOverlay, skipOffstage: false), + findsNothing, + ); + + await closeDialog(tester); + await tester.pump(const Duration(milliseconds: 400)); + expect(done, isFalse); + expect(tester.takeException(), isNull); + }); + testWidgets("invoice with invoice support is a placeholder", ( tester, ) async { diff --git a/test/pages/slatepack/slatepack_input_field_test.dart b/test/pages/slatepack/slatepack_input_field_test.dart new file mode 100644 index 0000000000..5104771e8c --- /dev/null +++ b/test/pages/slatepack/slatepack_input_field_test.dart @@ -0,0 +1,62 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_input_field.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/clipboard_interface.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; + +import '../../sample_data/theme_json.dart'; + +class _Clipboard extends Fake implements ClipboardInterface { + final response = Completer(); + + @override + Future getData(String format) => response.future; +} + +void main() { + testWidgets('paste completes after the input closes', (tester) async { + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final controller = TextEditingController(); + final clipboard = _Clipboard(); + final changes = []; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: SlatepackInputField( + controller: controller, + hint: 'Slatepack', + clipboard: clipboard, + onChanged: changes.add, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('slatepackPasteButton'))); + await tester.pumpWidget(const SizedBox.shrink()); + controller.dispose(); + clipboard.response.complete(const ClipboardData(text: 'slatepack')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(changes, isEmpty); + }); +} diff --git a/test/pages/slatepack/slatepack_qr_test.dart b/test/pages/slatepack/slatepack_qr_test.dart index c763ea648b..fde826e7bb 100644 --- a/test/pages/slatepack/slatepack_qr_test.dart +++ b/test/pages/slatepack/slatepack_qr_test.dart @@ -20,11 +20,32 @@ Widget _app(Widget child) => MaterialApp( void main() { test("length guard", () { - expect(slatepackFitsQr("a" * kSlatepackQrMaxLength), isTrue); - expect(slatepackFitsQr("a" * (kSlatepackQrMaxLength + 1)), isFalse); - // Measured Grin lengths: an encrypted S1 fits, an S2 does not. - expect(slatepackFitsQr("a" * 955), isTrue); - expect(slatepackFitsQr("a" * 1837), isFalse); + expect(slatepackFitsQr("a" * kSlatepackQrMaxBytes), isTrue); + expect(slatepackFitsQr("a" * (kSlatepackQrMaxBytes + 1)), isFalse); + // Bytes count, not characters. + expect(slatepackFitsQr("é" * (kSlatepackQrMaxBytes ~/ 2)), isTrue); + expect(slatepackFitsQr("é" * (kSlatepackQrMaxBytes ~/ 2 + 1)), isFalse); + }); + + testWidgets("the longest slatepack that fits is drawn", (tester) async { + await tester.pumpWidget( + _app(SlatepackQr(data: "a" * kSlatepackQrMaxBytes, noun: "slate")), + ); + await tester.pump(); + expect(find.byKey(const Key("slatepackQrCode")), findsOneWidget); + expect(find.byKey(const Key("slatepackQrTooLong")), findsNothing); + expect(find.text("Too much data to show as a QR code"), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets("a slate of a few thousand characters is drawn", (tester) async { + await tester.pumpWidget( + _app(SlatepackQr(data: '{"slate": "${"a" * 2400}"}', noun: "slate")), + ); + await tester.pump(); + expect(find.byKey(const Key("slatepackQrCode")), findsOneWidget); + expect(find.text("Too much data to show as a QR code"), findsNothing); + expect(tester.takeException(), isNull); }); testWidgets("short slatepack shows a QR code", (tester) async { @@ -52,7 +73,7 @@ void main() { testWidgets("long slatepack falls back to a note", (tester) async { await tester.pumpWidget( - _app(SlatepackQr(data: "a" * (kSlatepackQrMaxLength + 1), noun: "slate")), + _app(SlatepackQr(data: "a" * (kSlatepackQrMaxBytes + 1), noun: "slate")), ); expect(find.byType(QR), findsNothing); expect(find.byKey(const Key("slatepackQrTooLong")), findsOneWidget); diff --git a/test/pages/slatepack/slatepack_view_test.dart b/test/pages/slatepack/slatepack_view_test.dart new file mode 100644 index 0000000000..a24652c7c6 --- /dev/null +++ b/test/pages/slatepack/slatepack_view_test.dart @@ -0,0 +1,107 @@ +import 'dart:async'; +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/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_view.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/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +/// Epic Cash wallet whose inspection waits for [gate] and then reports a +/// finalized slate, which the import flow answers with a plain message. +class _SlowWallet extends EpiccashWallet { + _SlowWallet() : super(CryptoCurrencyNetwork.main); + + final gate = Completer(); + int inspections = 0; + + @override + Future inspectSlatepack(String armored) async { + inspections++; + await gate.future; + return const SlateInspection(state: SlateState.s3, slateId: "test-slate"); + } +} + +void main() { + testWidgets("Continue starts one import however often it is pressed", ( + tester, + ) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + // The phone layout closes the keyboard and waits a moment before it + // starts the import, which is when a second press can get in. + final previousWidth = Util.screenWidth; + Util.screenWidth = 400; + addTearDown(() => Util.screenWidth = previousWidth); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final wallet = _SlowWallet(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold(body: SlatepackView(walletId: "wallet-1")), + ), + ), + ); + await tester.pumpAndSettle(); + + PrimaryButton button() => + tester.widget(find.byType(PrimaryButton)); + + expect(button().enabled, isFalse); + await tester.enterText(find.byType(TextField), "{}"); + await tester.pump(); + expect(button().enabled, isTrue); + + // The second press lands before a frame has disabled the button, the + // third while the keyboard is still closing. + await tester.tap(find.text("Continue")); + await tester.tap(find.text("Continue"), warnIfMissed: false); + await tester.pump(const Duration(milliseconds: 20)); + expect(button().enabled, isFalse); + await tester.tap(find.text("Continue"), warnIfMissed: false); + + // Keyboard delay, loading overlay delay, then the inspection. + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.inspections, 1); + + wallet.gate.complete(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text("Already finalized"), findsOneWidget); + await tester.tap(find.text("OK")); + await tester.pump(const Duration(milliseconds: 400)); + + expect(wallet.inspections, 1); + // Nothing was acted on, so the text stays and Continue works again. + expect(find.text("{}"), findsOneWidget); + expect(button().enabled, isTrue); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/wallets/mimblewimble_slate_inspection_test.dart b/test/wallets/mimblewimble_slate_inspection_test.dart index 77f581e69f..0761fbe497 100644 --- a/test/wallets/mimblewimble_slate_inspection_test.dart +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -1,4 +1,8 @@ +import 'dart:convert'; + 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/transaction_v2.dart'; import 'package:stackwallet/models/slatepack_models.dart'; import 'package:stackwallet/utilities/enums/slatepack_method.dart'; import 'package:stackwallet/utilities/slatepack_terms.dart'; @@ -22,7 +26,36 @@ Map _slate({required int signatures, int participants = 2}) { }; } +TransactionV2 _tx(int n, TransactionType type, String slateId) => TransactionV2( + walletId: "wallet", + blockHash: null, + hash: "hash$n", + txid: "txid$n", + timestamp: 0, + height: null, + inputs: const [], + outputs: const [], + version: 0, + type: type, + subType: TransactionSubType.none, + otherData: jsonEncode({"slateId": slateId}), +); + void main() { + test("local transaction for a slate", () { + const id = "0436430c-2b02-624c-2032-570501212b00"; + final received = _tx(1, TransactionType.incoming, id); + final sent = _tx(2, TransactionType.outgoing, id); + // Contains the id without being the transaction for it. + final other = _tx(3, TransactionType.outgoing, "$id-other"); + + expect(MimblewimbleWallet.localTxMatching([other], id), isNull); + expect(MimblewimbleWallet.localTxMatching([other, received], id), received); + // A send to self holds both sides, and the send is what gets finalized. + expect(MimblewimbleWallet.localTxMatching([received, sent], id), sent); + expect(MimblewimbleWallet.localTxMatching([sent, received], id), sent); + }); + SlateInspection inspect( Map json, { String? sender,