Merge pull request #1537 from cypherstack/fix/simplex-current-receiving-address
What changed, and why it matters
This change fixes how Stack Wallet picks a Bitcoin receiving address when a user buys crypto through Simplex. Previously, the app could generate a fresh address every time instead of reusing the same one, which could cause funds sent to an earlier address to be harder to track or link. The patch makes the app persist and reuse a single BIP84 (SegWit) receiving address, and adds a lock so multiple simultaneous calls don't create duplicate addresses.
Review the new `getOrCreateCurrentReceivingAddress` method for correct handling of all `DerivePathType` values and ensure the mutex is used consistently across other wallet flows that generate receiving addresses. Verify that persisted addresses are properly backed up/restored with wallet state.
Security signals we found
Address reuse / derivation index stability for fiat-to-crypto buy flow
Race-condition protection via mutex for address generation
Removal of direct Isar query from UI layer in favor of wallet abstraction
New unit tests covering concurrency and address-type separation
Evidence from the diff
The commit introduces getOrCreateCurrentReceivingAddress() in Bip39HDWallet, which queries the local Isar database for the highest-derivation-index receiving address of a given type, returns it if found, or generates index 0 and persists it. A Mutex prevents race conditions. The buy flow in buy_form.dart is refactored to call this method for BIP84 addresses when the wallet’s current receiving address is Taproot (BIP86), instead of directly querying Isar and unconditionally generating a new address. Tests verify reuse, concurrency safety, exclusion of change addresses, and non-interference with Taproot addresses.
Changed components
lib/pages/buy_view/buy_form.dartlib/wallets/wallet/intermediate/bip39_hd_wallet.darttest/wallets/receiving_address_index_test.dartInspect captured patch +239 / −59
### lib/pages/buy_view/buy_form.dart
@@ -16,7 +16,6 @@ import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
-import 'package:isar_community/isar.dart';
import '../../app_config.dart';
import '../../models/buy/response_objects/crypto.dart';
@@ -1216,66 +1215,46 @@ class _BuyFormState extends ConsumerState<BuyForm> {
if (AppConfig.isStackCoin(selectedCrypto?.ticker))
CustomTextButton(
text: "Choose from ${AppConfig.prefix}",
- onTap: () {
+ onTap: () async {
try {
final coin = AppConfig.getCryptoCurrencyForTicker(
selectedCrypto!.ticker,
);
- Navigator.of(context)
- .pushNamed(
- ChooseAddressFromStackView.routeName,
- arguments: coin,
- )
- .then((value) async {
- if (value
- is ({
- String walletId,
- String address,
- String walletName,
- })) {
- final wallet = ref
- .read(pWallets)
- .getWallet(value.walletId);
-
- // _toController.text = manager.walletName;
- // model.recipientAddress =
- // await manager.currentReceivingAddress;
-
- final address = await wallet
- .getCurrentReceivingAddress();
-
- if (address!.type == AddressType.p2tr &&
- wallet is Bip39HDWallet) {
- // lets assume any wallet that has taproot also has segwit. WCGW
- final address =
- await ref
- .read(mainDBProvider)
- .isar
- .addresses
- .where()
- .walletIdEqualTo(wallet.walletId)
- .filter()
- .typeEqualTo(AddressType.p2wpkh)
- .sortByDerivationIndexDesc()
- .findFirst() ??
- await wallet.generateNextReceivingAddress(
- derivePathType: DerivePathType.bip84,
- );
-
- _receiveAddressController.text =
- address.value;
- } else {
- _receiveAddressController.text =
- address.value;
- }
-
- setState(() {
- _addressToggleFlag =
- _receiveAddressController.text.isNotEmpty;
- });
- validateAmount();
- }
- });
+ final value = await Navigator.of(context).pushNamed(
+ ChooseAddressFromStackView.routeName,
+ arguments: coin,
+ );
+ if (value
+ is ({
+ String walletId,
+ String address,
+ String walletName,
+ })) {
+ final wallet = ref
+ .read(pWallets)
+ .getWallet(value.walletId);
+
+ final currentAddress = await wallet
+ .getCurrentReceivingAddress();
+
+ final Address address;
+ if (currentAddress!.type == AddressType.p2tr &&
+ wallet is Bip39HDWallet) {
+ address = await wallet
+ .getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+ } else {
+ address = currentAddress;
+ }
+
+ _receiveAddressController.text = address.value;
+ setState(() {
+ _addressToggleFlag =
+ _receiveAddressController.text.isNotEmpty;
+ });
+ validateAmount();
+ }
} catch (e, s) {
Logging.instance.w("", error: e, stackTrace: s);
}
### lib/wallets/wallet/intermediate/bip39_hd_wallet.dart
@@ -3,6 +3,7 @@ import 'dart:typed_data';
import 'package:bip39/bip39.dart' as bip39;
import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
import 'package:isar_community/isar.dart';
+import 'package:mutex/mutex.dart';
import '../../../models/balance.dart';
import '../../../models/isar/models/blockchain_data/address.dart';
@@ -20,6 +21,8 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
with MultiAddressInterface<T>, ViewOnlyOptionInterface<T> {
Bip39HDWallet(super.cryptoCurrency);
+ final _receivingAddressMutex = Mutex();
+
Set<AddressType> get supportedAddressTypes => cryptoCurrency
.supportedDerivationPathTypes
.where((e) => e != DerivePathType.bip49)
@@ -84,6 +87,43 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
return address;
}
+ /// Returns the latest persisted receiving address for [derivePathType].
+ ///
+ /// If that typed receiving chain has not been initialized, derives and
+ /// persists index zero before returning it. Transaction history is
+ /// intentionally ignored, so repeated callers reuse the same address.
+ Future<Address> getOrCreateCurrentReceivingAddress({
+ required DerivePathType derivePathType,
+ }) async {
+ if (!cryptoCurrency.supportedDerivationPathTypes.contains(derivePathType)) {
+ throw Exception(
+ "Unsupported DerivePathType passed to "
+ "getOrCreateCurrentReceivingAddress().",
+ );
+ }
+
+ return _receivingAddressMutex.protect(() async {
+ final current = await mainDB.isar.addresses
+ .where()
+ .walletIdEqualTo(walletId)
+ .filter()
+ .typeEqualTo(derivePathType.getAddressType())
+ .subTypeEqualTo(AddressSubType.receiving)
+ .sortByDerivationIndexDesc()
+ .findFirst();
+
+ if (current != null) {
+ return current;
+ }
+
+ final address = await generateNextReceivingAddress(
+ derivePathType: derivePathType,
+ );
+ await mainDB.updateOrPutAddresses([address]);
+ return address;
+ });
+ }
+
@override
List<FilterOperation> get standardReceivingAddressFilters => [
// view only only have a single derivation path currently
### test/wallets/receiving_address_index_test.dart
@@ -54,13 +54,18 @@ void main() {
wallet = _Wallet();
});
- Address address(String value, int index, AddressSubType subType) => Address(
+ Address address(
+ String value,
+ int index,
+ AddressSubType subType, {
+ AddressType type = AddressType.p2wpkh,
+ }) => Address(
walletId: wallet.walletId,
value: value,
publicKey: [],
derivationIndex: index,
derivationPath: null,
- type: AddressType.p2wpkh,
+ type: type,
subType: subType,
);
@@ -94,4 +99,160 @@ void main() {
expect(generated.derivationPath!.value, "m/84'/0'/0'/0/0");
},
);
+
+ test(
+ 'getOrCreateCurrentReceivingAddress persists the first typed address',
+ () async {
+ final current = await wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+
+ final stored = await isar.addresses
+ .where()
+ .walletIdEqualTo(wallet.walletId)
+ .filter()
+ .valueEqualTo(current.value)
+ .findFirst();
+
+ expect(current.derivationIndex, 0);
+ expect(current.derivationPath!.value, "m/84'/0'/0'/0/0");
+ expect(current.subType, AddressSubType.receiving);
+ expect(stored?.value, current.value);
+ },
+ );
+
+ test(
+ 'getOrCreateCurrentReceivingAddress reuses the persisted address',
+ () async {
+ final first = await wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+ final second = await wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+
+ final receivingAddresses = await isar.addresses
+ .where()
+ .walletIdEqualTo(wallet.walletId)
+ .filter()
+ .typeEqualTo(AddressType.p2wpkh)
+ .subTypeEqualTo(AddressSubType.receiving)
+ .findAll();
+
+ expect(second.value, first.value);
+ expect(second.derivationIndex, 0);
+ expect(receivingAddresses, hasLength(1));
+ },
+ );
+
+ test(
+ 'concurrent getOrCreateCurrentReceivingAddress calls persist one address',
+ () async {
+ final addresses = await Future.wait(
+ List.generate(
+ 3,
+ (_) => wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ ),
+ ),
+ );
+
+ final receivingAddresses = await isar.addresses
+ .where()
+ .walletIdEqualTo(wallet.walletId)
+ .filter()
+ .typeEqualTo(AddressType.p2wpkh)
+ .subTypeEqualTo(AddressSubType.receiving)
+ .findAll();
+
+ expect(addresses.map((address) => address.value).toSet(), hasLength(1));
+ expect(receivingAddresses, hasLength(1));
+ expect(receivingAddresses.single.derivationIndex, 0);
+ },
+ );
+
+ test(
+ 'getOrCreateCurrentReceivingAddress excludes change addresses',
+ () async {
+ await MainDB.instance.putAddress(
+ address('change', 100, AddressSubType.change),
+ );
+
+ final current = await wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+
+ expect(current.derivationIndex, 0);
+ expect(current.subType, AddressSubType.receiving);
+ expect(await isar.addresses.count(), 2);
+ },
+ );
+
+ test(
+ 'getOrCreateCurrentReceivingAddress reuses an address with history',
+ () async {
+ final used = address('used', 7, AddressSubType.receiving);
+ final transaction = Transaction(
+ walletId: wallet.walletId,
+ txid: 'used-transaction',
+ timestamp: 1,
+ type: TransactionType.incoming,
+ subType: TransactionSubType.none,
+ amount: 1,
+ amountString: null,
+ fee: 0,
+ height: 1,
+ isCancelled: false,
+ isLelantus: null,
+ slateId: null,
+ otherData: null,
+ inputs: const [],
+ outputs: const [],
+ nonce: null,
+ numberOfMessages: null,
+ );
+ await isar.writeTxn(() async {
+ await isar.transactions.put(transaction);
+ await isar.addresses.put(used);
+ used.transactions.add(transaction);
+ await used.transactions.save();
+ });
+
+ final current = await wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+
+ expect(current.value, used.value);
+ expect(current.derivationIndex, 7);
+ expect(await isar.addresses.count(), 1);
+ },
+ );
+
+ test(
+ 'getOrCreateCurrentReceivingAddress leaves primary BIP86 unchanged',
+ () async {
+ final primary = address(
+ 'primary-taproot',
+ 4,
+ AddressSubType.receiving,
+ type: AddressType.p2tr,
+ );
+ await MainDB.instance.putAddress(primary);
+
+ final current = await wallet.getOrCreateCurrentReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+
+ final storedPrimary = await isar.addresses
+ .where()
+ .walletIdEqualTo(wallet.walletId)
+ .filter()
+ .valueEqualTo(primary.value)
+ .findFirst();
+ expect(current.type, AddressType.p2wpkh);
+ expect(current.derivationIndex, 0);
+ expect(storedPrimary?.value, primary.value);
+ expect(storedPrimary?.type, AddressType.p2tr);
+ },
+ );
}Why this scored 29/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.