diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 78cf9b87e8..b92f17f31e 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -332,7 +332,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { _clearRecipientForms(); // auto fill address - _address = paymentData.address.trim(); + _address = _stripRelayPrefixes(paymentData.address.trim()); // autofill notes field if (paymentData.message != null) { @@ -401,6 +401,31 @@ class _SendViewState extends ConsumerState with SendFeeForm { } } + /// [address] without the prefixes an Epicbox address can be scanned or + /// pasted with. Other coins' addresses come back unchanged. + String _stripRelayPrefixes(String address) => coin is Epiccash + ? AddressUtils().formatEpicCashAddress(address) + : address; + + /// Strips the prefixes an Epicbox address can be pasted with. Only + /// rewrites the field when that changes the text, so typing stays intact. + String _formatRelayAddress(String text) { + if (coin is! Epiccash) return text; + String address = text.trim(); + if (address.contains("\n")) { + address = address.substring(0, address.indexOf("\n")); + } + final formatted = _stripRelayPrefixes(address); + if (formatted != address) { + sendToController.value = TextEditingValue( + text: formatted, + selection: TextSelection.collapsed(offset: formatted.length), + ); + return formatted; + } + return text; + } + Future _checkSparkNameAndOrSetAddress( String content, { bool setController = true, @@ -520,7 +545,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { _applyUri(paymentData); } else { _setOpReturnData(null); - _address = qrResult.rawContent!.split("\n").first.trim(); + _address = _stripRelayPrefixes( + qrResult.rawContent!.split("\n").first.trim(), + ); sendToController.text = _address ?? ""; _setValidAddressProviders(_address); @@ -1548,24 +1575,6 @@ class _SendViewState extends ConsumerState with SendFeeForm { } }); - // add listener for epic cash to strip http:// and https:// prefixes if the address also ocntains an @ symbol (indicating an epicbox address) - if (coin is Epiccash) { - sendToController.addListener(() { - _address = sendToController.text.trim(); - - if (_address != null && _address!.isNotEmpty) { - _address = _address!.trim(); - if (_address!.contains("\n")) { - _address = _address!.substring(0, _address!.indexOf("\n")); - } - - sendToController.text = AddressUtils().formatEpicCashAddress( - _address!, - ); - } - }); - } - Decimal? price; if (ref.watch(prefsChangeNotifierProvider.select((s) => s.externalCalls))) { price = ref.watch( @@ -1836,6 +1845,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { selectAll: false, ), onChanged: (newValue) async { + newValue = _formatRelayAddress(newValue); final trimmed = newValue.trim(); if (AddressUtils.mayBePaymentUri( @@ -1853,8 +1863,12 @@ class _SendViewState extends ConsumerState with SendFeeForm { _applyUri(parsed); } else { _setOpReturnData(null); + // The text is already in the field; + // writing it back would move the + // cursor on every keystroke. await _checkSparkNameAndOrSetAddress( newValue, + setController: false, ); } } else { 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 ebbd81514b..a782a52412 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 @@ -1081,7 +1081,10 @@ class _DesktopSendState extends ConsumerState { _applyUri(paymentData); } else { _setOpReturnData(null); - _address = qrCodeData.split("\n").first.trim(); + _address = stripRelayPrefixes( + coin, + qrCodeData.split("\n").first.trim(), + ); sendToController.text = _address ?? ""; _setValidAddressProviders(_address); @@ -1296,7 +1299,7 @@ class _DesktopSendState extends ConsumerState { _clearRecipientForms(); // auto fill address - _address = paymentData.address; + _address = stripRelayPrefixes(coin, paymentData.address.trim()); sendToController.text = _address!; // autofill notes field. @@ -1347,6 +1350,26 @@ class _DesktopSendState extends ConsumerState { } } + /// Strips the prefixes an Epicbox or MWCMQS address can be pasted with. + /// Only rewrites the field when that changes the text, so typing stays + /// intact. + String _formatRelayAddress(String text) { + if (coin is! Epiccash && coin is! Mimblewimblecoin) return text; + String address = text.trim(); + if (address.contains("\n")) { + address = address.substring(0, address.indexOf("\n")); + } + final formatted = stripRelayPrefixes(coin, address); + if (formatted != address) { + sendToController.value = TextEditingValue( + text: formatted, + selection: TextSelection.collapsed(offset: formatted.length), + ); + return formatted; + } + return text; + } + Future _checkSparkNameAndOrSetAddress( String content, { bool setController = true, @@ -1678,39 +1701,8 @@ class _DesktopSendState extends ConsumerState { final previewEnabled = ref.watch(pPreviewTxButtonEnabled(coin)); final needsEthFee = coin is Ethereum && isCustomFee; - // add listener for epic cash to strip http:// and https:// prefixes if the address also ocntains an @ symbol (indicating an epicbox address) - if (coin is Epiccash) { - sendToController.addListener(() { - _address = sendToController.text; - - if (_address != null && _address!.isNotEmpty) { - _address = _address!.trim(); - if (_address!.contains("\n")) { - _address = _address!.substring(0, _address!.indexOf("\n")); - } - - sendToController.text = formatAddress(_address!); - } - }); - } - final balType = ref.watch(publicPrivateBalanceStateProvider); - if (coin is Mimblewimblecoin) { - sendToController.addListener(() { - _address = sendToController.text; - - if (_address != null && _address!.isNotEmpty) { - _address = _address!.trim(); - if (_address!.contains("\n")) { - _address = _address!.substring(0, _address!.indexOf("\n")); - } - - sendToController.text = formatAddressMwc(_address!); - } - }); - } - final isMwebEnabled = ref.watch( pWalletInfo(walletId).select((s) => s.isMwebEnabled), ); @@ -2162,6 +2154,7 @@ class _DesktopSendState extends ConsumerState { selectAll: false, ), onChanged: (newValue) async { + newValue = _formatRelayAddress(newValue); final trimmed = newValue; if (AddressUtils.mayBePaymentUri(trimmed, _address ?? "")) { @@ -2175,7 +2168,12 @@ class _DesktopSendState extends ConsumerState { _applyUri(parsed); } else { _setOpReturnData(null); - await _checkSparkNameAndOrSetAddress(newValue); + // The text is already in the field; writing it back + // would move the cursor on every keystroke. + await _checkSparkNameAndOrSetAddress( + newValue, + setController: false, + ); } } else { _setOpReturnData(null); @@ -2589,6 +2587,15 @@ class _DesktopSendState extends ConsumerState { } } +/// [address] without the prefixes an Epicbox or MWCMQS address can be scanned +/// or pasted with. Other coins' addresses come back unchanged. +String stripRelayPrefixes(CryptoCurrency coin, String address) => + coin is Epiccash + ? formatAddress(address) + : coin is Mimblewimblecoin + ? formatAddressMwc(address) + : address; + String formatAddress(String epicAddress) { // strip http:// or https:// prefixes if the address contains an @ symbol (and is thus an epicbox address) if ((epicAddress.startsWith("http://") || diff --git a/lib/utilities/address_utils.dart b/lib/utilities/address_utils.dart index 9005166e64..da3c91b98c 100644 --- a/lib/utilities/address_utils.dart +++ b/lib/utilities/address_utils.dart @@ -261,6 +261,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/test/address_utils_test.dart b/test/address_utils_test.dart index af615c5b56..d211b5fa6a 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/epic_send_address_test.dart b/test/pages/send_view/epic_send_address_test.dart new file mode 100644 index 0000000000..293b99429c --- /dev/null +++ b/test/pages/send_view/epic_send_address_test.dart @@ -0,0 +1,204 @@ +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/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/send_view/send_view.dart'; +import 'package:stackwallet/providers/global/barcode_scanner_provider.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/coin_icon_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/barcode_scanner_interface.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +class _SendPrefs extends ConfirmationPrefs { + @override + bool get enableCoinControl => false; + @override + AmountUnit amountUnit(CryptoCurrency coin) => AmountUnit.normal; + @override + int maxDecimals(CryptoCurrency coin) => coin.fractionDigits; +} + +class _TestWallet extends EpiccashWallet { + _TestWallet() : super(CryptoCurrencyNetwork.main); + + @override + Future estimateFeeFor(Amount amount, BigInt feeRate) async => + Amount.zeroWith(fractionDigits: cryptoCurrency.fractionDigits); +} + +class _FakeScanner implements BarcodeScannerInterface { + _FakeScanner(this.rawContent); + + final String rawContent; + + @override + Future scan({required BuildContext context}) async => + ScanResult(rawContent: rawContent); +} + +void main() { + Future pumpSendView(WidgetTester tester, [String scanned = '']) async { + tester.view.physicalSize = const Size(800, 1200); + 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 wallet = _TestWallet(); + final coin = wallet.cryptoCurrency; + const walletId = 'epic-send-form'; + final info = WalletInfo( + walletId: walletId, + name: 'Epic Cash test wallet', + mainAddressType: AddressType.mimbleWimble, + coinName: coin.identifier, + ); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletInfo(walletId).overrideWithValue(info), + pWalletCoin(walletId).overrideWithValue(coin), + pWalletName(walletId).overrideWithValue(info.name), + pWalletBalance(walletId) + .overrideWithValue(Balance.zeroFor(currency: coin)), + prefsChangeNotifierProvider.overrideWithValue(_SendPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + coinIconProvider(coin).overrideWithValue( + File('test/sample_data/light/assets/dummy.svg').absolute.path, + ), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: 8, + ), + ), + pBarcodeScanner.overrideWithValue(_FakeScanner(scanned)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: SendView(walletId: walletId, coin: coin), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + String addressField(WidgetTester tester) => tester + .widget(find.byKey(const Key('sendViewAddressFieldKey'))) + .controller! + .text; + + TextSelection addressSelection(WidgetTester tester) => tester + .widget(find.byKey(const Key('sendViewAddressFieldKey'))) + .controller! + .selection; + + Future type(WidgetTester tester, String text, int cursor) async { + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: cursor), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + Future scan(WidgetTester tester) async { + final button = find.byKey(const Key('sendViewScanQrButtonKey')); + await tester.ensureVisible(button); + await tester.tap(button); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + Future dispose(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + } + + testWidgets('a scanned Epicbox address loses its https prefix and slash', ( + tester, + ) async { + await pumpSendView(tester, 'https://user@epicbox.example/\nsecond line'); + + await scan(tester); + + expect(addressField(tester), 'user@epicbox.example'); + await dispose(tester); + }); + + testWidgets('a scanned mailto Epicbox address loses its prefix', ( + tester, + ) async { + await pumpSendView(tester, 'mailto:user@epicbox.example'); + + await scan(tester); + + expect(addressField(tester), 'user@epicbox.example'); + await dispose(tester); + }); + + testWidgets('a scanned http receiver address is kept as it is', ( + tester, + ) async { + await pumpSendView(tester, 'https://receiver.example:3415'); + + await scan(tester); + + expect(addressField(tester), 'https://receiver.example:3415'); + await dispose(tester); + }); + + testWidgets('typing an http receiver address keeps the cursor in place', ( + tester, + ) async { + await pumpSendView(tester); + const address = 'https://receiver.example:3415'; + await tester.showKeyboard(find.byKey(const Key('sendViewAddressFieldKey'))); + + for (var i = 1; i <= address.length; i++) { + await type(tester, address.substring(0, i), i); + + expect(addressField(tester), address.substring(0, i)); + expect(addressSelection(tester), TextSelection.collapsed(offset: i)); + } + + // An edit in the middle of the address. + const edited = 'https://my-receiver.example:3415'; + await type(tester, edited, 'https://my-'.length); + + expect(addressField(tester), edited); + expect( + addressSelection(tester), + const TextSelection.collapsed(offset: 'https://my-'.length), + ); + await dispose(tester); + }); +} diff --git a/test/pages_desktop_specific/wallet/desktop_send_relay_address_test.dart b/test/pages_desktop_specific/wallet/desktop_send_relay_address_test.dart new file mode 100644 index 0000000000..7f427f1277 --- /dev/null +++ b/test/pages_desktop_specific/wallet/desktop_send_relay_address_test.dart @@ -0,0 +1,53 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; + +void main() { + final epic = Epiccash(CryptoCurrencyNetwork.main); + final mwc = Mimblewimblecoin(CryptoCurrencyNetwork.main); + final bitcoin = Bitcoin(CryptoCurrencyNetwork.main); + + test('an Epicbox address loses the prefixes and the trailing slash', () { + expect( + stripRelayPrefixes(epic, 'https://user@epicbox.example/'), + 'user@epicbox.example', + ); + expect( + stripRelayPrefixes(epic, 'http://user@epicbox.example'), + 'user@epicbox.example', + ); + expect( + stripRelayPrefixes(epic, 'mailto:user@epicbox.example'), + 'user@epicbox.example', + ); + }); + + test('an MWCMQS address loses the prefixes and the trailing slash', () { + expect( + stripRelayPrefixes(mwc, 'https://user@mqs.example/'), + 'user@mqs.example', + ); + expect( + stripRelayPrefixes(mwc, 'mailto:user@mqs.example'), + 'user@mqs.example', + ); + }); + + test('an http receiver address is kept as it is', () { + expect( + stripRelayPrefixes(epic, 'https://receiver.example:3415'), + 'https://receiver.example:3415', + ); + expect( + stripRelayPrefixes(mwc, 'http://receiver.example:3415/'), + 'http://receiver.example:3415/', + ); + }); + + test('other coins keep the text as it is', () { + expect( + stripRelayPrefixes(bitcoin, 'https://user@host.example/'), + 'https://user@host.example/', + ); + }); +}