Test the Buy form's Choose from Stack flow in the real app
What changed, and why it matters
This commit adds automated integration and widget tests for the 'Buy' form's 'Choose from Stack' feature in a cryptocurrency wallet app. It does not change production code, fix bugs, or alter security behavior. It only verifies that the existing feature works correctly for different wallet types (Taproot, restored, view-only) and shows the right dialog when a wallet cannot be used.
No security action needed. Treat as normal test-only code review and merge when CI passes.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit introduces a new integration test suite under integration_test/buy_flow/ plus a widget test under test/pages/buy_view/. A fake ElectrumX server, test harness, and three scenario tests exercise the Buy form’s wallet-selection flow end-to-end against the real desktop app. The tests verify: (1) restored wallets advance used derivation paths to fresh addresses, (2) Taproot wallets derive and cache a BIP84 address because the buy provider does not accept Taproot, and (3) view-only Taproot wallets are rejected with a dialog. TestUI is extended with an optional report prefix so the harness can reuse it. No application logic is modified.
Changed components
integration_test/buy_flow/fake_electrumx.dartintegration_test/buy_flow/harness.dartintegration_test/buy_flow/restored_wallet_test.dartintegration_test/buy_flow/taproot_wallet_test.dartintegration_test/buy_flow/view_only_wallet_test.dartintegration_test/wallet_creation/ui.darttest/pages/buy_view/buy_form_choose_from_stack_test.dartInspect captured patch +1022 / −2
### integration_test/buy_flow/fake_electrumx.dart
@@ -0,0 +1,252 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
+import 'package:stackwallet/wallets/crypto_currency/intermediate/bip39_hd_currency.dart';
+
+/// An ElectrumX server on a loopback port. Its chain is empty until [pay] is
+/// called; wallets then see the payment like any confirmed transaction.
+class FakeElectrumX {
+ FakeElectrumX._(this._server, this._coin) {
+ _server.listen(_serve);
+ }
+
+ static Future<FakeElectrumX> start(Bip39HDCurrency coin) async =>
+ FakeElectrumX._(
+ await ServerSocket.bind(InternetAddress.loopbackIPv4, 0),
+ coin,
+ );
+
+ static const _tip = 800000;
+ static const _serverVersion = 'ElectrumX 1.16.0';
+
+ final ServerSocket _server;
+ final Bip39HDCurrency _coin;
+ final _sockets = <Socket>{};
+ final _payments = <_Payment>[];
+
+ int get port => _server.port;
+
+ /// Adds a confirmed payment of [sats] to [address].
+ void pay(String address, {int sats = 10000}) {
+ final number = _payments.length + 1;
+ final transaction = coinlib.Transaction(
+ inputs: [
+ // A coinbase input, so wallets have no earlier transaction to look up.
+ // Its script makes every payment a different transaction.
+ coinlib.RawInput(
+ prevOut: coinlib.OutPoint(Uint8List(32), 0xffffffff),
+ scriptSig: Uint8List.fromList([2, number & 0xff, number >> 8]),
+ ),
+ ],
+ outputs: [
+ coinlib.Output.fromAddress(
+ BigInt.from(sats),
+ coinlib.Address.fromString(address, _coin.networkParams),
+ ),
+ ],
+ );
+ _payments.add(
+ _Payment(
+ address: address,
+ scriptHash: _coin.addressToScriptHash(address: address),
+ sats: sats,
+ height: _tip - 10,
+ transaction: transaction,
+ ),
+ );
+ }
+
+ Future<void> close() async {
+ await _server.close();
+ for (final socket in _sockets.toList()) {
+ socket.destroy();
+ }
+ }
+
+ void _serve(Socket socket) {
+ void drop() {
+ _sockets.remove(socket);
+ socket.destroy();
+ }
+
+ _sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen(
+ (line) {
+ // One JSON-RPC request, or a batch of them, per line.
+ Object? reply;
+ try {
+ final message = jsonDecode(line);
+ reply = message is List
+ ? [for (final request in message) ?_reply(request as Map)]
+ : _reply(message as Map);
+ } on Object {
+ reply = _error(null, -32700, 'not a JSON-RPC request');
+ }
+ if (reply == null || (reply is List && reply.isEmpty)) return;
+ socket.write('${jsonEncode(reply)}\n');
+ },
+ onError: (Object _) => drop(),
+ onDone: drop,
+ cancelOnError: true,
+ );
+ }
+
+ Map<String, Object?> _error(Object? id, int code, String message) => {
+ 'jsonrpc': '2.0',
+ 'id': id,
+ 'error': {'code': code, 'message': message},
+ };
+
+ Map<String, Object?>? _reply(Map<dynamic, dynamic> request) {
+ // A request without an id is a notification and gets no reply.
+ if (!request.containsKey('id')) return null;
+ final id = request['id'];
+ try {
+ return {
+ 'jsonrpc': '2.0',
+ 'id': id,
+ 'result': _result(
+ request['method'] as String,
+ request['params'] as List? ?? const [],
+ ),
+ };
+ } on _RpcError catch (error) {
+ return _error(id, error.code, error.message);
+ } on Object catch (error) {
+ // Answer anyway, so a request this server cannot handle fails at once
+ // instead of timing out.
+ return _error(id, -32603, 'fake ElectrumX: $error');
+ }
+ }
+
+ Object? _result(String method, List<dynamic> params) {
+ Iterable<_Payment> paymentsTo() =>
+ _payments.where((payment) => payment.scriptHash == params.first);
+
+ switch (method) {
+ case 'server.version':
+ return [_serverVersion, '1.4'];
+ case 'server.features':
+ return {
+ 'genesis_hash': _coin.genesisHash,
+ 'hash_function': 'sha256',
+ 'server_version': _serverVersion,
+ 'protocol_min': '1.4',
+ 'protocol_max': '1.4.2',
+ 'pruning': null,
+ 'hosts': <String, Object?>{},
+ };
+ case 'server.ping':
+ case 'blockchain.scripthash.subscribe':
+ return null;
+ case 'blockchain.headers.subscribe':
+ return {'height': _tip, 'hex': '00' * 80};
+ case 'blockchain.estimatefee':
+ case 'blockchain.relayfee':
+ return 0.00001;
+ case 'blockchain.scripthash.get_history':
+ return [
+ for (final payment in paymentsTo())
+ {'tx_hash': payment.txid, 'height': payment.height},
+ ];
+ case 'blockchain.scripthash.listunspent':
+ return [
+ for (final payment in paymentsTo())
+ {
+ 'tx_hash': payment.txid,
+ 'tx_pos': 0,
+ 'height': payment.height,
+ 'value': payment.sats,
+ },
+ ];
+ case 'blockchain.scripthash.get_balance':
+ return {
+ 'confirmed': paymentsTo().fold(0, (sum, p) => sum + p.sats),
+ 'unconfirmed': 0,
+ };
+ case 'blockchain.transaction.get':
+ final payment = _payments
+ .where((payment) => payment.txid == params.first)
+ .firstOrNull;
+ if (payment == null) {
+ throw const _RpcError(
+ 2,
+ "daemon error: DaemonError({'code': -5, 'message': 'No such "
+ "mempool or blockchain transaction. Use gettransaction for "
+ "wallet transactions.'})",
+ );
+ }
+ final verbose = params.length > 1 && params[1] == true;
+ return verbose ? payment.verbose(_tip) : payment.transaction.toHex();
+ default:
+ throw _RpcError(-32601, 'unknown method "$method"');
+ }
+ }
+}
+
+class _Payment {
+ _Payment({
+ required this.address,
+ required this.scriptHash,
+ required this.sats,
+ required this.height,
+ required this.transaction,
+ });
+
+ final String address;
+ final String scriptHash;
+ final int sats;
+ final int height;
+ final coinlib.Transaction transaction;
+
+ String get txid => transaction.txid;
+
+ /// The transaction as `blockchain.transaction.get` returns it when verbose.
+ Map<String, Object?> verbose(int tip) {
+ final input = transaction.inputs.single;
+ final output = transaction.outputs.single;
+ return {
+ 'txid': txid,
+ 'hash': txid,
+ 'version': transaction.version,
+ 'size': transaction.size,
+ 'vsize': transaction.size,
+ 'locktime': transaction.locktime,
+ 'vin': [
+ {
+ 'coinbase': coinlib.bytesToHex(input.scriptSig),
+ 'sequence': input.sequence,
+ },
+ ],
+ 'vout': [
+ {
+ 'value': sats / 100000000,
+ 'n': 0,
+ 'scriptPubKey': {
+ 'hex': coinlib.bytesToHex(output.scriptPubKey),
+ 'address': address,
+ },
+ },
+ ],
+ 'hex': transaction.toHex(),
+ 'blockhash': '00' * 32,
+ 'confirmations': tip - height + 1,
+ 'time': 1700000000,
+ 'blocktime': 1700000000,
+ };
+ }
+}
+
+class _RpcError implements Exception {
+ const _RpcError(this.code, this.message);
+
+ final int code;
+ final String message;
+}
### integration_test/buy_flow/harness.dart
@@ -0,0 +1,373 @@
+// Buy flow integration tests, for desktop. With Flutter 3.49 or later:
+//
+// flutter test integration_test/buy_flow -d macos
+//
+// With older Flutter versions, run each *_test.dart file in this folder on
+// its own, for example:
+//
+// flutter test -d macos integration_test/buy_flow/taproot_wallet_test.dart
+//
+// (or -d linux / -d windows). Linux needs a desktop session, because
+// notifications use D-Bus, and a screen at least 800 px wide, otherwise the
+// app uses its mobile UI.
+//
+// Each test launches the real app against a throwaway folder, sets a password
+// through the UI and points Bitcoin at a fake ElectrumX server on this
+// machine. The app's HTTP requests are refused. A test's Bitcoin wallets
+// therefore neither depend on nor send anything to a real service; a wallet
+// of another coin would still reach that coin's default server. Wallets come
+// from a public test mnemonic, which makes every address a known value.
+//
+// One test per file: the app keeps process-wide state, so every scenario
+// needs its own launch.
+
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:path/path.dart' as p;
+import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
+import 'package:stackwallet/main.dart' as app;
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/keys/view_only_wallet_data.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/pages/buy_view/buy_form.dart';
+import 'package:stackwallet/pages/exchange_view/choose_address_from_stack_view.dart';
+import 'package:stackwallet/pages/intro_view.dart';
+import 'package:stackwallet/pages/stack_privacy_calls.dart';
+import 'package:stackwallet/providers/global/secure_store_provider.dart';
+import 'package:stackwallet/providers/providers.dart';
+import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart';
+import 'package:stackwallet/services/event_bus/global_event_bus.dart';
+import 'package:stackwallet/services/notifications_api.dart';
+import 'package:stackwallet/services/wallets.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/wallet/impl/bitcoin_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/extended_keys_interface.dart';
+
+import '../wallet_creation/drivers/desktop_driver.dart';
+import '../wallet_creation/ui.dart';
+import 'fake_electrumx.dart';
+
+/// The mnemonic of the BIP44, BIP49, BIP84 and BIP86 test vectors. It is
+/// public, so nobody keeps funds on it.
+const testMnemonic =
+ 'abandon abandon abandon abandon abandon abandon abandon abandon abandon '
+ 'abandon abandon about';
+
+/// Addresses of [testMnemonic], as the BIPs list them.
+const legacyAddress0 = '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA'; // m/44'/0'/0'/0/0
+const nestedSegwitAddress0 =
+ '37VucYSaXLCAsxYyAPfbSi9eh4iEcbShgf'; // m/49'/0'/0'/0/0
+const segwitAddress0 =
+ 'bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu'; // m/84'/0'/0'/0/0
+const segwitAddress1 =
+ 'bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g'; // m/84'/0'/0'/0/1
+const taprootAddress0 =
+ 'bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr'; // m/86'/0'/0'/0/0
+
+void buyFlowTest(
+ String description,
+ Future<void> Function(BuyFlowTest t) body,
+) {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+ testWidgets(
+ description,
+ (tester) async {
+ final temp = await Directory.systemTemp.createTemp(
+ 'stack_buy_flow_test_',
+ );
+ debugPrint('Test folder: ${temp.path}');
+ final electrumX = await FakeElectrumX.start(
+ Bitcoin(CryptoCurrencyNetwork.main),
+ );
+ try {
+ await body(BuyFlowTest._(tester, temp.path, electrumX));
+ } finally {
+ for (final wallet in Wallets.sharedInstance.wallets) {
+ wallet.shouldAutoSync = false;
+ await wallet.exit();
+ }
+ await electrumX.close();
+ }
+ // Only reached when the test passed, so failed runs keep the folder.
+ // On Windows the still running app holds some of it open.
+ try {
+ await temp.delete(recursive: true);
+ } on FileSystemException catch (_) {}
+ },
+ skip: !(Platform.isLinux || Platform.isMacOS || Platform.isWindows),
+ timeout: const Timeout(Duration(minutes: 10)),
+ );
+}
+
+class BuyFlowTest {
+ BuyFlowTest._(this.tester, this._temp, this.electrumX)
+ : ui = TestUI(tester, reportPrefix: 'BUY_FLOW_');
+
+ final WidgetTester tester;
+ final String _temp;
+
+ /// The server every Bitcoin wallet of the test talks to.
+ final FakeElectrumX electrumX;
+ final TestUI ui;
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+ late final ProviderContainer _app;
+
+ static const _addressField = Key('buyViewReceiveAddressFieldKey');
+
+ /// Starts the app on an empty data folder and sets it up through the UI.
+ Future<void> launch() async {
+ PathProviderPlatform.instance = _TestPaths(_temp);
+ StackFileSystem.setDesktopOverrideDir(p.join(_temp, 'data'));
+ HttpOverrides.global = _NoHttp();
+ ui.errorLog = File(p.join(_temp, 'failure.txt'));
+ // Keep the real notification plugin but avoid OS permission dialogs.
+ await NotificationApi.init(requestPermissions: false);
+ await tester.binding.setSurfaceSize(const Size(1920, 1080));
+ runZonedGuarded(
+ () => app.main(const []),
+ (error, stack) => ui.errors.add(error),
+ );
+
+ ui.stage = 'first launch';
+ final driver = DesktopDriver(ui);
+ await ui.waitFor(find.byType(IntroView));
+ await ui.tap(find.byType(GetStartedButton));
+ await ui.waitFor(find.byType(StackPrivacyCalls));
+ await ui.tapText('Incognito');
+ await ui.tapText('Continue');
+ await driver.createCredentials();
+ _app = ProviderScope.containerOf(tester.element(driver.home));
+
+ // Wallets created from here on use the fake server only. Without their
+ // failover flag, the default nodes are never tried.
+ final nodes = _app.read(nodeServiceChangeNotifierProvider);
+ for (final node in nodes.getNodesFor(coin)) {
+ await nodes.setFailover(node.id, false);
+ }
+ final node = NodeModel(
+ host: InternetAddress.loopbackIPv4.address,
+ port: electrumX.port,
+ name: 'Buy flow test',
+ id: 'buy_flow_test',
+ useSSL: false,
+ enabled: true,
+ coinName: coin.identifier,
+ isFailover: false,
+ isDown: false,
+ torEnabled: false,
+ clearnetEnabled: true,
+ isPrimary: true,
+ );
+ await nodes.save(node, null, false);
+ await nodes.setPrimaryNodeFor(coin: coin, node: node);
+ }
+
+ /// Restores a wallet from [testMnemonic], as the restore screens do.
+ Future<BitcoinWallet> addWallet(String name) =>
+ _addWallet(name, mnemonic: testMnemonic);
+
+ /// Restores a view only wallet from one extended public key.
+ Future<BitcoinWallet> addViewOnlyWallet(String name, XPub xPub) =>
+ _addWallet(name, xPub: xPub);
+
+ Future<BitcoinWallet> _addWallet(
+ String name, {
+ String? mnemonic,
+ XPub? xPub,
+ }) async {
+ ui.stage = 'add "$name"';
+ final db = _app.read(mainDBProvider);
+ final info = WalletInfo.createNew(
+ coin: coin,
+ name: name,
+ otherDataJsonString: xPub == null
+ ? null
+ : jsonEncode({
+ WalletInfoKeys.isViewOnlyKey: true,
+ WalletInfoKeys.viewOnlyTypeIndexKey:
+ ViewOnlyWalletType.xPub.index,
+ }),
+ );
+ final wallet = await Wallet.create(
+ walletInfo: info,
+ mainDB: db,
+ secureStorageInterface: _app.read(secureStoreProvider),
+ nodeService: _app.read(nodeServiceChangeNotifierProvider),
+ prefs: _app.read(prefsChangeNotifierProvider),
+ mnemonic: mnemonic,
+ mnemonicPassphrase: mnemonic == null ? null : '',
+ viewOnlyData: xPub == null
+ ? null
+ : ExtendedKeysViewOnlyWalletData(
+ walletId: info.walletId,
+ xPubs: [xPub],
+ ),
+ );
+ await _wait(() async {
+ await wallet.init();
+ await wallet.recover(isRescan: false);
+ await wallet.info.setMnemonicVerified(isar: db.isar);
+ }(), 'restore to finish');
+ _app.read(pWallets).addWallet(wallet);
+ return wallet as BitcoinWallet;
+ }
+
+ /// The saved receiving addresses of one type, lowest index first.
+ Future<List<Address>> receiving(Wallet wallet, AddressType type) => _app
+ .read(mainDBProvider)
+ .isar
+ .addresses
+ .where()
+ .walletIdEqualTo(wallet.walletId)
+ .filter()
+ .typeEqualTo(type)
+ .subTypeEqualTo(AddressSubType.receiving)
+ .sortByDerivationIndex()
+ .findAll();
+
+ /// Refreshes [wallet] until [done]. One refresh is not always enough: a
+ /// refresh that is already running may have started before the change the
+ /// test is waiting for.
+ Future<void> refreshUntil(
+ Wallet wallet,
+ Future<bool> Function() done,
+ String description,
+ ) async {
+ ui.stage = 'refresh "${wallet.info.name}"';
+ // A refresh that fails still completes normally. It only fires an event.
+ var failed = false;
+ final events = GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .listen(
+ (event) => failed |=
+ event.walletId == wallet.walletId &&
+ event.newStatus == WalletSyncStatus.unableToSync,
+ );
+ final deadline = DateTime.now().add(const Duration(minutes: 2));
+ try {
+ while (true) {
+ await _wait(wallet.refresh(), 'refresh to finish');
+ if (failed) {
+ fail(
+ '${ui.stage}: the refresh failed; '
+ 'the app log in the test folder has the error',
+ );
+ }
+ if (await done()) return;
+ if (DateTime.now().isAfter(deadline)) {
+ fail('${ui.stage}: timed out waiting for $description');
+ }
+ }
+ } finally {
+ await events.cancel();
+ }
+ }
+
+ Future<void> openBuy() async {
+ ui.stage = 'open the Buy page';
+ await ui.tap(find.byKey(const ValueKey('buy')));
+ await ui.waitFor(find.byType(BuyForm), description: 'Buy form');
+ }
+
+ /// The text of the Buy form's receiving address field.
+ String get address =>
+ tester.widget<TextField>(find.byKey(_addressField)).controller!.text;
+
+ /// Whether the Buy form is on screen and takes input. A form under a
+ /// dialog, or on a page that is closing, does not.
+ bool get formTakesInput =>
+ find.byKey(_addressField).hitTestable().evaluate().isNotEmpty;
+
+ /// Empties the address field with its clear button, so the next choice
+ /// visibly fills it again.
+ Future<void> clearAddress() async {
+ await ui.tap(find.byKey(const Key('buyViewClearAddressFieldButtonKey')));
+ expect(address, isEmpty);
+ }
+
+ Future<void> waitForAddress(String expected) => ui.until(
+ () => address == expected,
+ 'the address field to show $expected',
+ );
+
+ /// Taps "Choose from Stack", then [wallet] in the list that opens.
+ Future<void> chooseFromStack(Wallet wallet) async {
+ ui.stage = 'choose "${wallet.info.name}" from Stack';
+ await ui.tapText('Choose from Stack');
+ final wallets = find.byType(ChooseAddressFromStackView);
+ await ui.waitFor(wallets, description: 'wallet list');
+ await ui.tap(
+ find.descendant(of: wallets, matching: find.text(wallet.info.name)),
+ );
+ await ui.until(() => wallets.evaluate().isEmpty, 'wallet list to close');
+ }
+
+ /// Keeps frames coming, and app errors noticed, while [future] runs.
+ Future<T> _wait<T>(Future<T> future, String description) async {
+ var done = false;
+ late final T value;
+ Object? error;
+ StackTrace? trace;
+ unawaited(
+ future
+ .then<void>(
+ (result) => value = result,
+ onError: (Object e, StackTrace s) {
+ error = e;
+ trace = s;
+ },
+ )
+ .whenComplete(() => done = true),
+ );
+ await ui.until(() => done, description);
+ if (error != null) Error.throwWithStackTrace(error!, trace!);
+ return value;
+ }
+}
+
+/// Refuses the app's HTTP requests.
+final class _NoHttp extends HttpOverrides {
+ @override
+ HttpClient createHttpClient(SecurityContext? context) =>
+ super.createHttpClient(context)
+ ..connectionFactory = (url, proxyHost, proxyPort) => Future.error(
+ SocketException('Refused by the buy flow test: ${url.host}'),
+ );
+}
+
+class _TestPaths extends PathProviderPlatform {
+ _TestPaths(this.temp);
+
+ final String temp;
+
+ Future<String> _directory(String name) async =>
+ (await Directory(p.join(temp, name)).create(recursive: true)).path;
+
+ @override
+ Future<String?> getTemporaryPath() => _directory('temp');
+
+ @override
+ Future<String?> getApplicationSupportPath() => _directory('support');
+
+ @override
+ Future<String?> getLibraryPath() => _directory('library');
+
+ @override
+ Future<String?> getApplicationDocumentsPath() => _directory('documents');
+
+ @override
+ Future<String?> getApplicationCachePath() => _directory('cache');
+
+ @override
+ Future<String?> getDownloadsPath() => _directory('downloads');
+}
### integration_test/buy_flow/restored_wallet_test.dart
@@ -0,0 +1,46 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+
+import 'harness.dart';
+
+void main() {
+ buyFlowTest('a restored wallet moves every derivation path to an address '
+ 'without history', (t) async {
+ await t.launch();
+ // The first address of three derivation paths was paid before the restore.
+ const usedPaths = {
+ AddressType.p2pkh: "m/44'/0'/0'/0",
+ AddressType.p2sh: "m/49'/0'/0'/0",
+ AddressType.p2wpkh: "m/84'/0'/0'/0",
+ };
+ t.electrumX.pay(legacyAddress0);
+ t.electrumX.pay(nestedSegwitAddress0);
+ t.electrumX.pay(segwitAddress0);
+ final wallet = await t.addWallet('Restored wallet');
+
+ // The restore saves each path up to its last used address. A refresh then
+ // saves the next address of each one.
+ await t.refreshUntil(wallet, () async {
+ for (final type in usedPaths.keys) {
+ if ((await t.receiving(wallet, type)).length < 2) return false;
+ }
+ return true;
+ }, 'a new address on every used derivation path');
+ for (final MapEntry(key: type, value: path) in usedPaths.entries) {
+ expect(
+ (await t.receiving(wallet, type)).map((e) => e.derivationPath!.value),
+ ['$path/0', '$path/1'],
+ reason: type.name,
+ );
+ }
+ // Taproot has no history, so it stays where it is.
+ expect((await t.receiving(wallet, AddressType.p2tr)).map((e) => e.value), [
+ taprootAddress0,
+ ]);
+
+ // The Buy form offers the unused native SegWit address.
+ await t.openBuy();
+ await t.chooseFromStack(wallet);
+ await t.waitForAddress(segwitAddress1);
+ });
+}
### integration_test/buy_flow/taproot_wallet_test.dart
@@ -0,0 +1,55 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+
+import 'harness.dart';
+
+void main() {
+ buyFlowTest('a Taproot wallet gets one saved native SegWit address, and a '
+ 'new one once that has been paid', (t) async {
+ await t.launch();
+ final wallet = await t.addWallet('Taproot wallet');
+ expect(wallet.info.mainAddressType, AddressType.p2tr);
+ expect(wallet.info.cachedReceivingAddress, taprootAddress0);
+ expect(await t.receiving(wallet, AddressType.p2wpkh), isEmpty);
+
+ await t.openBuy();
+ expect(t.address, isEmpty);
+
+ // Simplex does not accept Taproot, so the wallet derives a BIP84 address
+ // and saves it.
+ await t.chooseFromStack(wallet);
+ await t.waitForAddress(segwitAddress0);
+ var saved = await t.receiving(wallet, AddressType.p2wpkh);
+ expect(saved.map((e) => e.value), [segwitAddress0]);
+ expect(saved.single.derivationPath!.value, "m/84'/0'/0'/0/0");
+ // Every refresh now checks it for payments.
+ expect(
+ (await wallet.fetchAddressesForElectrumXScan()).map((e) => e.value),
+ contains(segwitAddress0),
+ );
+ // The wallet's own receiving address is still its Taproot one.
+ expect(wallet.info.cachedReceivingAddress, taprootAddress0);
+
+ // Choosing the wallet again reuses the saved address.
+ await t.clearAddress();
+ await t.chooseFromStack(wallet);
+ await t.waitForAddress(segwitAddress0);
+ expect(await t.receiving(wallet, AddressType.p2wpkh), hasLength(1));
+
+ // Once the address has been paid, a refresh saves the next one and the
+ // form offers that.
+ t.electrumX.pay(segwitAddress0);
+ await t.refreshUntil(
+ wallet,
+ () async => (await t.receiving(wallet, AddressType.p2wpkh)).length > 1,
+ 'a new native SegWit address',
+ );
+ await t.clearAddress();
+ await t.chooseFromStack(wallet);
+ await t.waitForAddress(segwitAddress1);
+ saved = await t.receiving(wallet, AddressType.p2wpkh);
+ expect(saved.map((e) => e.value), [segwitAddress0, segwitAddress1]);
+ expect(saved.last.derivationPath!.value, "m/84'/0'/0'/0/1");
+ expect(wallet.info.cachedReceivingAddress, taprootAddress0);
+ });
+}
### integration_test/buy_flow/view_only_wallet_test.dart
@@ -0,0 +1,50 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+
+import 'harness.dart';
+
+void main() {
+ buyFlowTest('a view only wallet is used as is, or declined when it only '
+ 'has Taproot addresses', (t) async {
+ await t.launch();
+ final seed = await t.addWallet('Seed wallet');
+ final xPubs = (await seed.getXPubs()).xpubs;
+ final segwit = await t.addViewOnlyWallet(
+ 'View only SegWit',
+ xPubs.singleWhere((e) => e.path == "m/84'/0'/0'"),
+ );
+ final taproot = await t.addViewOnlyWallet(
+ 'View only Taproot',
+ xPubs.singleWhere((e) => e.path == "m/86'/0'/0'"),
+ );
+ await t.openBuy();
+
+ // Its own address is not Taproot, so it is used as is.
+ await t.chooseFromStack(segwit);
+ await t.waitForAddress(segwitAddress0);
+
+ // A view only wallet has the public key of one derivation path, so a
+ // Taproot one cannot derive the BIP84 address the form needs.
+ await t.chooseFromStack(taproot);
+ final title = find.text('Wallet not supported');
+ await t.ui.waitFor(title, description: 'view only Taproot dialog');
+ expect(t.formTakesInput, isFalse);
+ expect(
+ find.textContaining('a view only Taproot wallet has no other address'),
+ findsOneWidget,
+ );
+
+ // OK closes the dialog and nothing else.
+ t.ui.stage = 'close the dialog';
+ await t.ui.tapText('OK');
+ await t.ui.until(() => title.evaluate().isEmpty, 'the dialog to close');
+ expect(t.formTakesInput, isTrue);
+ expect(t.address, segwitAddress0);
+ expect(await t.receiving(taproot, AddressType.p2wpkh), isEmpty);
+
+ // The form still works afterwards.
+ await t.clearAddress();
+ await t.chooseFromStack(segwit);
+ await t.waitForAddress(segwitAddress0);
+ });
+}
### integration_test/wallet_creation/ui.dart
@@ -7,9 +7,12 @@ import 'package:flutter_test/flutter_test.dart';
/// Bounded real-app pumping. Never print finders containing recovery words.
class TestUI {
- TestUI(this.tester);
+ TestUI(this.tester, {this.reportPrefix = 'WALLET_CREATION_'});
final WidgetTester tester;
+
+ /// Starts every line this prints, so a runner can pick them out.
+ final String reportPrefix;
final errors = <Object>[];
File? errorLog;
String _stage = 'startup';
@@ -20,7 +23,7 @@ class TestUI {
}
void report(String message) =>
- debugPrintSynchronously('WALLET_CREATION_$message');
+ debugPrintSynchronously('$reportPrefix$message');
Future<void> pump() async {
await tester
### test/pages/buy_view/buy_form_choose_from_stack_test.dart
@@ -0,0 +1,241 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:platform/platform.dart' as platform;
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/pages/buy_view/buy_form.dart';
+import 'package:stackwallet/pages/exchange_view/choose_address_from_stack_view.dart';
+import 'package:stackwallet/providers/global/wallets_provider.dart';
+import 'package:stackwallet/services/wallets.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/themes/theme_providers.dart';
+import 'package:stackwallet/utilities/enums/derive_path_type_enum.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/impl/bitcoin_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+import '../../sample_data/theme_json.dart';
+import '../send_view/support/send_view_harness.dart';
+
+const _walletId = 'buy-form-test';
+
+Address _address(String value, AddressType type) => Address(
+ walletId: _walletId,
+ value: value,
+ publicKey: [],
+ derivationIndex: 0,
+ derivationPath: null,
+ type: type,
+ subType: AddressSubType.receiving,
+);
+
+class _Wallet extends BitcoinWallet {
+ _Wallet({required this.viewOnly, required this.current, this.fallback})
+ : super(CryptoCurrencyNetwork.main);
+
+ final bool viewOnly;
+ final Address current;
+ final Address? fallback;
+ int fallbackCalls = 0;
+
+ @override
+ String get walletId => _walletId;
+
+ @override
+ bool get isViewOnly => viewOnly;
+
+ @override
+ Future<Address?> getCurrentReceivingAddress() async => current;
+
+ @override
+ Future<Address> getOrCreateCurrentReceivingAddress({
+ required DerivePathType derivePathType,
+ }) async {
+ fallbackCalls++;
+ return fallback!;
+ }
+}
+
+class _FakeWallets extends Fake implements Wallets {
+ _FakeWallets(this.wallet);
+
+ final Wallet wallet;
+
+ @override
+ Wallet getWallet(String walletId) => wallet;
+}
+
+/// Stands in for the wallet chooser: returns the wallet the way it does.
+class _Chooser extends StatelessWidget {
+ const _Chooser();
+
+ @override
+ Widget build(BuildContext context) => Scaffold(
+ body: TextButton(
+ onPressed: () => Navigator.of(context)
+ .pop((walletId: _walletId, address: 'unused', walletName: 'Wallet')),
+ child: const Text('pick'),
+ ),
+ );
+}
+
+class _PopCounter extends NavigatorObserver {
+ int pops = 0;
+
+ @override
+ void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => pops++;
+}
+
+void main() {
+ late platform.Platform originalPlatform;
+
+ setUpAll(loadButtonFont);
+ setUp(() => originalPlatform = Util.layoutPlatform);
+ tearDown(() => Util.layoutPlatform = originalPlatform);
+
+ final field = find.byKey(const Key('buyViewReceiveAddressFieldKey'));
+ const homeKey = Key('home');
+
+ /// Pumps the Buy form where each layout really hosts it: directly under the
+ /// app's navigator on mobile, inside a nested navigator on desktop.
+ Future<({_PopCounter root, _PopCounter nested})> pumpForm(
+ WidgetTester tester,
+ _Wallet wallet,
+ ) async {
+ tester.view.physicalSize = const Size(1600, 2400);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+
+ final root = _PopCounter();
+ final nested = _PopCounter();
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+
+ Route<dynamic> route(RouteSettings settings) => MaterialPageRoute<dynamic>(
+ settings: settings,
+ builder: (_) => settings.name == ChooseAddressFromStackView.routeName
+ ? const _Chooser()
+ : const Scaffold(body: BuyForm()),
+ );
+
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [
+ themeProvider.overrideWithProvider(StateProvider((ref) => theme)),
+ pWallets.overrideWithValue(_FakeWallets(wallet)),
+ ],
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ navigatorObservers: [root],
+ onGenerateRoute: Util.isDesktop ? null : route,
+ home: Util.isDesktop
+ ? Scaffold(
+ key: homeKey,
+ body: Navigator(onGenerateRoute: route, observers: [nested]),
+ )
+ : const Scaffold(key: homeKey, body: BuyForm()),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return (root: root, nested: nested);
+ }
+
+ Future<void> chooseWallet(WidgetTester tester) async {
+ await tester.tap(find.text('Choose from Stack', findRichText: true));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('pick'));
+ await tester.pumpAndSettle();
+ }
+
+ String fieldText(WidgetTester tester) =>
+ tester.widget<TextField>(field).controller!.text;
+
+ // The form and the dialog only ask whether the layout is desktop, so one
+ // OS of each kind covers both.
+ for (final (layout, os) in [('mobile', 'android'), ('desktop', 'macos')]) {
+ group('$layout layout', () {
+ setUp(
+ () => Util.layoutPlatform = platform.FakePlatform(operatingSystem: os),
+ );
+
+ testWidgets('a view only Taproot wallet shows a dialog', (tester) async {
+ final wallet = _Wallet(
+ viewOnly: true,
+ current: _address('bc1ptaproot', AddressType.p2tr),
+ );
+ final pops = await pumpForm(tester, wallet);
+ await tester.enterText(field, 'previous');
+ await tester.pumpAndSettle();
+
+ await chooseWallet(tester);
+
+ expect(find.text('Wallet not supported'), findsOneWidget);
+ expect(
+ find.textContaining('a view only Taproot wallet has no other'),
+ findsOneWidget,
+ );
+ // The chooser is closed and the form is still there under the dialog.
+ expect(find.byType(_Chooser), findsNothing);
+ expect(find.byType(BuyForm), findsOneWidget);
+ expect(wallet.fallbackCalls, 0);
+ final rootPops = pops.root.pops;
+ final nestedPops = pops.nested.pops;
+
+ await tester.tap(find.text('OK'));
+ await tester.pumpAndSettle();
+
+ // Closing the dialog pops that one route and nothing else.
+ expect(find.text('Wallet not supported'), findsNothing);
+ expect(pops.root.pops, rootPops + 1);
+ expect(pops.nested.pops, nestedPops);
+ expect(find.byKey(homeKey), findsOneWidget);
+ expect(find.byType(BuyForm), findsOneWidget);
+ expect(fieldText(tester), 'previous');
+ expect(tester.takeException(), isNull);
+
+ // The form still works afterwards.
+ await chooseWallet(tester);
+ expect(find.text('Wallet not supported'), findsOneWidget);
+ });
+
+ testWidgets('a Taproot wallet with a seed gets its BIP84 address', (
+ tester,
+ ) async {
+ final wallet = _Wallet(
+ viewOnly: false,
+ current: _address('bc1ptaproot', AddressType.p2tr),
+ fallback: _address('bc1qfallback', AddressType.p2wpkh),
+ );
+ await pumpForm(tester, wallet);
+
+ await chooseWallet(tester);
+
+ expect(find.text('Wallet not supported'), findsNothing);
+ expect(fieldText(tester), 'bc1qfallback');
+ expect(wallet.fallbackCalls, 1);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('a view only wallet on another path is used as is', (
+ tester,
+ ) async {
+ final wallet = _Wallet(
+ viewOnly: true,
+ current: _address('bc1qcurrent', AddressType.p2wpkh),
+ );
+ await pumpForm(tester, wallet);
+
+ await chooseWallet(tester);
+
+ expect(find.text('Wallet not supported'), findsNothing);
+ expect(fieldText(tester), 'bc1qcurrent');
+ expect(wallet.fallbackCalls, 0);
+ expect(tester.takeException(), isNull);
+ });
+ });
+ }
+}Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.