diff --git a/README.md b/README.md index 70bf3f836..319c235d1 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Highlights include: - [Dogecoin](https://dogecoin.com/) - [Epic Cash](https://linktr.ee/epiccash) - [MimbleWimbleCoin](https://mwc.mw) + - [Grin](https://grin.mw/) - [Ethereum](https://ethereum.org/en/) - [Ecash](https://e.cash/) - [Fact0rn](https://www.fact0rn.io/) diff --git a/asset_sources/default_themes/stack_duo/dark.zip b/asset_sources/default_themes/stack_duo/dark.zip index a44c89cf8..e7cd9e064 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 82dc05870..9824e430c 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 a44c89cf8..e7cd9e064 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 82dc05870..9824e430c 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 d4c36814a..3b46ac33d 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'; @@ -359,11 +360,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); - final s2 = await bob.receiveSlatepack(s1); - expect(s2.state, GrinSlateState.s2); + expect(inspected.state, SlateState.s1); + expect(inspected.amount, grin(50)); + expect(inspected.senderAddress, aliceAddress); + final s2 = await bob.receiveSlatepack(inspected); + expect(s2.state, SlateState.s2); expect(s2.slateId, slateId); await sync(bob); @@ -378,7 +379,9 @@ void main() { expect(bob.info.cachedBalance.total, grin(0)); expect(bob.info.cachedBalance.spendable, grin(0)); - final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + final s3 = await alice.finalizeSlatepack( + await alice.inspectSlatepack(s2.slatepack!), + ); expect(s3.posted, isTrue); expect(s3.kernelExcess, hasLength(66)); // Posting mined height 16; ten more give it 11 confirmations. @@ -397,7 +400,7 @@ void main() { expect(data[TxV2OdKeys.grinPaymentProofLogId], isA()); 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); @@ -418,27 +421,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, @@ -447,47 +444,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('a send whose funds changed after review is refused', ( @@ -558,13 +555,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); @@ -573,7 +570,7 @@ void main() { // A second cancel is reported, not thrown. expect( - await alice.cancelPendingTransactionAndPost(slate.slateId), + await alice.cancelPendingTransactionAndPost(slate.slateId!), isNotEmpty, ); }, timeout: _timeout); @@ -589,20 +586,24 @@ 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( + await bob.inspectSlatepack(slate.slatepack!), + ); (await chain.api(alice)).skipNextBroadcast = true; - final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + final s3 = await alice.finalizeSlatepack( + await alice.inspectSlatepack(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), @@ -611,7 +612,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); @@ -624,13 +625,17 @@ 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( + await bob.inspectSlatepack(slate.slatepack!), + ); + final s3 = await alice.finalizeSlatepack( + await alice.inspectSlatepack(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); @@ -654,11 +659,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/integration_test/wallet_creation/coin_matrix.dart b/integration_test/wallet_creation/coin_matrix.dart index 8a051daf8..4cbec6b20 100644 --- a/integration_test/wallet_creation/coin_matrix.dart +++ b/integration_test/wallet_creation/coin_matrix.dart @@ -11,6 +11,7 @@ const defaultWordCounts = { 'ethereum': 12, 'fact0rn': 12, 'firo': 12, + 'grin': 24, 'litecoin': 12, 'mimblewimblecoin': 12, 'monero': 16, diff --git a/integration_test/wallet_creation/seed_validators.dart b/integration_test/wallet_creation/seed_validators.dart index cb8983b45..2ead3b49d 100644 --- a/integration_test/wallet_creation/seed_validators.dart +++ b/integration_test/wallet_creation/seed_validators.dart @@ -8,6 +8,7 @@ import 'package:stackwallet/services/wallets.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import 'package:stackwallet/wallets/wallet/intermediate/cryptonote_wallet.dart'; import 'package:stackwallet/wallets/wallet/intermediate/lib_xelis_wallet.dart'; @@ -31,6 +32,8 @@ Future verifyOpenNativeWallet(Wallet wallet, String expected) async { 0, await wallet.getMwcMqsConfig(), )).value; + } else if (wallet is GrinWallet) { + actual = await wallet.getNativeReceivingAddress(); } else if (wallet is LibXelisWallet) { wallet.checkInitialized(); actual = wallet.xelis.getAddress(wallet.wallet!); diff --git a/lib/models/slatepack_models.dart b/lib/models/slatepack_models.dart index 930dd8ea4..1b3d2ab78 100644 --- a/lib/models/slatepack_models.dart +++ b/lib/models/slatepack_models.dart @@ -38,12 +38,14 @@ class SlateInspection { final SlateState state; final String slateId; - /// Decoded slate passed to receive/finalize so an armored Slatepack is not - /// decoded over FFI a second time. + /// The slate as this wallet's receive/finalize take it. Epic Cash and MWC + /// store the decoded slate JSON so an armored Slatepack is not decoded over + /// FFI a second time; Grin's native API takes the armored Slatepack itself. final String slateJson; - /// Null when the slate does not carry it. MWC compact S2 slates decode with - /// 0; look the amount up with localTxForSlate instead. + /// Null when the slate does not carry it. MWC compact S2 slates and Grin + /// S2 and I2 slates decode with 0; look the amount up with localTxForSlate + /// instead. final Amount? amount; final Amount? fee; final String? senderAddress; @@ -175,3 +177,150 @@ 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's broadcast + /// of it failed: the node refused it or gave no usable answer. 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 confirm that it accepted this transaction. " + "Cancelling unlocks its funds in this wallet. If the node did " + "receive it, or it was posted somewhere else, it can still confirm, " + "and its change then only shows after a rescan."; + } 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/exchange_view/choose_address_from_stack_view.dart b/lib/pages/exchange_view/choose_address_from_stack_view.dart index c17c58b1a..c453ea0e1 100644 --- a/lib/pages/exchange_view/choose_address_from_stack_view.dart +++ b/lib/pages/exchange_view/choose_address_from_stack_view.dart @@ -19,6 +19,7 @@ import '../../utilities/constants.dart'; import '../../utilities/show_loading.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; +import '../../app_config.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; @@ -29,6 +30,15 @@ import '../../widgets/stack_dialog.dart'; import '../../widgets/wallet_info_row/sub_widgets/wallet_info_row_balance.dart'; import '../../widgets/wallet_info_row/sub_widgets/wallet_info_row_coin_icon.dart'; +/// Why no wallet of [coin] can give an address to an exchange, or null. +/// +/// Stack receives Grin by Slatepack only and runs no listener, so an +/// exchange cannot pay or refund to a Grin wallet's address. +String? exchangeAddressUnavailableReason(CryptoCurrency coin) => coin is Grin + ? "${AppConfig.prefix} receives Grin by Slatepack only, so an exchange " + "cannot pay to its Grin wallets." + : null; + class ChooseAddressFromStackView extends ConsumerStatefulWidget { const ChooseAddressFromStackView({super.key, required this.coin}); @@ -53,12 +63,15 @@ class _ChooseFromStackViewState @override Widget build(BuildContext context) { - final walletIds = ref - .watch(pWallets) - .wallets - .where((e) => e.info.coin == coin) - .map((e) => e.walletId) - .toList(); + final unavailable = exchangeAddressUnavailableReason(coin); + final walletIds = unavailable != null + ? [] + : ref + .watch(pWallets) + .wallets + .where((e) => e.info.coin == coin) + .map((e) => e.walletId) + .toList(); return Background( child: Scaffold( @@ -79,7 +92,8 @@ class _ChooseFromStackViewState RoundedWhiteContainer( child: Center( child: Text( - "No ${coin.ticker.toUpperCase()} wallets", + unavailable ?? + "No ${coin.ticker.toUpperCase()} wallets", style: STextStyles.itemSubtitle(context), ), ), @@ -210,9 +224,8 @@ class _WalletAddressSelectCardState return sparkAddress.value; } - return (await wallet.generateNextSparkAddress( - saveToDB: true, - )).value; + return (await wallet.generateNextSparkAddress(saveToDB: true)) + .value; } Exception? ex; diff --git a/lib/pages/receive_view/receive_view.dart b/lib/pages/receive_view/receive_view.dart index 40835684a..e372f4812 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'; @@ -83,6 +84,7 @@ class _ReceiveViewState extends ConsumerState { late bool supportsMweb; SlatepackTerms? _slatepackTerms; bool _importingSlatepack = false; + SlatepackInterface? _slatepackWallet; int _currentIndex = 0; @@ -296,6 +298,7 @@ class _ReceiveViewState extends ConsumerState { _supportsSpark = wallet is SparkInterface; if (wallet is SlatepackInterface) { _slatepackTerms = wallet.slatepackTerms; + _slatepackWallet = wallet; } supportsMweb = wallet is MwebInterface && @@ -695,6 +698,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", @@ -731,6 +741,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( @@ -739,34 +756,44 @@ 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), - CustomTextButton( - text: "Advanced options", - onTap: () async { - unawaited( - Navigator.of(context).push( - RouteGenerator.getRoute( - shouldUseMaterialRoute: - RouteGenerator.useMaterialPageRoute, - builder: (_) => GenerateUriQrCodeView( - coin: coin, - receivingAddress: address, - ), - settings: const RouteSettings( - name: GenerateUriQrCodeView.routeName, + // Its QR codes are payment URIs, which a coin + // with a bare address QR does not use. + if (!(_slatepackWallet?.receiveQrIsRawAddress ?? + false)) ...[ + const SizedBox(height: 20), + CustomTextButton( + text: "Advanced options", + onTap: () async { + unawaited( + Navigator.of(context).push( + RouteGenerator.getRoute( + shouldUseMaterialRoute: RouteGenerator + .useMaterialPageRoute, + builder: (_) => GenerateUriQrCodeView( + coin: coin, + receivingAddress: address, + ), + settings: const RouteSettings( + name: + GenerateUriQrCodeView.routeName, + ), ), ), - ), - ); - }, - ), + ); + }, + ), + ], ], ), ), diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index f045094c6..c04511872 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'; @@ -28,12 +29,16 @@ import '../../pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/deskt import '../../providers/providers.dart'; import '../../providers/wallet/public_private_balance_state_provider.dart'; import '../../route_generator.dart'; +import '../../services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import '../../services/event_bus/events/global/tor_status_changed_event.dart'; +import '../../services/event_bus/global_event_bus.dart'; import '../../themes/stack_colors.dart'; import '../../themes/theme_providers.dart'; import '../../utilities/amount/amount.dart'; import '../../utilities/amount/amount_formatter.dart'; import '../../utilities/amount/fee_rate_formatter.dart'; import '../../utilities/constants.dart'; +import '../../utilities/enums/slatepack_method.dart'; import '../../utilities/logger.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; @@ -45,6 +50,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 +68,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 +113,13 @@ class ConfirmTransactionView extends ConsumerStatefulWidget { class _ConfirmTransactionViewState extends ConsumerState { + // Direct (http) slatepack sends: transport warnings the user accepted. + bool _clearnetAck = false; + bool _plaintextAck = false; + // The transport policy depends on Tor, so the screen follows its changes. + StreamSubscription? _torStatusSub; + StreamSubscription? _torPrefSub; + late final String walletId; late final String routeOnSuccessName; late final bool isDesktop; @@ -235,6 +250,8 @@ class _ConfirmTransactionViewState noteOnChain: wallet.supportsOnChainNote ? onChainNoteController.text : null, + grinClearnetAcknowledged: _clearnetAck, + grinPlaintextAcknowledged: _plaintextAck, ), ); } else { @@ -306,6 +323,44 @@ 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. + } + } + 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 @@ -377,6 +432,11 @@ class _ConfirmTransactionViewState } }, ); + // The fee or amount on this screen is no longer what a send would + // be, so it goes back to the send form to be reviewed again. + if (e is GrinWalletException && e.termsChanged && context.mounted) { + Navigator.of(context).pop(); + } } } } @@ -401,10 +461,25 @@ class _ConfirmTransactionViewState onChainNoteController.text = widget.txData.noteOnChain ?? ""; _checkForOrdinalSpend(true); + + if (widget.txData.slatepackMethod == SlatepackMethod.http) { + void rebuild(_) { + if (mounted) setState(() {}); + } + + _torStatusSub = GlobalEventBus.instance + .on() + .listen(rebuild); + _torPrefSub = GlobalEventBus.instance + .on() + .listen(rebuild); + } } @override void dispose() { + unawaited(_torStatusSub?.cancel()); + unawaited(_torPrefSub?.cancel()); unawaited( _cancelPreparation().catchError((Object error, StackTrace stack) { Logging.instance.e( @@ -490,6 +565,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, @@ -1425,6 +1513,21 @@ class _ConfirmTransactionViewState ), ), ), + if (httpPolicy != null) + Padding( + padding: isDesktop + ? const EdgeInsets.symmetric(horizontal: 32, vertical: 8) + : const EdgeInsets.symmetric(vertical: 8), + child: SlatepackTransportWarnings( + policy: httpPolicy, + clearnetAck: _clearnetAck, + plaintextAck: _plaintextAck, + onClearnetAck: (value) => + setState(() => _clearnetAck = value), + onPlaintextAck: (value) => + setState(() => _plaintextAck = value), + ), + ), SizedBox(height: isDesktop ? 28 : 16), Padding( padding: isDesktop @@ -1433,6 +1536,7 @@ class _ConfirmTransactionViewState child: PrimaryButton( label: "Send", buttonHeight: isDesktop ? ButtonHeight.l : null, + enabled: sendAllowed, onPressed: () async { if (isDesktop) { final unlocked = await showDialog( diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 67ffe109c..9692a4266 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -57,6 +57,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/salvium_wallet.dart'; +import '../../wallets/wallet/wallet.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/coin_control_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; @@ -80,6 +81,7 @@ import '../../widgets/stack_text_field.dart'; import '../../widgets/textfield_icon_button.dart'; import '../address_book_views/address_book_view.dart'; import '../coin_control/coin_control_view.dart'; +import '../slatepack/slatepack_recipient_field.dart'; import '../slatepack/slatepack_send_flow.dart'; import 'confirm_transaction_view.dart'; import 'frost_ms/recipient.dart'; @@ -116,6 +118,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; @@ -708,9 +711,16 @@ class _SendViewState extends ConsumerState with SendFeeForm { Future _previewTransaction() async { if (_creatingSlatepack) return; var lockedSlatepack = false; - final earlyWallet = ref.read(pWallets).getWallet(walletId); - final earlySlatepack = - earlyWallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + // A Grin address on the Address tab is also a Slatepack recipient, so it + // takes the same manual flow as the Slatepack tab. + bool usesSlatepackFlow(Wallet wallet) => + wallet is SlatepackInterface && + (ref.read(pIsSlatepack(walletId)) || + wallet.manualSlatepackRecipientForAddress(_address ?? "") != null); + + final earlySlatepack = usesSlatepackFlow( + ref.read(pWallets).getWallet(walletId), + ); if (earlySlatepack) { _creatingSlatepack = true; lockedSlatepack = true; @@ -721,17 +731,28 @@ 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 isSlatepackSend = usesSlatepackFlow(wallet); if (isSlatepackSend != earlySlatepack) return; - if (isSlatepackSend) { + if (isSlatepackSend && wallet is SlatepackInterface) { if (modalRouteOfUnwatched(context)?.isCurrent != true) return; final Amount? amount = ref.read(pSendAmount); if (amount == null || amount <= Amount.zero) return; + // Slatepack mode hides the address field, so an address left in it + // must not choose the recipient. + final manualAddressRecipient = ref.read(pIsSlatepack(walletId)) + ? null + : wallet.manualSlatepackRecipientForAddress(_address ?? ""); + final slatepackRecipient = _slatepackRecipientController.text.trim(); final created = await SlatepackSendFlow.run( context: context, wallet: wallet, amount: amount, + recipientAddress: + manualAddressRecipient ?? + (wallet.supportsSlatepackRecipient && + slatepackRecipient.isNotEmpty + ? slatepackRecipient + : null), message: onChainNoteController.text, localNote: noteController.text, db: ref.read(mainDBProvider), @@ -1134,6 +1155,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { onChainNoteController.text = ""; feeController.text = ""; memoController.text = ""; + _slatepackRecipientController.text = ""; _address = ""; _addressToggleFlag = false; _clearRecipientForms(); @@ -1294,6 +1316,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { } sendToController.dispose(); + _slatepackRecipientController.dispose(); cryptoAmountController.dispose(); baseAmountController.dispose(); noteController.dispose(); @@ -1403,6 +1426,10 @@ class _SendViewState extends ConsumerState with SendFeeForm { ref.watch(pValidSendToAddress); } final slateNoun = _slatepackWallet?.slatepackTerms.noun; + final isManualSlatepackCreation = + isSlatepackMode || + _slatepackWallet?.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; @@ -1573,6 +1600,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: @@ -1672,8 +1709,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 { @@ -1695,7 +1736,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { style: STextStyles.field(context), decoration: standardInputDecoration( - "Enter ${coin.ticker} address", + _slatepackWallet + ?.directSendAddressHint ?? + "Enter ${coin.ticker} address", _addressFocusNode, context, ).copyWith( @@ -2446,7 +2489,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" @@ -2454,8 +2497,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( @@ -2463,7 +2508,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { style: STextStyles.itemSubtitle(context), ), ) - else if (hasFees) + else if (hasFees && !isManualSlatepackCreation) Stack( children: [ TextField( @@ -2627,7 +2672,8 @@ class _SendViewState extends ConsumerState with SendFeeForm { context, ), child: Text( - isSlatepackMode && slateNoun != null + isManualSlatepackCreation && + slateNoun != null ? "Create $slateNoun" : "Preview", style: STextStyles.button(context), 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 000000000..f6aba4fec --- /dev/null +++ b/lib/pages/send_view/sub_widgets/slatepack_transport_warnings.dart @@ -0,0 +1,134 @@ +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, + this.clearnetAck = false, + this.plaintextAck = false, + }); + + final SlatepackHttpPolicy policy; + + /// What the user already accepted, shown again when a warning that was + /// hidden comes back. + final bool clearnetAck; + final bool plaintextAck; + 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", + initialValue: clearnetAck, + 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", + initialValue: plaintextAck, + 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 e8690392a..ee75b1490 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 000000000..5493bd7e5 --- /dev/null +++ b/lib/pages/slatepack/pay_invoice_confirm_view.dart @@ -0,0 +1,445 @@ +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 loaded = await SlatepackImportFlow.withLoadingResult( + 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 (loaded == null) return; + final result = loaded.value; + final paid = result.success && result.slatepack != null; + final estimate = _estimatedFee; + final actual = result.fee; + final higherFee = + paid && estimate != null && actual != null && actual > estimate; + if (!loaded.canPresentResult || !mounted) { + // Nothing can be asked now, so a fee above the reviewed estimate is + // not kept. Any other payment stays in the wallet's history. + final slateId = result.slateId; + if (higherFee && slateId != null) { + unawaited(_cancelAbandonedPayment(slateId)); + } + return; + } + + if (!paid) { + // 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; + } + + if (higherFee) { + _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 000000000..b47b2e5da --- /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 000000000..eeff7b4f3 --- /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 c449c343a..a1d678452 100644 --- a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart +++ b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; import '../../themes/stack_colors.dart'; import '../../utilities/exception_message.dart'; @@ -24,10 +25,13 @@ bool canCancelSlateTransaction({ (slateId?.trim().isNotEmpty ?? false) && !isCancelled && confirmations < 1; /// Confirms, executes, and reports cancelling a pending slate transaction. +/// [prompt] explains what cancelling does for this transaction; the generic +/// wording is used when it is null. Future cancelSlatepackTransaction({ required BuildContext context, required Wallet wallet, required String? slateId, + SlatepackCancelPrompt? prompt, }) async { if (wallet is! SlatepackInterface) { unawaited( @@ -55,7 +59,9 @@ Future cancelSlatepackTransaction({ final proceed = await showDialog( context: context, - builder: (_) => const SlatepackCancelTransactionDialog(), + builder: (_) => prompt == null + ? const SlatepackCancelTransactionDialog() + : SlatepackCancelTransactionDialog(prompt: prompt), ); if (proceed != true || !context.mounted) return; @@ -102,7 +108,18 @@ Future cancelSlatepackTransaction({ } 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) { @@ -116,15 +133,14 @@ class SlatepackCancelTransactionDialog extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( - "Cancel this transaction?", + prompt.title, style: 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, ), @@ -137,7 +153,7 @@ class SlatepackCancelTransactionDialog extends StatelessWidget { ), const SizedBox(height: 8), PrimaryButton( - label: "Cancel it", + label: prompt.confirmLabel, buttonHeight: isDesktop ? ButtonHeight.l : null, 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 bde293145..e3c53e9cc 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -4,11 +4,18 @@ 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 '../../utilities/logger.dart'; import '../../utilities/slatepack_text.dart'; +import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.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'; @@ -21,6 +28,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, @@ -38,10 +51,20 @@ abstract final class SlatepackImportFlow { // database or application shutdown from holding an import screen forever. static const _historyLookupTimeout = 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, }; @@ -61,11 +84,16 @@ abstract final class SlatepackImportFlow { "Reading ${terms.noun}...", () async { final inspection = await wallet.inspectSlatepack(slatepack); - final route = routeFor(inspection.state); + final route = routeFor( + inspection.state, + supportsInvoices: wallet.supportsInvoices, + ); var historyLookupFailed = false; final needsLocalHistory = route == SlatepackRoute.receive || - route == SlatepackRoute.finalizeSend; + route == SlatepackRoute.finalizeSend || + route == SlatepackRoute.payInvoice || + route == SlatepackRoute.finalizeInvoice; Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> lookupLocal() async { @@ -194,6 +222,73 @@ abstract final class SlatepackImportFlow { historyLookupTimedOut: read.historyLookupFailed, ); + case SlatepackRoute.payInvoice: + if (read.historyLookupFailed) { + 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) { + await showMessage( + context, + "Cannot pay this invoice", + local.isSend + ? "This wallet has already paid 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.historyLookupFailed) { + 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, + inspection, + amount: local.amount, + fee: null, + historyWarning: false, + historyLookupTimedOut: false, + invoiceText: slatepack, + ); + case SlatepackRoute.invoicesUnsupported: await showSlatepackOkDialog( context: context, @@ -206,6 +301,21 @@ abstract final class SlatepackImportFlow { return false; case SlatepackRoute.alreadyFinalized: + 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 showSlatepackOkDialog( context: context, title: "Already finalized", @@ -331,8 +441,10 @@ abstract final class SlatepackImportFlow { required Amount? fee, required bool historyWarning, required bool historyLookupTimedOut, + String? invoiceText, }) async { final terms = wallet.slatepackTerms; + final invoice = invoiceText != null; final noValues = amount == null && fee == null; final String? warning; @@ -358,18 +470,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"), @@ -382,9 +496,11 @@ abstract final class SlatepackImportFlow { final loaded = await _withLoading( context, - "Finalizing ${terms.noun}...", + "Finalizing ${invoice ? "invoice" : terms.noun}...", () async { - final r = await wallet.finalizeSlatepack(inspection); + final r = invoice + ? await wallet.finalizeInvoice(invoiceText) + : await wallet.finalizeSlatepack(inspection); if (!r.success) { final error = r.error?.trim(); throw Exception( @@ -393,7 +509,9 @@ abstract final class SlatepackImportFlow { } return r; }, - errorTitle: "${terms.title} finalize error", + errorTitle: invoice + ? "Invoice finalize error" + : "${terms.title} finalize error", ); if (loaded == null) return false; final result = loaded.value; @@ -418,13 +536,10 @@ abstract final class SlatepackImportFlow { return true; } - await showSlatepackOkDialog( - context: dialogContext, - title: "Finalized, not broadcast", - message: - "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( + dialogContext, + wallet, + result.slateId ?? inspection.slateId, ); return true; } @@ -449,6 +564,165 @@ 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 Check the node connection and transaction history before " + "creating a replacement.", + ); + } + } + + /// 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 withLoadingResult( + context, + "Posting transaction...", + () async { + await wallet.repost(slateId); + return true; + }, + errorTitle: "Repost failed", + ); + if (done == null) return false; + // The repost went through even when the result cannot be shown. + if (!done.canPresentResult || !context.mounted) return true; + 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 for screens outside this flow. + /// Shows the error and returns null when it throws, and also returns null + /// when the result can no longer be shown because the overlay's route was + /// removed. + static Future withLoading( + BuildContext context, + String message, + Future Function() action, { + required String errorTitle, + }) async { + final loaded = await withLoadingResult( + context, + message, + action, + errorTitle: errorTitle, + ); + if (loaded == null) return null; + if (!loaded.canPresentResult) { + Logging.instance.w("$message finished after its overlay was removed."); + return null; + } + return loaded.value; + } + + /// Like [withLoading], but also returns a result that can no longer be + /// shown, for callers that have to act on it anyway. + static Future<({T value, bool canPresentResult})?> withLoadingResult( + BuildContext context, + String message, + Future Function() action, { + required String errorTitle, + }) => _withLoading(context, message, action, errorTitle: errorTitle); + + static Future showMessage( + BuildContext context, + String title, + String message, + ) => showSlatepackOkDialog(context: context, title: title, message: message); + /// Runs [action] under a loading overlay. Shows the error and returns null /// when it throws. static Future<({T value, bool canPresentResult})?> _withLoading( diff --git a/lib/pages/slatepack/slatepack_input_field.dart b/lib/pages/slatepack/slatepack_input_field.dart index f2d2c8655..8d6f8cda3 100644 --- a/lib/pages/slatepack/slatepack_input_field.dart +++ b/lib/pages/slatepack/slatepack_input_field.dart @@ -35,6 +35,7 @@ class SlatepackInputField extends ConsumerStatefulWidget { required this.controller, required this.hint, required this.terms, + this.inputName, this.onChanged, this.focusNode, this.clipboard = const ClipboardWrapper(), @@ -43,10 +44,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(); @@ -90,7 +94,7 @@ class _SlatepackInputFieldState extends ConsumerState { } } catch (e, s) { Logging.instance.w( - "Pasting ${widget.terms.noun} from clipboard failed", + "Pasting ${widget.inputNoun} from clipboard failed", error: e, stackTrace: s, ); @@ -117,7 +121,7 @@ class _SlatepackInputFieldState extends ConsumerState { } } catch (e, s) { Logging.instance.w( - "Scanning ${widget.terms.noun} QR failed", + "Scanning ${widget.inputNoun} QR failed", error: e, stackTrace: s, ); @@ -132,7 +136,7 @@ class _SlatepackInputFieldState extends ConsumerState { _busy = true; 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; @@ -141,7 +145,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.", ); } @@ -150,14 +154,14 @@ class _SlatepackInputFieldState extends ConsumerState { if (picked.bytes != null) { bytes = picked.bytes!; 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}."); } } else if (picked.path != null) { final builder = BytesBuilder(copy: false); await for (final chunk in File(picked.path!).openRead()) { builder.add(chunk); if (builder.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}."); } } bytes = builder.takeBytes(); @@ -174,7 +178,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 000000000..7f0c713b6 --- /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 e08b9cc94..bbbb5fb4a 100644 --- a/lib/pages/slatepack/slatepack_send_flow.dart +++ b/lib/pages/slatepack/slatepack_send_flow.dart @@ -13,7 +13,7 @@ import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import 'slatepack_dialog.dart'; import 'slatepack_popup.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 @@ -30,6 +30,7 @@ abstract final class SlatepackSendFlow { required BuildContext context, required SlatepackInterface wallet, required Amount amount, + String? recipientAddress, required String message, required String localNote, required MainDB db, @@ -47,6 +48,7 @@ abstract final class SlatepackSendFlow { action: () async { final created = await wallet.createSlatepack( amount: amount, + recipientAddress: recipientAddress, message: wallet.supportsOnChainNote && message.isNotEmpty ? message : null, 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 000000000..052fbea5c --- /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 120b99b25..46b51cf0b 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 && locked.raw > BigInt.zero) ...[ + 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 000000000..3bb1ff7c5 --- /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 3d11bb159..992bda170 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'; @@ -63,6 +64,7 @@ import '../../../slatepack/slatepack_cancel_transaction_dialog.dart'; import '../../sub_widgets/tx_icon.dart'; import '../edit_note_view.dart'; import 'boost_transaction_view.dart'; +import 'slatepack_tx_details.dart'; class TransactionV2DetailsView extends ConsumerStatefulWidget { const TransactionV2DetailsView({ @@ -100,9 +102,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; @@ -209,6 +240,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) && @@ -1450,6 +1484,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, @@ -1468,27 +1511,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( @@ -1514,6 +1544,16 @@ class _TransactionV2DetailsViewState context: context, wallet: ref.read(pWallets).getWallet(walletId), slateId: _transaction.slateId, + // Wallets without slate state keep the generic + // wording. + prompt: _slatepackInfo == null + ? null + : SlatepackCancelPrompt.of( + _slatepackInfo, + incoming: + _transaction.type == + TransactionType.incoming, + ), ); } finally { _cancelling = false; diff --git a/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_address_from_stack.dart b/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_address_from_stack.dart index 8eaf94991..187e8765b 100644 --- a/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_address_from_stack.dart +++ b/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_address_from_stack.dart @@ -14,6 +14,8 @@ import 'package:flutter_svg/svg.dart'; import 'package:tuple/tuple.dart'; import '../../../app_config.dart'; +import '../../../pages/exchange_view/choose_address_from_stack_view.dart' + show exchangeAddressUnavailableReason; import '../../../providers/providers.dart'; import '../../../providers/wallet/public_private_balance_state_provider.dart'; import '../../../themes/stack_colors.dart'; @@ -108,9 +110,9 @@ class _DesktopChooseFromStackState }); }, style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveText, + color: Theme.of(context) + .extension()! + .textFieldActiveText, height: 1.8, ), decoration: @@ -158,21 +160,23 @@ class _DesktopChooseFromStackState Flexible( child: Builder( builder: (context) { + final unavailable = exchangeAddressUnavailableReason(widget.coin); final wallets = ref .watch(pWallets) .wallets .where((e) => e.info.coin == widget.coin); - if (wallets.isEmpty) { + if (unavailable != null || wallets.isEmpty) { return Column( children: [ RoundedWhiteContainer( - borderColor: Theme.of( - context, - ).extension()!.background, + borderColor: Theme.of(context) + .extension()! + .background, child: Center( child: Text( - "No ${widget.coin.ticker.toUpperCase()} wallets", + unavailable ?? + "No ${widget.coin.ticker.toUpperCase()} wallets", style: STextStyles.desktopTextExtraExtraSmall( context, ), @@ -267,9 +271,9 @@ class _WalletRow extends ConsumerWidget { ref.watch(pWalletName(walletId)), style: STextStyles.desktopTextExtraExtraSmall(context) .copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ], 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 9120a2774..b63c8ab0e 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_view.dart'; import '../../../../providers/providers.dart'; import '../../../../providers/ui/preview_tx_button_state_provider.dart'; @@ -81,6 +82,7 @@ class _DesktopReceiveState extends ConsumerState { late final bool showMultiType; late final SlatepackTerms _slatepackTerms; late final TextEditingController? _receiveSlateController; + SlatepackInterface? _slatepackWallet; int _currentIndex = 0; @@ -276,6 +278,7 @@ class _DesktopReceiveState extends ConsumerState { _receiveSlateController = wallet is SlatepackInterface ? TextEditingController() : null; + _slatepackWallet = wallet is SlatepackInterface ? wallet : null; if (wallet is ViewOnlyOptionInterface && wallet.isViewOnly) { showMultiType = false; @@ -595,6 +598,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) @@ -613,94 +632,100 @@ 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, ), ), const SizedBox(height: 32), + // Its QR codes are payment URIs, which a coin with a bare address + // QR does not use. // TODO: create transparent button class to account for hover - GestureDetector( - onTap: () async { - if (Util.isDesktop) { - await showDialog( - context: context, - builder: (context) => DesktopDialog( - maxHeight: double.infinity, - maxWidth: 580, - child: Column( - children: [ - Row( - children: [ - const AppBarBackButton(size: 40, iconSize: 24), - Text( - "Generate QR code", - style: STextStyles.desktopH3(context), - ), - ], - ), - IntrinsicHeight( - child: Navigator( - onGenerateRoute: RouteGenerator.generateRoute, - onGenerateInitialRoutes: (_, __) => [ - RouteGenerator.generateRoute( - RouteSettings( - name: GenerateUriQrCodeView.routeName, - arguments: Tuple2(coin, address), - ), + if (!(_slatepackWallet?.receiveQrIsRawAddress ?? false)) + GestureDetector( + onTap: () async { + if (Util.isDesktop) { + await showDialog( + context: context, + builder: (context) => DesktopDialog( + maxHeight: double.infinity, + maxWidth: 580, + child: Column( + children: [ + Row( + children: [ + const AppBarBackButton(size: 40, iconSize: 24), + Text( + "Generate QR code", + style: STextStyles.desktopH3(context), ), ], ), - ), - ], - ), - ), - ); - } else { - unawaited( - Navigator.of(context).push( - RouteGenerator.getRoute( - shouldUseMaterialRoute: - RouteGenerator.useMaterialPageRoute, - builder: (_) => GenerateUriQrCodeView( - coin: coin, - receivingAddress: address, + IntrinsicHeight( + child: Navigator( + onGenerateRoute: RouteGenerator.generateRoute, + onGenerateInitialRoutes: (_, __) => [ + RouteGenerator.generateRoute( + RouteSettings( + name: GenerateUriQrCodeView.routeName, + arguments: Tuple2(coin, address), + ), + ), + ], + ), + ), + ], ), - settings: const RouteSettings( - name: GenerateUriQrCodeView.routeName, + ), + ); + } else { + unawaited( + Navigator.of(context).push( + RouteGenerator.getRoute( + shouldUseMaterialRoute: + RouteGenerator.useMaterialPageRoute, + builder: (_) => GenerateUriQrCodeView( + coin: coin, + receivingAddress: address, + ), + settings: const RouteSettings( + name: GenerateUriQrCodeView.routeName, + ), ), ), - ), - ); - } - }, - child: Container( - color: Colors.transparent, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - SvgPicture.asset( - Assets.svg.qrcode, - width: 14, - height: 16, - color: Theme.of(context) - .extension()! - .accentColorBlue, - ), - const SizedBox(width: 8), - Text( - "Create new QR code", - style: STextStyles.desktopTextExtraSmall(context).copyWith( + ); + } + }, + child: Container( + color: Colors.transparent, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SvgPicture.asset( + Assets.svg.qrcode, + width: 14, + height: 16, color: Theme.of(context) .extension()! .accentColorBlue, ), - ), - ], + const SizedBox(width: 8), + Text( + "Create new QR code", + style: STextStyles.desktopTextExtraSmall(context) + .copyWith( + color: Theme.of(context) + .extension()! + .accentColorBlue, + ), + ), + ], + ), ), ), - ), ], if (isSlatepackMode) SlatepackImportForm( 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 30df65a68..f2a4c5dbe 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'; @@ -109,6 +110,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 usesSlatepacks; bool _creatingSlatepack = false; + 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; @@ -254,8 +261,15 @@ 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)); + // Slatepack mode hides the address field, so an address left in it must + // not choose the recipient. + final manualAddressRecipient = selectedSlatepack + ? null + : slatepackWallet?.manualSlatepackRecipientForAddress(_address ?? ""); + final isSlatepackSend = selectedSlatepack || manualAddressRecipient != null; if (isSlatepackSend) { FocusScope.of(context).unfocus(); @@ -264,12 +278,21 @@ class _DesktopSendState extends ConsumerState { if (_creatingSlatepack) return; _creatingSlatepack = true; try { + final slatepackRecipient = _slatepackRecipientController.text.trim(); final created = await SlatepackSendFlow.run( context: context, - wallet: wallet, + wallet: slatepackWallet!, amount: amount, - message: "", - localNote: "", + recipientAddress: + manualAddressRecipient ?? + (slatepackWallet.supportsSlatepackRecipient && + slatepackRecipient.isNotEmpty + ? slatepackRecipient + : null), + // Slatepack mode hides the note fields; an address-tab send keeps + // any note that came with the address. + message: selectedSlatepack ? "" : _onChainNote ?? "", + localNote: selectedSlatepack ? "" : _note ?? "", db: ref.read(mainDBProvider), format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, ); @@ -279,7 +302,6 @@ class _DesktopSendState extends ConsumerState { } return; } - String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; @@ -730,6 +752,7 @@ class _DesktopSendState extends ConsumerState { baseAmountController.text = ""; memoController.text = ""; nonceController.text = ""; + _slatepackRecipientController.text = ""; _address = ""; _addressToggleFlag = false; _clearRecipientForms(); @@ -1397,6 +1420,7 @@ class _DesktopSendState extends ConsumerState { _feeAmount.dispose(); sendToController.dispose(); + _slatepackRecipientController.dispose(); cryptoAmountController.dispose(); baseAmountController.dispose(); memoController.dispose(); @@ -1484,6 +1508,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, @@ -1517,6 +1545,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 +1923,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); @@ -1909,7 +1953,7 @@ class _DesktopSendState extends ConsumerState { ), decoration: standardInputDecoration( - "Enter ${coin.ticker} address", + _directSendAddressHint ?? "Enter ${coin.ticker} address", _addressFocusNode, context, desktopMed: true, @@ -2278,7 +2322,7 @@ class _DesktopSendState extends ConsumerState { (!needsEthFee || ethFee != null); return PrimaryButton( buttonHeight: ButtonHeight.l, - label: isSlatepackMode && 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 ac01104ff..0c5f45181 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,12 @@ class _WDesktopWalletSummaryState extends ConsumerState { balanceToShow = _showAvailable ? balance.spendable : balance.total; } + // Funds held by unfinished slatepack sends, not in either balance. + final wallet = widget.isToken + ? null + : ref.watch(pWallets).getWallet(walletId); + final locked = wallet is SlatepackInterface ? wallet.amountLocked : null; + return Consumer( builder: (context, ref, __) { return Row( @@ -182,9 +189,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 ca6521ce0..cd9365f30 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,47 @@ 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, + colorFilter: ColorFilter.mode( + Theme.of(context) + .extension()! + .textFieldActiveSearchIconLeft, + BlendMode.srcIn, + ), + ), + 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/themes/theme_service.dart b/lib/themes/theme_service.dart index 04e32f6de..c5b09cbc3 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 b04d4ad00..1ee2a6880 100644 --- a/lib/utilities/address_utils.dart +++ b/lib/utilities/address_utils.dart @@ -265,6 +265,14 @@ class AddressUtils { 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/wallets/wallet/impl/grin_wallet.dart b/lib/wallets/wallet/impl/grin_wallet.dart index cfaf0402d..720b01e73 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'; @@ -36,10 +36,12 @@ import '../../../utilities/stack_file_system.dart'; import '../../../utilities/tor_plain_net_option_enum.dart'; import '../../../wl_gen/interfaces/libgrin_interface.dart'; import '../../crypto_currency/crypto_currency.dart'; +import '../../isar/models/wallet_info.dart'; 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'; @@ -93,7 +95,7 @@ typedef _AppliedNetwork = ({ GrinTransport transport, }); -class GrinWallet extends Bip39Wallet { +class GrinWallet extends Bip39Wallet with SlatepackInterface { GrinWallet( CryptoCurrencyNetwork network, { GrinWalletBackend? backend, @@ -269,6 +271,21 @@ class GrinWallet extends Bip39Wallet { _AppliedNetwork? _applied; final _transportMutex = Mutex(); + + /// One change of the stored Grin data at a time, so a slate record and a + /// scan checkpoint written together both land. + final _grinDataMutex = Mutex(); + + /// Applies [change] to the Grin data as stored now and saves the result. + /// A null result saves nothing. + Future _changeGrinData( + GrinWalletData? Function(GrinWalletData? stored) change, + ) => _grinDataMutex.protect(() async { + final stored = await mainDB.isar.walletInfo.get(info.id); + final next = change(stored == null ? info.grinData : stored.grinData); + if (next == null) return; + await info.updateGrinData(grinData: next, isar: mainDB.isar); + }); Completer? _torConnecting; StreamSubscription? _torStatusSub; StreamSubscription? _torPrefSub; @@ -284,6 +301,20 @@ 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. Whoever waits + /// for the recovery keeps waiting: the scan was paused, not given up. + void cancelRunningScan() { + if (_scanJob == null) return; + _resumeScan = true; + _api?.cancelScan(); + } + /// Whether the Tor feature is compiled in. @visibleForTesting bool get torFeatureEnabled => AppConfig.hasFeature(AppFeature.tor); @@ -293,6 +324,18 @@ class GrinWallet extends Bip39Wallet { bool get _scanPending => info.grinData?.pendingScanFrom != null; + @override + Map get slatepackTransactionMetadata => + info.grinData?.slatepackTransactions ?? const {}; + + @override + Future updateSlatepackTransactionMetadata( + Map metadata, + ) => _changeGrinData( + (stored) => + stored?.withSlatepackTransactions(Map.from(metadata)), + ); + /// Whether a scan has to finish before node refreshes, fee estimates, /// cancels and sends. bool get isScanPending => _scanPending; @@ -437,12 +480,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(); } @@ -511,6 +562,8 @@ class GrinWallet extends Bip39Wallet { } } _endRecovery(GrinWalletException("The Grin wallet was closed.")); + _localSyncRequested = false; + await _localSyncJob; await _releaseOwnership(); _api = null; _applied = null; @@ -688,12 +741,11 @@ class GrinWallet extends Bip39Wallet { await running; } - Future _markScanFromRestoreHeight() async { + Future _markScanFromRestoreHeight() { final height = info.restoreHeight; - await info.updateGrinData( - grinData: (info.grinData ?? GrinWalletData(creationHeight: height)) + return _changeGrinData( + (stored) => (stored ?? GrinWalletData(creationHeight: height)) .withPendingScanFrom(height), - isar: mainDB.isar, ); } @@ -759,13 +811,16 @@ class GrinWallet extends Bip39Wallet { } } + /// Saves a scan checkpoint, as a running scan does. + @visibleForTesting + Future debugSetPendingScanFrom(int? height) => + _setPendingScanFrom(height); + Future _setPendingScanFrom(int? height) async { try { - final current = info.grinData; - await info.updateGrinData( - grinData: (current ?? GrinWalletData(creationHeight: height ?? 0)) + await _changeGrinData( + (stored) => (stored ?? GrinWalletData(creationHeight: height ?? 0)) .withPendingScanFrom(height), - isar: mainDB.isar, ); } catch (e) { // The wallet may be gone after a delete. @@ -774,6 +829,7 @@ class GrinWallet extends Bip39Wallet { } Future _runScanJob() { + if (_pauseObserver?.isPaused ?? false) return Future.value(); final running = _scanJob; if (running != null) return running; // The rescan starts its own once it has marked where to scan from. @@ -839,6 +895,7 @@ class GrinWallet extends Bip39Wallet { } // Stopped before it started: nothing was scanned. if (_scanStop.isCompleted) return; + if (_pauseObserver?.isPaused ?? false) return; _scanInLibrary = true; try { await api.scan(startHeight: from); @@ -894,6 +951,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 @@ -1105,6 +1168,10 @@ class GrinWallet extends Bip39Wallet { /// so the change does not wait a whole batch. It starts again from its /// saved resume height once a transport is usable, also for a wallet that /// does not sync on its own. + /// + /// 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 { @@ -1241,8 +1308,21 @@ class GrinWallet extends Bip39Wallet { 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 =========================================================== @@ -1296,20 +1376,80 @@ 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; - await _storeTransactions(list, kernelLookup: fromNode && !_offline); + final api = refreshFromNode ? await _requireNetwork() : current; + final list = await api.getTransactions(refreshFromNode: refreshFromNode); + if (refreshFromNode) _offline = !list.refreshedFromNode; + await _storeTransactions( + list, + kernelLookup: refreshFromNode && !_offline, + ); } 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); + } + + /// After a call that failed but named a slate the library may hold a + /// transaction for it (inputs locked, or finalized but not posted). Its + /// history is copied before the error is shown, so the entry the error + /// names is in the list. Not awaited behind a scan, which holds the + /// wallet until it ends. + Future _syncAfterSlateError(Object error) async { + if (error is! GrinException || error.slateId == null || _exited) return; + _scheduleLocalWalletSync(); + final job = _localSyncJob; + if (job != null && _scanJob == null) await job; + } + /// Stores the library's history. With [kernelLookup], a confirmed entry /// that has no height from the library and none stored gets the height of /// the block holding its kernel from the node. The library only knows the @@ -1325,6 +1465,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() @@ -1394,15 +1538,16 @@ class GrinWallet extends Bip39Wallet { refreshFromNode: false, minimumConfirmations: cryptoCurrency.minConfirms, ); + _amountLocked = _amount(balance.amountLocked); final txs = await api.getTransactions(refreshFromNode: false); - await info.updateBalance( - newBalance: grinBalanceToStack( - balance, - cryptoCurrency.fractionDigits, - entries: txs.transactions, - ), - isar: mainDB.isar, + final mapped = grinBalanceToStack( + balance, + cryptoCurrency.fractionDigits, + entries: txs.transactions, ); + if (info.cachedBalance.toJsonIgnoreCoin() != mapped.toJsonIgnoreCoin()) { + await info.updateBalance(newBalance: mapped, isar: mainDB.isar); + } } catch (e) { throw _fail("updateBalance", e); } @@ -1444,14 +1589,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) { @@ -1491,26 +1642,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 @@ -1562,7 +1748,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) { @@ -1601,7 +1787,7 @@ class GrinWallet extends Bip39Wallet { expectedFee: expectedFee, expectedAmount: expectedAmount, ); - unawaited(refresh()); + _scheduleLocalWalletSync(); return txData.copyWith( txid: slatepack.slateId, slatepack: slatepack.armoredSlatepack, @@ -1609,55 +1795,65 @@ class GrinWallet extends Bip39Wallet { ); case SlatepackMethod.http: + // Nothing is awaited between this check and the send, so the + // transport that was checked is the one the send uses. final api = await _requireNetwork(); _checkHttpPolicy( address, 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, - expectedFee: expectedFee, - expectedAmount: expectedAmount, - ), - ); - unawaited(refresh()); + final GrinSendResult result; + try { + result = await api.sendHttp( + GrinHttpSendArgs( + amount: amount, + recipientUrlOrAddress: address, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + ttlBlocks: slatepackTtlBlocks, + post: true, + expectedFee: expectedFee, + expectedAmount: expectedAmount, + ), + ); + } on GrinSlateException catch (e) { + await _syncAfterSlateError(e); + throw _fail("sendHttp", e, message: _httpSendFailedMessage(e)); + } on GrinTransactionException catch (e) { + if (e.termsChanged) rethrow; + await _syncAfterSlateError(e); + throw _fail("sendHttp", e, message: _httpSendFailedMessage(e)); + } + _scheduleLocalWalletSync(); return txData.copyWith( txid: result.slateId, fee: _amount(result.fee), ); } } catch (e) { - await _storeHistoryAfterFailure(); - throw _fail("confirmSend", e); + await _syncAfterSlateError(e); + final failure = _fail("confirmSend", e); + if (failure is GrinWalletException && failure.finalizedNotBroadcast) { + // As after a finalize the node refused, so the details screen offers + // cancel as well as repost. + await rememberSlateBroadcastStatus(failure.slateId, false); + } + throw failure; } } - /// For a send-side call that failed. The library may already hold a - /// transaction for it (inputs locked, or a slate finalized but not - /// posted), so its history is stored before the error is shown and the - /// entry the error names is in the list. - Future _storeHistoryAfterFailure() async { - final api = _api; - if (api == null || _exited || _scanPending) return; - try { - await _storeTransactions( - await api.getTransactions(refreshFromNode: false), - ); - } catch (e) { - Logging.instance.w( - "Grin history not stored after a failed call: " - "${describeGrinError(e)}", - ); + /// The text for an HTTP send that failed a check. The recipient is named + /// only for an answer the library refused; nothing is locked then. + static String _httpSendFailedMessage(GrinException error) { + if (error.badAnswer && error.slateId == null) return grinBadAnswerMessage; + const failed = "The send 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."; } - unawaited(refresh()); + return "$failed Nothing was sent. $grinLeftPendingNote"; } Future _initSend({ @@ -1736,56 +1932,167 @@ 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 { + final prefix = cryptoCurrency.network == CryptoCurrencyNetwork.main + ? "grin1" + : "tgrin1"; + return "$prefix 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. + Future _finalizeFailure( + String operation, + Object error, { + required String notFoundMessage, + }) async { + await _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. The scan holds the /// native wallet until it ends, so during one a plain Slatepack is read /// without the wallet and an encrypted one is refused. - Future inspectSlatepack(String armored) async { + @override + Future inspectSlatepack(String armored) async { + final GrinSlateInfo info; try { - if (_scanPending) { - 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); + 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, + // grin_native receives and finalizes armored Slatepacks, so the + // inspection carries the text as imported. + slateJson: armored, + 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, + ); } - /// 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)); + Future _decode(String armored) async { + if (_scanPending) { + 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); } - /// Starts a Slatepack send and returns the S1. Locks the inputs. - /// - /// With [expectedFee], the fee the user reviewed, a send whose fee or net - /// amount comes out different is refused before anything is locked. - Future createSlatepack({ + /// 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. The read still queues + // behind other wallet calls, such as a refresh, so it is bounded to answer + // before the import flow gives up on the lookup. grin-wallet refuses an + // already received S1 or paid I1 by itself. + try { + await _updateTransactions(refreshFromNode: false) + .timeout(const Duration(seconds: 2)); + } 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. 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, - bool sendAll = false, - Amount? expectedFee, + String? message, }) async { try { final address = recipientAddress?.trim(); @@ -1796,76 +2103,112 @@ class GrinWallet extends Bip39Wallet { "A Slatepack can only be encrypted to a Grin address.", ); } - final fee = expectedFee == null ? null : _nano(expectedFee); final result = await _initSend( amount: _nano(amount), recipientAddress: (address?.isEmpty ?? true) ? null : address, - sendAll: sendAll, - expectedFee: fee, - expectedAmount: fee == null - ? null - : sendAll - ? _nano(amount) - fee - : _nano(amount), + sendAll: false, ); - unawaited(refresh()); - return result; + final slatepack = _result(result); + await rememberPendingSlateSend(slatepack); + _scheduleLocalWalletSync(); + return slatepack; } catch (e) { - await _storeHistoryAfterFailure(); - throw _fail("createSlatepack", e); + await _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(SlateInspection inspection) async { try { _refuseWhileScanning(); final api = await _requireNetwork(); - final result = await api.receiveSlatepack(s1); - unawaited(refresh()); - return result; + final result = await api.receiveSlatepack(inspection.slateJson); + final slatepack = _result(result); + await persistPendingSlateReceive(slatepack); + _scheduleLocalWalletSync(); + return slatepack; } catch (e) { - await _storeHistoryAfterFailure(); - throw _fail("receiveSlatepack", e); + await _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(SlateInspection inspection) async { try { _refuseWhileScanning(); final api = await _requireNetwork(); - final result = await api.finalizeSlatepack(s2); - unawaited(refresh()); - return result; + final result = await api.finalizeSlatepack(inspection.slateJson); + final finalized = _finalized(result); + await rememberSlateBroadcastStatus(finalized.slateId, finalized.posted); + _scheduleLocalWalletSync(); + return finalized; } catch (e) { - await _storeHistoryAfterFailure(); - throw _fail("finalizeSlatepack", e); + final failure = await _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 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(amount), recipientAddress: payerAddress), + GrinInvoiceArgs( + amount: nano, + recipientAddress: (payer?.isEmpty ?? true) ? null : payer, + ), ); - unawaited(refresh()); - return result; + final invoice = _result(result); + await persistPendingSlateReceive(invoice); + _scheduleLocalWalletSync(); + return invoice; } catch (e) { - await _storeHistoryAfterFailure(); - throw _fail("issueInvoice", e); + await _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 { @@ -1890,30 +2233,50 @@ class GrinWallet extends Bip39Wallet { expectedAmount: expected, ), ); - unawaited(refresh()); - return result; + final payment = _result(result); + await rememberPendingSlateSend(payment); + _scheduleLocalWalletSync(); + return payment; } catch (e) { - await _storeHistoryAfterFailure(); - throw _fail("processInvoice", e); + await _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) { - await _storeHistoryAfterFailure(); - throw _fail("finalizeInvoice", e); + final failure = await _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(); @@ -1922,18 +2285,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(); @@ -1941,6 +2310,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; @@ -1958,10 +2328,27 @@ 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); + var tx = await _storedTx(txid); + // A send that failed at the broadcast moments ago reaches the history + // through the sync that the failure started. + final pendingSync = _localSyncJob; + if (tx == null && pendingSync != null) { + await pendingSync; + tx = await _storedTx(txid); + } if (tx == null || !_otherDataFlag(tx, TxV2OdKeys.grinHasStoredTx)) { throw GrinWalletException("No finalized transaction is stored."); } @@ -1977,13 +2364,24 @@ class GrinWallet extends Bip39Wallet { 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); @@ -1991,7 +2389,9 @@ class GrinWallet extends Bip39Wallet { throw GrinWalletException("This transaction has no payment proof."); } _refuseWhileScanning(); - final owner = _decode(tx.otherData!)[TxV2OdKeys.grinPaymentProofLogId]; + final owner = _decodeOtherData( + tx.otherData!, + )[TxV2OdKeys.grinPaymentProofLogId]; final logIds = _logIds(tx); final proof = await _requireApi().exportPaymentProof( txId: owner is int ? owner : (logIds.isEmpty ? null : logIds.first), @@ -1999,29 +2399,88 @@ 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."); } _refuseWhileScanning(); 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) @@ -2030,16 +2489,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/supporting/grin/grin_errors.dart b/lib/wallets/wallet/supporting/grin/grin_errors.dart index ce396d2ea..42a3d9760 100644 --- a/lib/wallets/wallet/supporting/grin/grin_errors.dart +++ b/lib/wallets/wallet/supporting/grin/grin_errors.dart @@ -48,6 +48,11 @@ class GrinWalletException extends SWException { bool get leftPendingTransaction => slateId != null && !finalized && !released; } +/// Shown for an HTTP send that refused the recipient's answer. Nothing is +/// locked then. +const grinBadAnswerMessage = + "The recipient's answer failed checks. Nothing was sent or locked."; + /// Shown for a call that failed after the transaction was finalized. const grinFinalizedNotBroadcastMessage = "The transaction was finalized but the node did not accept it. " 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 000000000..dc5692eb7 --- /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 e74bb014d..3e37e4fc0 100644 --- a/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart +++ b/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart @@ -138,7 +138,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 f00885a2d..d3f98435f 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 87f8a39cc..ff6fca76f 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -26,6 +26,12 @@ mixin SlatepackInterface on Wallet { _pendingSlateTransactions = {}; final Set _cancelledSlateIds = {}; + // 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; @@ -40,6 +46,10 @@ mixin SlatepackInterface on Wallet { supportedMethods.length > 1 && supportedMethods.contains(SlatepackMethod.slatepack); + bool get supportsInvoices => false; + + bool get supportsPaymentProofs => false; + /// "slate" or "slatepack" wording for this coin. SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; @@ -55,7 +65,8 @@ mixin SlatepackInterface on Wallet { ) async {} /// 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. @@ -128,7 +139,7 @@ mixin SlatepackInterface on Wallet { final inMemory = _pendingSlateTransactions[id]; ({Amount amount, Amount fee, bool isSend, bool isCancelled})? pending; try { - pending = pendingSlateSendMatching( + pending = pendingSlateTransactionMatching( slatepackTransactionMetadata, id, fractionDigits: cryptoCurrency.fractionDigits, @@ -249,7 +260,20 @@ 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 durably, before native history is copied + /// into Isar. These are receives from this wallet's point of view. Wallets + /// that only need the in-memory guard use [rememberPendingSlateReceive]. + @protected + Future persistPendingSlateReceive(SlatepackResult result) => + _rememberPendingSlateTransaction(result, isSend: false); + + Future _rememberPendingSlateTransaction( + SlatepackResult result, { + required bool isSend, + }) async { final rawSlateId = result.slateId; final amount = result.amount; final fee = result.fee; @@ -262,7 +286,7 @@ mixin SlatepackInterface on Wallet { _pendingSlateTransactions[id] = ( amount: amount, fee: fee, - isSend: true, + isSend: isSend, isCancelled: false, ); @@ -275,7 +299,7 @@ mixin SlatepackInterface on Wallet { entry.addAll({ 'amount': amount.raw.toString(), 'fee': fee.raw.toString(), - 'isSend': true, + 'isSend': isSend, 'isCancelled': false, }); metadata[match.key] = entry; @@ -332,7 +356,7 @@ mixin SlatepackInterface on Wallet { final match = _findMetadataEntry(metadata, slateId, id); final pending = inMemory ?? - pendingSlateSendMatching( + pendingSlateTransactionMatching( metadata, id, fractionDigits: cryptoCurrency.fractionDigits, @@ -346,9 +370,9 @@ mixin SlatepackInterface on Wallet { isCancelled: true, ); - // Only persist sends (or updates to existing entries); - // pendingSlateSendMatching reads send metadata, while receives persist in - // Isar. + // Only persist sends (or updates to existing entries). Receives are + // only in this map when the wallet persisted them; otherwise they + // persist in Isar. if (!pending.isSend && match.entry == null) return; final entry = match.entry != null @@ -370,6 +394,59 @@ 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 || posted == null) return; + final id = _normalizeSlateId(slateId); + if (id.isEmpty) return; + + _observedBroadcastStatuses[id] = posted; + + try { + final metadata = Map.from(slatepackTransactionMetadata); + final match = _findMetadataEntry(metadata, slateId, id); + final entry = match.entry != null + ? Map.from(match.entry!) + : {}; + entry['broadcastPosted'] = posted; + metadata[match.key] = entry; + 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) return null; + final id = _normalizeSlateId(slateId); + if (id.isEmpty) return null; + final observed = _observedBroadcastStatuses[id]; + if (observed != null) return observed; + try { + final raw = _findMetadataEntry( + slatepackTransactionMetadata, + slateId, + id, + ).entry; + return raw != null && raw['broadcastPosted'] is bool + ? raw['broadcastPosted'] as bool + : null; + } catch (_) { + return null; + } + } + /// State, id, amount and fee for a native slate JSON result. @protected SlateInspection? inspectSlateJsonString(String? slateJson) { @@ -404,6 +481,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. @@ -440,10 +578,11 @@ 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, @@ -460,7 +599,7 @@ pendingSlateSendMatching( break; } } - if (raw == null || raw['isSend'] != true) return null; + if (raw == null || raw['isSend'] is! bool) return null; final amount = BigInt.tryParse(raw['amount']?.toString() ?? ''); final fee = BigInt.tryParse(raw['fee']?.toString() ?? ''); @@ -469,11 +608,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/scripts/app_config/configure_stack_wallet.sh b/scripts/app_config/configure_stack_wallet.sh index 65e3d0cfb..f1299d773 100755 --- a/scripts/app_config/configure_stack_wallet.sh +++ b/scripts/app_config/configure_stack_wallet.sh @@ -111,6 +111,7 @@ final List _supportedCoins = List.unmodifiable([ Ethereum(CryptoCurrencyNetwork.main), Fact0rn(CryptoCurrencyNetwork.main), Firo(CryptoCurrencyNetwork.main), + Grin(CryptoCurrencyNetwork.main), Litecoin(CryptoCurrencyNetwork.main), Mimblewimblecoin(CryptoCurrencyNetwork.main), Nano(CryptoCurrencyNetwork.main), diff --git a/scripts/tests/wallet_creation_runner_test.dart b/scripts/tests/wallet_creation_runner_test.dart index 664254582..ffab5efe4 100644 --- a/scripts/tests/wallet_creation_runner_test.dart +++ b/scripts/tests/wallet_creation_runner_test.dart @@ -69,11 +69,11 @@ void main() { .map((line) => jsonDecode(line) as Map) .toList(); - test('the shared matrix covers the 24 base wallets and excludes FROST', () { - expect(defaultWordCounts, hasLength(24)); + test('the shared matrix covers the 25 base wallets and excludes FROST', () { + expect(defaultWordCounts, hasLength(25)); expect( defaultWordCounts.keys, - containsAll(['eCash', 'epicCash', 'monero', 'solana']), + containsAll(['eCash', 'epicCash', 'grin', 'monero', 'solana']), ); expect(defaultWordCounts, isNot(contains('bitcoinFrost'))); }); @@ -269,7 +269,7 @@ void main() { final suite = runner(omitCoin: 'xelis'); expect(await suite.run(options(['--device', 'linux', '--all-coins'])), 1); expect(suite.results.first['failure'], 'incomplete_results'); - expect(suite.results.first['completed_coins'], hasLength(23)); + expect(suite.results.first['completed_coins'], hasLength(24)); expect(await events(), hasLength(1)); }, ); diff --git a/test/address_utils_test.dart b/test/address_utils_test.dart index af615c5b5..d211b5fa6 100644 --- a/test/address_utils_test.dart +++ b/test/address_utils_test.dart @@ -454,4 +454,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 000000000..e63abcdfa --- /dev/null +++ b/test/pages/send_view/grin_confirmation_test.dart @@ -0,0 +1,396 @@ +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/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/services/event_bus/global_event_bus.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/supporting/grin/grin_errors.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 = []; + final broadcastStatuses = {}; + + @override + Future refresh() async {} + + @override + Future rememberSlateBroadcastStatus( + String? slateId, + bool? posted, + ) async => broadcastStatuses[slateId] = posted; + + @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() { + useGrinCoinConfig(); + 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), + // The send views always set a note. + note: '', + 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, + bool pushed = 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: Builder( + builder: (context) { + Widget confirm() => ConfirmTransactionView( + txData: txData, + walletId: h.walletId, + onSuccess: onSuccess ?? () {}, + onSuccessInsteadOfRouteOnSuccess: () {}, + ); + if (!pushed) return Scaffold(body: confirm()); + // Stands in for the send form the confirmation was opened from. + return Scaffold( + body: TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => Scaffold(body: confirm()), + ), + ), + child: const Text('Send form'), + ), + ); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + if (pushed) { + await tester.tap(find.text('Send form')); + 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('the warnings follow Tor while the screen is open', ( + tester, + ) async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.connecting; + await pumpConfirm(tester, direct('https://payee.example')); + expect(find.textContaining('Tor is not connected'), findsOneWidget); + + h.tor.current = TorConnectionStatus.connected; + GlobalEventBus.instance.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('Tor is not connected'), findsNothing); + expect(sendEnabled(tester), isTrue); + + // Tor off: the IP warning appears and has to be accepted. + h.prefs.tor = false; + GlobalEventBus.instance.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.disconnected, ''), + ); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('slatepackClearnetAck')), 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'); + expect(wallet.broadcastStatuses, {'slate-f': false}); + + await tester.tap(find.text('Later')); + await tester.pumpAndSettle(); + expect(wallet.reposted, isEmpty); + expect(succeeded, isTrue); + expect(tester.takeException(), isNull); + }); + + testWidgets('a send whose fee changed after review goes back to the send ' + 'form', (tester) async { + final wallet = _QuietWallet(h); + await tester.runAsync(wallet.init); + addTearDown(() async { + try { + await wallet.exit(); + } catch (_) {} + }); + // The wallet's funds changed since the review: a send now costs more. + h.backend.api.fee = GrinFeeEstimate( + fee: BigInt.from(31000000), + amount: BigInt.zero, + netAmount: BigInt.zero, + total: BigInt.zero, + inputsCount: 2, + changeOutputs: 1, + ); + var succeeded = false; + await pumpConfirm( + tester, + direct('https://payee.example'), + sender: wallet, + onSuccess: () => succeeded = true, + pushed: true, + ); + expect(find.byType(ConfirmTransactionView), findsOneWidget); + 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 (find.text('Broadcast transaction failed').evaluate().isNotEmpty) { + break; + } + } + + expect(find.textContaining(grinTermsChangedMessage), findsOneWidget); + expect(h.backend.api.httpSends, isEmpty); + await tester.tap(find.text('Ok')); + await tester.pumpAndSettle(); + expect(find.byType(ConfirmTransactionView), findsNothing); + expect(find.text('Send form'), findsOneWidget); + expect(succeeded, isFalse); + expect(tester.takeException(), isNull); + }); +} 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 000000000..266ac4f46 --- /dev/null +++ b/test/pages/send_view/grin_send_form_test.dart @@ -0,0 +1,244 @@ +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() { + useGrinCoinConfig(); + 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 2b50fbc07..3ea02c2e3 100644 --- a/test/pages/send_view/send_views_test.dart +++ b/test/pages/send_view/send_views_test.dart @@ -960,6 +960,123 @@ 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); + }, + ); + testWithoutAnimation( + "in Slatepack mode a manual-slate address left on the Address tab " + "does not pick the recipient ($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", + ); + ProviderScope.containerOf( + tester.element(find.byKey(view.addressField)), + ).read(pSelectedSlatepackMethod(wallet.walletId).notifier).state = + SlatepackMethod.slatepack; + await tester.pumpAndSettle(); + 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"); + }, + ); + } + 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 000000000..2b2a22996 --- /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 f6572599f..7169c2c0b 100644 --- a/test/pages/send_view/support/fake_wallets.dart +++ b/test/pages/send_view/support/fake_wallets.dart @@ -301,6 +301,7 @@ class FakeEpiccashWallet extends FakeWallet int slateCreates = 0; String? lastMessage; + String? requestedSlateRecipient; @override Future createSlatepack({ @@ -310,6 +311,7 @@ class FakeEpiccashWallet extends FakeWallet }) async { slateCreates++; lastMessage = message; + requestedSlateRecipient = recipientAddress; return SlatepackResult( success: true, slatepack: '{"id":"test-slate","amount":"${amount.raw}"}', @@ -333,13 +335,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; +} + /// MWC checking only transport prefixes, as tests lack its native library. class TestMimblewimblecoin extends Mimblewimblecoin { TestMimblewimblecoin() : super(CryptoCurrencyNetwork.main); @@ -387,9 +407,18 @@ 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; + @override + String? get directSendAddressHint => null; + @override SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; } diff --git a/test/pages/slatepack/desktop_receive_slatepack_test.dart b/test/pages/slatepack/desktop_receive_slatepack_test.dart index 0d57c27ff..3b6303274 100644 --- a/test/pages/slatepack/desktop_receive_slatepack_test.dart +++ b/test/pages/slatepack/desktop_receive_slatepack_test.dart @@ -37,6 +37,14 @@ class _Wallet extends EpiccashWallet { WalletInfo get info => _info; } +/// As a Grin wallet: its receive QR is the bare address. +class _RawQrWallet extends _Wallet { + _RawQrWallet(super._info); + + @override + bool get receiveQrIsRawAddress => true; +} + class _Wallets extends Fake implements Wallets { _Wallets(this.wallet); @@ -188,4 +196,72 @@ void main() { expect(tester.takeException(), isNull); }, ); + + for (final raw in [false, true]) { + testWidgets( + raw + ? 'a bare address QR offers no payment URI QR codes' + : 'a URI QR offers more payment URI QR codes', + (tester) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + tester.view.physicalSize = const Size(1400, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final info = WalletInfo.createNew( + coin: Epiccash(CryptoCurrencyNetwork.main), + name: 'Epic Cash', + walletIdOverride: _walletId, + ).copyWith(cachedReceivingAddress: _address); + final wallet = raw ? _RawQrWallet(info) : _Wallet(info); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(_Wallets(wallet)), + pWalletInfo(_walletId).overrideWithValue(info), + pWalletReceivingAddress(_walletId).overrideWithValue(_address), + pSelectedSlatepackMethod(_walletId).overrideWithProvider( + StateProvider((ref) => null), + ), + themeProvider.overrideWithProvider( + StateProvider((ref) => theme), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SingleChildScrollView( + child: SizedBox( + width: 520, + child: DesktopReceive(walletId: _walletId), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final qr = tester.widget(find.byType(QR)); + expect(qr.data == _address, raw); + expect( + find.text('Create new QR code'), + raw ? findsNothing : findsOneWidget, + ); + expect(tester.takeException(), isNull); + }, + ); + } } 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 000000000..281b7c38d --- /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 000000000..74fca5db2 --- /dev/null +++ b/test/pages/slatepack/grin_slatepack_flow_test.dart @@ -0,0 +1,561 @@ +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(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() { + useGrinCoinConfig(); + 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 000000000..511ec1e37 --- /dev/null +++ b/test/pages/slatepack/grin_tx_details_and_proof_test.dart @@ -0,0 +1,441 @@ +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() { + useGrinCoinConfig(); + 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 failed broadcast explains what cancelling can and cannot do', () { + final prompt = SlatepackCancelPrompt.of( + const SlatepackTxInfo( + state: SlateState.s3, + finalizedAwaitingConfirmation: true, + broadcastPosted: false, + ), + incoming: false, + ); + // The node may have taken it without answering. + expect(prompt.message, contains('did not confirm that it accepted')); + expect(prompt.message, contains('can still confirm')); + expect(prompt.message, contains('rescan')); + }); + }); + + 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 000000000..d16f76895 --- /dev/null +++ b/test/pages/slatepack/invoice_dialog_layout_test.dart @@ -0,0 +1,169 @@ +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() { + useGrinCoinConfig(); + 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 000000000..50c295922 --- /dev/null +++ b/test/pages/slatepack/request_invoice_view_test.dart @@ -0,0 +1,169 @@ +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() { + useGrinCoinConfig(); + 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 4ed2c84fd..10bee25d5 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, @@ -47,7 +52,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. @@ -134,6 +146,9 @@ class _SynchronousMwcWallet extends MimblewimblecoinWallet { final SlateState state; final Completer? localGate; + @override + String get walletId => "test-wallet"; + @override Future inspectSlatepack(String armored) { onInspect(); @@ -150,38 +165,71 @@ class _SynchronousMwcWallet extends MimblewimblecoinWallet { } } +/// A real MWC wallet with only an id, for flows that never reach native code. +class _IdentifiedMwcWallet extends MimblewimblecoinWallet { + _IdentifiedMwcWallet() : super(CryptoCurrencyNetwork.main); + + @override + String get walletId => "test-wallet"; +} + 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, ); }); @@ -293,6 +341,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( @@ -615,6 +666,28 @@ void main() { expect(wallet.receiveCalls, 0); }); + for (final (paid, wording) in [ + (true, 'already paid this invoice'), + (false, 'This wallet created the invoice'), + ]) { + testWidgets( + 'an invoice in the history is not paid again (paid by us: $paid)', + (tester) async { + final wallet = _InspectOnlyWallet( + SlateState.i1, + invoices: true, + localIsSend: paid, + ); + + await runFlow(tester, wallet); + + expect(find.text('Cannot pay this invoice'), findsOneWidget); + expect(find.textContaining(wording), findsOneWidget); + await closeDialog(tester); + }, + ); + } + testWidgets('a hexadecimal slatepack sender is labelled as a key', ( tester, ) async { @@ -970,7 +1043,7 @@ void main() { testWidgets("multiple pasted MWC slatepacks explain that two were found", ( tester, ) async { - final wallet = MimblewimblecoinWallet(CryptoCurrencyNetwork.main); + final wallet = _IdentifiedMwcWallet(); const reply = "Here is my response:\n" "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK.\n\n" @@ -990,5 +1063,13 @@ 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 5710b970c..401809235 100644 --- a/test/pages/slatepack/slatepack_send_flow_test.dart +++ b/test/pages/slatepack/slatepack_send_flow_test.dart @@ -56,6 +56,7 @@ class _Wallet extends EpiccashWallet { int created = 0; int refreshed = 0; final cancelled = []; + String? requestedRecipient; @override String get walletId => 'wallet-1'; @@ -75,6 +76,7 @@ class _Wallet extends EpiccashWallet { String? message, }) async { created++; + requestedRecipient = recipientAddress; await gate?.future; if (createError != null) { return SlatepackResult( @@ -160,6 +162,7 @@ Future> _pumpSend( SlatepackInterface wallet, { MainDB? db, bool nestedNavigator = false, + String? recipientAddress, }) async { tester.view.physicalSize = const Size(1400, 2400); tester.view.devicePixelRatio = 1; @@ -182,6 +185,7 @@ Future> _pumpSend( context: context, wallet: wallet, amount: _amount(100), + recipientAddress: recipientAddress, message: 'on-chain note', localNote: 'local note', db: db ?? _Notes(), @@ -215,6 +219,16 @@ Future> _pumpSend( } void main() { + testWidgets('the recipient address is forwarded', (tester) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 1); + + await _pumpSend(tester, wallet, recipientAddress: 'grin1recipient'); + await tester.pumpAndSettle(); + + expect(wallet.requestedRecipient, 'grin1recipient'); + 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 000000000..fa282610a --- /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_coin_test.dart b/test/wallets/grin/grin_coin_test.dart index cc3cb1f71..28073c889 100644 --- a/test/wallets/grin/grin_coin_test.dart +++ b/test/wallets/grin/grin_coin_test.dart @@ -1,6 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:grin_native/grin_native.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/pages/exchange_view/choose_address_from_stack_view.dart'; import 'package:stackwallet/wallets/crypto_currency/coins/grin_checkpoints.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; @@ -75,6 +76,14 @@ void main() { expect(throwing.validateAddress('grin1abc'), isFalse); }); + test('an exchange is never offered a Grin wallet address', () { + expect(exchangeAddressUnavailableReason(main), contains('Slatepack')); + expect( + exchangeAddressUnavailableReason(Bitcoin(CryptoCurrencyNetwork.main)), + isNull, + ); + }); + test('isSlatepack', () { expect(main.isSlatepack(' BEGINSLATEPACK. abc ENDSLATEPACK. '), isTrue); expect(main.isSlatepack('BEGINSLATEPACK. abc'), isFalse); diff --git a/test/wallets/grin/grin_errors_test.dart b/test/wallets/grin/grin_errors_test.dart index 6f0dfa7bf..ca87893b9 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/exceptions/wallet/node_tor_mismatch_config_exception.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; @@ -26,6 +26,10 @@ Future captureLogs(Future Function() body) async { return out.toString(); } +/// A Slatepack as the import flow hands it to the wallet after inspection. +SlateInspection _imported(String armored, SlateState state) => + SlateInspection(state: state, slateId: 'slate', slateJson: armored); + void main() { useGrinCoinConfig(); TestWidgetsFlutterBinding.ensureInitialized(); @@ -184,9 +188,9 @@ void main() { ); final s1 = await h.wallet.receiveSlatepack( - 'BEGINSLATEPACK. incoming ENDSLATEPACK.', + _imported('BEGINSLATEPACK. incoming ENDSLATEPACK.', SlateState.s1), ); - 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 375bee8fe..993eba1b0 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'; @@ -36,30 +37,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'))); }); @@ -71,7 +77,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); @@ -79,13 +88,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 ae0be94ca..445d1bb6f 100644 --- a/test/wallets/grin/grin_lifecycle_test.dart +++ b/test/wallets/grin/grin_lifecycle_test.dart @@ -232,6 +232,22 @@ void main() { await eventually(() => next.info.grinData!.pendingScanFrom == null); }); + test( + 'a slate record and a scan checkpoint written together both land', + () async { + await h.wallet.init(); + await Future.wait([ + h.wallet.debugSetPendingScanFrom(1234), + h.wallet.updateSlatepackTransactionMetadata({ + 'slate-a': {'broadcastPosted': false}, + }), + ]); + final stored = h.wallet.info.grinData!; + expect(stored.pendingScanFrom, 1234); + expect(stored.slatepackTransactions, contains('slate-a')); + }, + ); + test('a rescan that cannot open the wallet is still owed', () async { final r = await GrinHarness.create(restoreHeight: 1000); addTearDown(r.dispose); diff --git a/test/wallets/grin/grin_scan_test.dart b/test/wallets/grin/grin_scan_test.dart index c23b1156d..b2b0ea6b6 100644 --- a/test/wallets/grin/grin_scan_test.dart +++ b/test/wallets/grin/grin_scan_test.dart @@ -3,11 +3,13 @@ import 'dart:convert'; 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'; 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/services/event_bus/events/global/blocks_remaining_event.dart'; import 'package:stackwallet/services/event_bus/events/global/refresh_percent_changed_event.dart'; import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; @@ -193,6 +195,50 @@ void main() { expect(h.wallet.info.grinData!.pendingScanFrom, isNull); }); + test('a paused restore continues when the app resumes, and a backup restore ' + 'waiting for it is not told it failed', () async { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + h.wallet.mobileScanLifecycle = true; + final api = await restore(); + Object? waitError; + var waited = false; + unawaited( + h.wallet.waitForRecovery().then( + (_) => waited = true, + onError: (Object e) => waitError = e, + ), + ); + 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); + expect(waitError, isNull); + expect(waited, isFalse); + api.finishScan(); + await eventually(() => waited, reason: 'the recovery ends with the scan'); + expect(waitError, isNull); + }); + test('a node change continues a pending restore', () async { await h.wallet.init(isRestore: true); h.wallet.shouldAutoSync = true; @@ -443,8 +489,21 @@ void main() { await expectLater(h.wallet.exportPaymentProof('slate-1'), scanning); await expectLater(h.wallet.verifyPaymentProof(proof), scanning); await expectLater(h.wallet.repost('slate-1'), scanning); - await expectLater(h.wallet.finalizeSlatepack('s2'), scanning); - await expectLater(h.wallet.finalizeInvoice('i2'), scanning); + // Finalizing reports a failed result rather than throwing. + for (final finalize in [ + h.wallet.finalizeSlatepack( + const SlateInspection( + state: SlateState.s2, + slateId: 'slate-1', + slateJson: 's2', + ), + ), + h.wallet.finalizeInvoice('i2'), + ]) { + final result = await finalize; + expect(result.success, isFalse); + expect(result.error, contains('finish scanning')); + } // Encrypted: only the wallet could read it. h.backend.decodeError = grinError(11); await expectLater( 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 000000000..063c7f57c --- /dev/null +++ b/test/wallets/grin/grin_slatepack_interface_test.dart @@ -0,0 +1,592 @@ +import 'dart:async'; +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'; + +/// A Slatepack as the import flow hands it to the wallet after inspection. +SlateInspection _imported(String armored, SlateState state) => + SlateInspection(state: state, slateId: 'slate', slateJson: armored); + +void main() { + useGrinCoinConfig(); + 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); + }); + + test( + 'localTxForSlate does not wait long behind other wallet calls', + () async { + final queued = Completer(); + h.backend.api.transactionsGate = queued.future; + final watch = Stopwatch()..start(); + expect(await h.wallet.localTxForSlate('slate-1'), isNull); + // The import flow gives up on the lookup after three seconds. + expect(watch.elapsed, lessThan(const Duration(seconds: 3))); + queued.complete(); + }, + ); + + group('createSlatepack', () { + test('encrypts to a recipient', () async { + h.backend.api.transactionRefreshes.clear(); + h.backend.api.balanceRefreshes.clear(); + final result = await h.wallet.createSlatepack( + amount: grin(5000), + recipientAddress: 'grin1friend', + ); + 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, isFalse); + expect(args.amountIncludesFee, isFalse); + 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( + _imported('s1', SlateState.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( + _imported('s2', SlateState.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( + _imported('s2', SlateState.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( + _imported('s2', SlateState.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( + _imported('s2', SlateState.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('a refused broadcast is in the history when the result returns, so ' + 'repost straight after it finds the transaction', () async { + h.backend.api.transactions = GrinTxList( + refreshedFromNode: false, + transactions: [ + entryOf(id: 3, state: GrinSlateState.s3, hasStoredTx: true), + ], + ); + h.backend.api.finalizeError = grinError( + 9, + details: {'slate_id': 'slate-1', 'finalized': true}, + ); + final result = await h.wallet.finalizeSlatepack( + _imported('s2', SlateState.s2), + ); + expect(result.posted, isFalse); + expect( + await isar.transactionV2s.filter().txidEqualTo('slate-1').findFirst(), + isNotNull, + ); + + await h.wallet.repost('slate-1'); + expect(h.backend.api.calls, contains('repost')); + }); + + 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, + kernelExcess: '08ab', + 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); + } + }); + }); + + group('an HTTP send that fails checks', () { + Future send() => 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, + ), + ); + + test('blames the recipient only for an answer it refused', () async { + for (final code in [11, 12]) { + h.backend.api.sendError = grinError( + code, + details: {'reason': 'bad_answer'}, + ); + await expectLater( + send(), + throwsA( + isA().having( + (e) => e.message, + 'message', + grinBadAnswerMessage, + ), + ), + ); + } + }); + + test('reports a failure of its own as such', () async { + for (final code in [11, 12]) { + h.backend.api.sendError = grinError(code); + await expectLater( + send(), + throwsA( + isA().having( + (e) => e.message, + 'message', + isNot(contains('recipient')), + ), + ), + ); + } + }); + }); + + 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 000000000..ce39fb4a7 --- /dev/null +++ b/test/wallets/grin/grin_tx_failures_test.dart @@ -0,0 +1,424 @@ +import 'dart:convert'; +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/transaction.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'; + +/// A Slatepack as the import flow hands it to the wallet after inspection. +SlateInspection _imported(String armored, SlateState state) => + SlateInspection(state: state, slateId: 'slate', slateJson: armored); + +void main() { + useGrinCoinConfig(); + 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); + // Recorded as not posted, so details offer cancel next to repost. + final stored = TransactionV2( + walletId: h.wallet.walletId, + blockHash: null, + hash: '', + txid: 'slate-f', + timestamp: 0, + height: null, + inputs: const [], + outputs: const [], + version: 0, + type: TransactionType.outgoing, + subType: TransactionSubType.none, + otherData: jsonEncode({ + TxV2OdKeys.isGrinTransaction: true, + TxV2OdKeys.slateId: 'slate-f', + TxV2OdKeys.grinHasStoredTx: true, + }), + ); + expect(h.wallet.slatepackTxInfo(stored)!.broadcastPosted, 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', method: SlatepackMethod.slatepack), + ); + api.fee = feeOf(31000000); + final e = await failure(h.wallet.confirmSend(txData: prepared)); + expect(e.termsChanged, isTrue); + expect(e.message, grinTermsChangedMessage); + 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.termsChanged, isTrue); + expect(e.message, grinTermsChangedMessage); + expect(api.httpSends, isEmpty); + expect(api.cancelled, isEmpty); + }); + + test('an unchanged fee sends', () async { + await h.wallet.init(); + final prepared = await h.wallet.prepareSend( + txData: send( + 'grin1friend', + method: SlatepackMethod.slatepack, + ).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( + _imported('s1', SlateState.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(_imported('s2', SlateState.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( + _imported('s1', SlateState.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 56079ec87..fd5bec369 100644 --- a/test/wallets/grin/grin_tx_mapping_test.dart +++ b/test/wallets/grin/grin_tx_mapping_test.dart @@ -292,6 +292,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 0128c07aa..254aee6a6 100644 --- a/test/wallets/mimblewimble_slate_inspection_test.dart +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -78,10 +78,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; @@ -91,7 +96,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) => @@ -102,6 +108,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); } class _ThrowingMetadataWallet extends _PendingLookupWallet { @@ -376,6 +387,47 @@ void main() { ); }); + 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 fc50cd716..df6d4c212 100644 --- a/test/wallets/support/grin_fakes.dart +++ b/test/wallets/support/grin_fakes.dart @@ -89,10 +89,18 @@ class FakeGrinWalletApi implements GrinWalletApi { Object? sendError; Object? scanError; Object? updateNetworkError; + Object? finalizeError; + Object? invoiceError; + Object? repostError; + Object? verifyError; + + /// Fails a cancel by log id, or by slate id under the key -1. + final cancelErrors = {}; /// 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; @@ -113,6 +121,10 @@ class FakeGrinWalletApi implements GrinWalletApi { final kernelLookups = <({String excess, int? minHeight})>[]; Object? kernelError; + /// When set, getTransactions waits for it, like a read queued behind + /// another wallet call. + Future? transactionsGate; + Completer? closeGate; bool _closed = false; final _events = StreamController.broadcast(); @@ -247,6 +259,7 @@ class FakeGrinWalletApi implements GrinWalletApi { Future getTransactions({bool refreshFromNode = true}) async { _check('getTransactions'); transactionRefreshes.add(refreshFromNode); + await transactionsGate; return transactions; } @@ -334,6 +347,7 @@ class FakeGrinWalletApi implements GrinWalletApi { bool fluff = false, }) async { _check('finalizeSlatepack'); + if (finalizeError != null) throw finalizeError!; return finalizedOf(); } @@ -350,6 +364,7 @@ class FakeGrinWalletApi implements GrinWalletApi { ) async { _check('processInvoice'); invoicePayments.add(args); + if (invoiceError != null) throw invoiceError!; return slatepackOf(GrinSlateState.i2); } @@ -360,17 +375,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)); } @@ -395,6 +415,7 @@ class FakeGrinWalletApi implements GrinWalletApi { GrinPaymentProof proof, ) async { _check('verifyPaymentProof'); + if (verifyError != null) throw verifyError!; return const GrinPaymentProofVerification( isSender: true, isRecipient: false, @@ -443,17 +464,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', @@ -725,6 +749,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,