Merge pull request #1541 from cypherstack/rotate-receiving-address-types
What changed, and why it matters
This commit changes how Stack Wallet picks and updates Bitcoin receiving addresses. It makes the wallet rotate (advance to a fresh address) not just on its main address type, but also on other supported address types when they have transaction history. It also changes the 'Buy' flow so that if a user selects a Taproot-only view-only wallet, the app shows a warning and refuses to use it, because that wallet type cannot derive the non-Taproot address the Buy partner requires. The change is primarily a privacy/usability improvement, but it touches address-derivation and transaction-scanning logic.
Review the new _checkOtherReceivingAddressesForTransactions loop for termination guarantees and ensure generateNextReceivingAddress cannot be called indefinitely if the server reports spurious transaction counts. Confirm that the view-only Taproot guard covers all entry points where a BIP84 address might be derived. Consider whether the change warrants a changelog note about improved address rotation and Buy-flow wallet compatibility.
Security signals we found
Address rotation logic added for non-main derivation paths
View-only Taproot wallet explicitly rejected in Buy flow to avoid deriving addresses without private key material
New test coverage for address reuse and rotation across BIP44/BIP84/BIP86 paths
No explicit vendor security disclosure or CVE references present in commit
Evidence from the diff
The commit adds address rotation across all supported derivation path types in ElectrumXInterface.checkReceivingAddressForTransactions via a new _checkOtherReceivingAddressesForTransactions helper. For each supported DerivePathType whose AddressType differs from the wallet’s main type, it walks saved receiving addresses forward while they have transaction history. In lib/pages/buy_view/buy_form.dart, it blocks view-only Taproot wallets from being used in the Buy flow because they cannot derive a BIP84 address. The rest of the diff is extensive test scaffolding (FakeElectrumX, integration tests, unit tests) validating restored wallets, Taproot wallets, view-only wallets, and address rotation behavior.
Changed components
lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dartlib/pages/buy_view/buy_form.dartintegration_test/buy_flow/*test/wallets/receiving_address_rotation_test.darttest/pages/buy_view/buy_form_choose_from_stack_test.dartInspect captured patch +1288 / −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
### lib/pages/buy_view/buy_form.dart
@@ -1240,6 +1240,29 @@ class _BuyFormState extends ConsumerState<BuyForm> {
final Address address;
if (currentAddress!.type == AddressType.p2tr &&
wallet is Bip39HDWallet) {
+ if (wallet.isViewOnly) {
+ // A view only wallet only has the public key of
+ // its own derivation path, so it cannot derive
+ // the BIP84 address used below.
+ if (context.mounted) {
+ await showDialog<void>(
+ context: context,
+ useRootNavigator: true,
+ builder: (_) => StackOkDialog(
+ desktopPopRootNavigator: true,
+ title: "Wallet not supported",
+ message:
+ "Taproot addresses are not allowed, "
+ "and a view only Taproot wallet has "
+ "no other address type. Choose "
+ "another wallet or enter an address.",
+ maxWidth: isDesktop ? 400 : null,
+ ),
+ );
+ }
+ return;
+ }
+
address = await wallet
.getOrCreateCurrentReceivingAddress(
derivePathType: DerivePathType.bip84,
### lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart
@@ -1816,6 +1816,9 @@ mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
// keep checking until address with no tx history is set as current
await checkReceivingAddressForTransactions();
}
+ } else if (!isViewOnly &&
+ info.otherData[WalletInfoKeys.reuseAddress] != true) {
+ await _checkOtherReceivingAddressesForTransactions();
}
} catch (e, s) {
Logging.instance.e(
@@ -1826,6 +1829,43 @@ mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
}
}
+ /// Does for the other supported derivation paths what
+ /// [checkReceivingAddressForTransactions] does for the main one: while the
+ /// latest saved receiving address has history, the next one is generated
+ /// and saved. A path without a saved receiving address is left alone.
+ Future<void> _checkOtherReceivingAddressesForTransactions() async {
+ for (final type in cryptoCurrency.supportedDerivationPathTypes) {
+ final addressType = type.getAddressType();
+
+ // Saved addresses are looked up by address type, so a path that shares
+ // the main address type (bch44, eCash44) cannot be told apart here.
+ if (addressType == info.mainAddressType) continue;
+
+ while (true) {
+ final current = await mainDB.isar.addresses
+ .where()
+ .walletIdEqualTo(walletId)
+ .filter()
+ .typeEqualTo(addressType)
+ .subTypeEqualTo(AddressSubType.receiving)
+ .sortByDerivationIndexDesc()
+ .findFirst();
+ if (current == null) break;
+
+ final txCount = await fetchTxCount(
+ addressScriptHash: cryptoCurrency.addressToScriptHash(
+ address: current.value,
+ ),
+ );
+ if (txCount == 0) break;
+
+ await mainDB.updateOrPutAddresses([
+ await generateNextReceivingAddress(derivePathType: type),
+ ]);
+ }
+ }
+ }
+
@override
Future<void> checkChangeAddressForTransactions() async {
if (isViewOnly &&
### 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);
+ });
+ });
+ }
+}
### test/wallets/receiving_address_rotation_test.dart
@@ -0,0 +1,203 @@
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart';
+import 'package:stackwallet/models/keys/view_only_wallet_data.dart';
+import 'package:stackwallet/utilities/enums/derive_path_type_enum.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_mixin_interfaces/extended_keys_interface.dart';
+
+import '../support/isar_test_utils.dart';
+
+class _Wallet extends BitcoinWallet {
+ _Wallet({this.viewOnlyPath}) : super(CryptoCurrencyNetwork.main) {
+ mainDB = MainDB.instance;
+ }
+
+ /// Account path of the xpub a view-only wallet watches. Null for a wallet
+ /// that holds its seed.
+ final String? viewOnlyPath;
+
+ /// Script hashes the fake server reports history for.
+ final Set<String> used = {};
+
+ @override
+ String get walletId => 'address-rotation-test';
+
+ @override
+ bool get isViewOnly => viewOnlyPath != null;
+
+ @override
+ ViewOnlyWalletType get viewOnlyType => ViewOnlyWalletType.xPub;
+
+ @override
+ Future<ViewOnlyWalletData> getViewOnlyWalletData() async =>
+ ExtendedKeysViewOnlyWalletData(
+ walletId: walletId,
+ xPubs: [
+ XPub(
+ path: viewOnlyPath!,
+ encoded: (await getRootHDNode())
+ .derivePath(viewOnlyPath!)
+ .hdPublicKey
+ .encode(cryptoCurrency.networkParams.pubHDPrefix),
+ ),
+ ],
+ );
+
+ @override
+ Future<coinlib.HDPrivateKey> getRootHDNode() async =>
+ coinlib.HDPrivateKey.fromSeed(Uint8List.fromList(List.filled(32, 1)));
+
+ @override
+ Future<int> fetchTxCount({required String addressScriptHash}) async =>
+ used.contains(addressScriptHash) ? 1 : 0;
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Isar isar;
+ late _Wallet wallet;
+
+ setUpAll(() async {
+ await initializeTestIsar();
+ await coinlib.loadCoinlib();
+ });
+ setUp(() async {
+ final directory = await Directory.systemTemp.createTemp(
+ 'stack_address_rotation_',
+ );
+ addTearDown(() => directory.delete(recursive: true));
+ isar = await Isar.open(
+ [AddressSchema, TransactionSchema, WalletInfoSchema],
+ directory: directory.path,
+ name: 'address-rotation-test',
+ inspector: false,
+ );
+ addTearDown(() => isar.close());
+ await MainDB.instance.initMainDB(mock: isar);
+ wallet = _Wallet();
+ await isar.writeTxn(
+ () => isar.walletInfo.put(
+ WalletInfo.createNew(
+ coin: wallet.cryptoCurrency,
+ name: 'address-rotation-test',
+ walletIdOverride: wallet.walletId,
+ ),
+ ),
+ );
+ // The Taproot address every Bitcoin wallet starts with.
+ await wallet.checkSaveInitialReceivingAddress();
+ });
+
+ Future<List<Address>> receiving(AddressType type) => isar.addresses
+ .where()
+ .walletIdEqualTo(wallet.walletId)
+ .filter()
+ .typeEqualTo(type)
+ .subTypeEqualTo(AddressSubType.receiving)
+ .sortByDerivationIndex()
+ .findAll();
+
+ /// Saves the next receiving address on [type], as the Receive view does.
+ Future<Address> saveNext(DerivePathType type) async {
+ final address = await wallet.generateNextReceivingAddress(
+ derivePathType: type,
+ );
+ await MainDB.instance.updateOrPutAddresses([address]);
+ return address;
+ }
+
+ void markUsed(Address address) => wallet.used.add(
+ wallet.cryptoCurrency.addressToScriptHash(address: address.value),
+ );
+
+ test('a used address is rotated on every derivation path', () async {
+ final taproot = (await receiving(AddressType.p2tr)).single;
+ final segwit = await saveNext(DerivePathType.bip84);
+ final legacy = await saveNext(DerivePathType.bip44);
+ markUsed(taproot);
+ markUsed(segwit);
+ markUsed(legacy);
+
+ await wallet.checkReceivingAddressForTransactions();
+
+ for (final type in [
+ AddressType.p2tr,
+ AddressType.p2wpkh,
+ AddressType.p2pkh,
+ ]) {
+ final addresses = await receiving(type);
+ expect(addresses.map((e) => e.derivationIndex), [0, 1], reason: '$type');
+ }
+ expect(
+ (await receiving(AddressType.p2wpkh)).last.derivationPath!.value,
+ "m/84'/0'/0'/0/1",
+ );
+ expect(
+ (await receiving(AddressType.p2pkh)).last.derivationPath!.value,
+ "m/44'/0'/0'/0/1",
+ );
+
+ // Only the main type's address becomes the wallet's receiving address.
+ expect(
+ wallet.info.cachedReceivingAddress,
+ (await receiving(AddressType.p2tr)).last.value,
+ );
+ });
+
+ test('rotation continues until an unused address is found', () async {
+ final first = await saveNext(DerivePathType.bip84);
+ markUsed(first);
+ // The next address already has history too, as after a restore.
+ markUsed(
+ await wallet.generateNextReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ ),
+ );
+
+ await wallet.checkReceivingAddressForTransactions();
+
+ final addresses = await receiving(AddressType.p2wpkh);
+ expect(addresses.map((e) => e.derivationIndex), [0, 1, 2]);
+ });
+
+ test('an unused address is kept', () async {
+ markUsed((await receiving(AddressType.p2tr)).single);
+ final segwit = await saveNext(DerivePathType.bip84);
+
+ await wallet.checkReceivingAddressForTransactions();
+
+ expect((await receiving(AddressType.p2wpkh)).single.value, segwit.value);
+ expect(await receiving(AddressType.p2tr), hasLength(2));
+ });
+
+ test('a path without a saved receiving address gets none', () async {
+ markUsed((await receiving(AddressType.p2tr)).single);
+
+ await wallet.checkReceivingAddressForTransactions();
+
+ expect(await receiving(AddressType.p2tr), hasLength(2));
+ expect(await isar.addresses.count(), 2);
+ });
+
+ test('a view-only wallet rotates the one path of its xpub', () async {
+ await isar.writeTxn(() => isar.addresses.clear());
+ wallet = _Wallet(viewOnlyPath: "m/84'/0'/0'");
+ await wallet.checkSaveInitialReceivingAddress();
+ markUsed((await receiving(AddressType.p2wpkh)).single);
+
+ await wallet.checkReceivingAddressForTransactions();
+
+ final addresses = await receiving(AddressType.p2wpkh);
+ expect(addresses.map((e) => e.derivationIndex), [0, 1]);
+ expect(await isar.addresses.count(), 2);
+ });
+}Why this scored 35/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.