Cw 1681 bitcoin accounts code enhancements (#3728)
What changed, and why it matters
This commit is a large internal refactor of how Bitcoin-style wallets in Cake Wallet store and derive account keys. It replaces scattered maps of HD keys with a single shared 'ElectrumAccounts' model, initializes those keys earlier during wallet creation, and changes the wallet-keys screen to show the master xPrv/xPub instead of per-account WIF/private key. There is also a specific fix for Litecoin MWEB change-address detection. The changes look like a normal code-cleanup and bug-fix patch; there is no direct evidence in the commit of a security vulnerability being fixed, but any refactor that touches key derivation deserves careful review because mistakes could affect which addresses are generated or which private keys are exposed.
Treat this as a high-touch refactor requiring focused QA on address derivation correctness, account switching, wallet restore from seed/xpub, and hardware-wallet paths. Verify that the new ElectrumAccounts model derives identical receive/change keys for all supported address types and account indexes compared to the previous implementation. Confirm the wallet keys screen no longer leaks unintended keys and that view-only wallets correctly show no private material. Run the new and existing cw_bitcoin tests, especially address derivation and Litecoin MWEB tests, before release.
Security signals we found
Refactor of BIP32 HD key derivation and account key storage across multiple coin modules
Wallet keys view model now exposes master xPrv and xPub instead of per-account private key
Change in how legacy change HDs are identified, with a new regression test for Litecoin MWEB change addresses
Removal of direct mainHdByTypeAndAccount/sideHdByTypeAndAccount maps in favor of centralized ElectrumAccounts model
Early initialization of account HD keys during wallet construction rather than lazy preparation
Evidence from the diff
The patch consolidates BIP32 HD key management for Electrum/Bitcoin/Litecoin/Bitcoin Cash/Dogecoin wallets into a new ElectrumAccounts/ElectrumAccount/AccountHdKeys class hierarchy. Previously, mainHdByTypeAndAccount and sideHdByTypeAndAccount maps were passed around and populated lazily; now an ElectrumAccounts object is created in the ElectrumWallet constructor, derives account keys up front, and is shared with the addresses class. Key derivation logic was moved from _prepareHdForAccount into ElectrumAccounts._deriveHd, with behavior preserved for seed-based vs xpub-only wallets. The wallet keys display now returns master-level WIF/xPrv/xPub/masterFingerprint when a master HD is available, and falls back to empty strings for view-only wallets. A new test verifies that Litecoin MWEB change addresses are only identified when the legacy change HD is used, fixing a prior detection bug.
Changed components
cw_bitcoin/lib/electrum_wallet.dartcw_bitcoin/lib/electrum_wallet_addresses.dartcw_bitcoin/lib/electrum_account.dartcw_bitcoin/lib/bitcoin_wallet.dartcw_bitcoin/lib/bitcoin_wallet_addresses.dartcw_bitcoin/lib/litecoin_wallet.dartcw_bitcoin/lib/litecoin_wallet_addresses.dartcw_bitcoin_cash/lib/src/bitcoin_cash_wallet.dartcw_bitcoin_cash/lib/src/bitcoin_cash_wallet_addresses.dartcw_dogecoin/lib/src/dogecoin_wallet.dartcw_dogecoin/lib/src/dogecoin_wallet_addresses.dartlib/view_model/wallet_keys_view_model.dartInspect captured patch +500 / −373
### cw_bitcoin/lib/bitcoin_wallet.dart
@@ -80,6 +80,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
bool? alwaysScan,
bool? useLightning,
String? cachedLightningAddress,
+ List<int>? accountIndexes,
}) : super(
mnemonic: mnemonic,
passphrase: passphrase,
@@ -101,6 +102,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
networkParam == BitcoinNetwork.testnet ? CryptoCurrency.tbtc : CryptoCurrency.btc,
alwaysScan: alwaysScan,
useLightning: useLightning ?? true,
+ accountIndexes: accountIndexes
) {
// in a standard BIP44 wallet, mainHd derivation path = m/84'/0'/0'/0 (account 0, index unspecified here)
// the sideHd derivation path = m/84'/0'/0'/1 (account 1, index unspecified here)
@@ -131,12 +133,8 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
initialChangeAddressIndex: initialChangeAddressIndex,
initialSilentAddresses: initialSilentAddresses,
initialSilentAddressIndex: initialSilentAddressIndex,
- mainHdByTypeAndAccount: mainHdByTypeAndAccount,
- sideHdByTypeAndAccount: sideHdByTypeAndAccount,
- accountIndexes: [currentAccountIndex],
+ accounts: accounts,
currentAccountIndex: currentAccountIndex,
- legacyMainHd: mainHd,
- legacySideHd: sideHd,
network: networkParam ?? network,
masterHd: seedBytes != null ? Bip32Slip10Secp256k1.fromSeed(seedBytes) : null,
isHardwareWallet: walletInfo.isHardwareWallet,
@@ -312,6 +310,9 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
}
}
+ final accountIndexes =
+ (await walletInfo.getAccounts()).map((account) => account.accountIndex).toList();
+
return BitcoinWallet(
mnemonic: mnemonic,
xpub: keysData.xPub != null ? convertZpubToXpub(keysData.xPub!) : null,
@@ -335,6 +336,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
useLightning: snp?.useLightning,
cachedLightningAddress: snp?.cachedLightningAddress,
payjoinBox: payjoinBox,
+ accountIndexes: accountIndexes,
);
}
### cw_bitcoin/lib/bitcoin_wallet_addresses.dart
@@ -10,7 +10,6 @@ import 'package:cw_core/payment_uris.dart';
import 'package:cw_core/receive_page_option.dart';
import 'package:cw_core/unspent_coin_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
-import 'package:cw_core/wallet_info.dart';
import 'package:mobx/mobx.dart';
import 'package:payjoin_flutter/receive.dart' as payjoin;
@@ -22,13 +21,8 @@ class BitcoinWalletAddresses = BitcoinWalletAddressesBase with _$BitcoinWalletAd
abstract class BitcoinWalletAddressesBase extends ElectrumWalletAddresses with Store {
BitcoinWalletAddressesBase(
- WalletInfo walletInfo, {
- required super.mainHdByTypeAndAccount,
- required super.sideHdByTypeAndAccount,
- required super.accountIndexes,
- required super.currentAccountIndex,
- required super.legacySideHd,
- required super.legacyMainHd,
+ super.walletInfo, {
+ required super.accounts,
required super.network,
required super.isHardwareWallet,
required this.payjoinManager,
@@ -39,7 +33,8 @@ abstract class BitcoinWalletAddressesBase extends ElectrumWalletAddresses with S
super.initialSilentAddressIndex = 0,
super.masterHd,
super.lightningWallet,
- }) : super(walletInfo);
+ super.currentAccountIndex,
+ });
final PayjoinManager payjoinManager;
### cw_bitcoin/lib/electrum_account.dart
@@ -0,0 +1,184 @@
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/electrum_wallet_addresses.dart";
+import "package:cw_core/utils/print_verbose.dart";
+
+int purposeForType(BitcoinAddressType type) {
+ switch (type.value) {
+ case 'P2PKH':
+ return 44;
+ case 'P2SH/P2WPKH':
+ return 49;
+ case 'P2WPKH':
+ return 84;
+ case 'P2TR':
+ return 86;
+ default:
+ return 84;
+ }
+}
+
+class ElectrumAccounts {
+ ElectrumAccounts({
+ required List<BitcoinAddressType> primaryTypes,
+ required Bip32Slip10Secp256k1 accountHd,
+ Bip32Slip10Secp256k1? masterHd,
+ int? coinType,
+ List<BitcoinAddressType> extraTypes = EXTRA_ACCOUNT_ADDRESS_TYPES,
+ }) : _primaryTypes = List.unmodifiable(primaryTypes),
+ _extraTypes = List.unmodifiable(extraTypes),
+ _accountHd = accountHd,
+ _masterHd = masterHd,
+ _coinType = coinType;
+
+ final List<BitcoinAddressType> _primaryTypes;
+ final List<BitcoinAddressType> _extraTypes;
+ final Bip32Slip10Secp256k1 _accountHd;
+ final Bip32Slip10Secp256k1? _masterHd;
+ final int? _coinType;
+ final Map<int, ElectrumAccount> _byIndex = {};
+ final Map<int, AccountHdKeys> _hdByIndex = {};
+
+ List<int> get indexes => _byIndex.keys.toList()..sort();
+
+ ElectrumAccount? operator [](int index) => _byIndex[index];
+
+ Bip32Slip10Secp256k1? hdFor({
+ required int accountIndex,
+ required BitcoinAddressType type,
+ required bool isChange,
+ bool isLegacy = false,
+ }) =>
+ _hdByIndex[accountIndex]?.branch(type, isChange: isChange, isLegacy: isLegacy);
+
+ ElectrumAccount getOrCreate(int index) {
+ final existing = _byIndex[index];
+ if (existing != null) return existing;
+
+ final account = ElectrumAccount(
+ index: index,
+ label: index == 0 ? "Primary account" : "Account $index",
+ supportedTypes: index == 0 ? _primaryTypes : _extraTypes,
+ );
+
+ _hdByIndex[index] = _deriveHd(index, account.supportedTypes);
+ _byIndex[index] = account;
+
+ printV("[ELECTRUM ACCOUNTS] added account $index "
+ '(${account.supportedTypes.map((t) => t.value).join('/')}), now $indexes');
+ return account;
+ }
+
+ bool contains(int index) => _byIndex.containsKey(index);
+
+ void remove(int index) {
+ _hdByIndex.remove(index);
+ if (_byIndex.remove(index) != null) {
+ printV("[ELECTRUM ACCOUNTS] removed account $index, now $indexes");
+ }
+ }
+
+ Bip32Slip10Secp256k1? receiveHd(int index, BitcoinAddressType type) =>
+ _hdByIndex[index]?.receive(type);
+
+ bool isLegacyChange(Bip32Slip10Secp256k1 hd) => _hdByIndex[0]?.isLegacyChange(hd) ?? false;
+
+ AccountHdKeys _deriveHd(int index, List<BitcoinAddressType> types) {
+ final hd = AccountHdKeys();
+ final masterHd = _masterHd;
+ final coinType = _coinType;
+
+ if (masterHd != null && coinType != null) {
+ final accountHdByPath = <String, Bip32Slip10Secp256k1>{};
+
+ for (final type in types) {
+ final accountPath = "m/${purposeForType(type)}'/$coinType'/$index'";
+ final accountHd = accountHdByPath[accountPath] ??=
+ masterHd.derivePath(accountPath) as Bip32Slip10Secp256k1;
+
+ hd.set(
+ type,
+ receive: accountHd.childKey(Bip32KeyIndex(0)),
+ change: accountHd.childKey(Bip32KeyIndex(1)),
+ );
+ }
+ } else {
+ for (final type in types) {
+ hd.set(
+ type,
+ receive: _accountHd.childKey(Bip32KeyIndex(0)),
+ change: _accountHd.childKey(Bip32KeyIndex(1)),
+ );
+ }
+ }
+
+ if (index == 0) {
+ hd.setLegacy(
+ receive: _accountHd.childKey(Bip32KeyIndex(0)),
+ change: _accountHd.childKey(Bip32KeyIndex(1)),
+ );
+ }
+
+ return hd;
+ }
+
+ @override
+ String toString() =>
+ 'ElectrumAccounts(${indexes.map((i) => '${_byIndex[i]} ${_hdByIndex[i]}').join(',\n')})';
+}
+
+class ElectrumAccount {
+ ElectrumAccount({
+ required this.index,
+ required this.label,
+ required List<BitcoinAddressType> supportedTypes,
+ }) : supportedTypes = List.unmodifiable(supportedTypes);
+
+ final int index;
+ String label;
+ final List<BitcoinAddressType> supportedTypes;
+
+ @override
+ String toString() =>
+ 'ElectrumAccount(index: $index, label: $label, types: ${supportedTypes.map((t) => t.value).join('/')})';
+}
+
+class AccountHdKeys {
+ final Map<BitcoinAddressType, Bip32Slip10Secp256k1> _receive = {};
+ final Map<BitcoinAddressType, Bip32Slip10Secp256k1> _change = {};
+
+ Bip32Slip10Secp256k1? _legacyReceive;
+ Bip32Slip10Secp256k1? _legacyChange;
+
+ void setLegacy({required Bip32Slip10Secp256k1 receive, required Bip32Slip10Secp256k1 change}) {
+ _legacyReceive = receive;
+ _legacyChange = change;
+ }
+
+ void set(
+ BitcoinAddressType type, {
+ required Bip32Slip10Secp256k1 receive,
+ required Bip32Slip10Secp256k1 change,
+ }) {
+ _receive[type] = receive;
+ _change[type] = change;
+ }
+
+ Bip32Slip10Secp256k1? receive(BitcoinAddressType type) => _receive[type];
+
+ Bip32Slip10Secp256k1? branch(
+ BitcoinAddressType type, {
+ required bool isChange,
+ bool isLegacy = false,
+ }) {
+ if (isLegacy) return isChange ? _legacyChange : _legacyReceive;
+ return isChange ? _change[type] : _receive[type];
+ }
+
+ bool isLegacyChange(Bip32Slip10Secp256k1 hd) => identical(hd, _legacyChange);
+
+ @override
+ String toString() => 'AccountHdKeys(receive: ${_receive.keys.map((t) => t.value).join('/')}, '
+ 'change: ${_change.keys.map((t) => t.value).join('/')}, '
+ "legacy: ${_legacyReceive != null})";
+}
### cw_bitcoin/lib/electrum_wallet.dart
@@ -4,6 +4,8 @@ import 'dart:isolate';
import 'dart:math' show Random, min;
import 'package:bitcoin_base/bitcoin_base.dart';
+import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_account.dart";
import 'package:cw_bitcoin/lightning/lightning_addres_type.dart';
import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
@@ -84,9 +86,10 @@ abstract class ElectrumWalletBase
CryptoCurrency? currency,
bool? alwaysScan,
bool useLightning = true,
+ List<int>? accountIndexes,
}) : _masterHD = getMasterHD(seedBytes, network, walletInfo.hardwareWalletType),
accountHD = getAccountHDWallet(
- currency, network, seedBytes, xpub, derivationInfo, walletInfo.hardwareWalletType),
+ currency, network, seedBytes, xpub, derivationInfo, walletInfo.hardwareWalletType,),
syncStatus = NotConnectedSyncStatus(),
_password = password,
_feeRates = <int>[],
@@ -112,21 +115,18 @@ abstract class ElectrumWalletBase
reaction((_) => syncStatus, _syncStatusReaction);
sharedPrefs.complete(SharedPreferences.getInstance());
- _prepareHdForAccount(currentAccountIndex, currency);
- }
- int _purposeForType(BitcoinAddressType type) {
- switch (type.value) {
- case 'P2PKH':
- return 44;
- case 'P2SH/P2WPKH':
- return 49;
- case 'P2WPKH':
- return 84;
- case 'P2TR':
- return 86;
- default:
- return 84;
+ final isElectrumDerivation = derivationInfo.derivationType == DerivationType.electrum;
+ accounts = ElectrumAccounts(
+ primaryTypes: supportedAddressTypes(walletInfo.type),
+ accountHd: accountHD,
+ masterHd: _masterHD,
+ coinType: currency != null && !isElectrumDerivation ? _coinTypeFor(currency) : null,
+ );
+
+ final indexes = hasAccountsSupport ? (accountIndexes ?? [currentAccountIndex]) : [0];
+ for (final accountIndex in indexes) {
+ accounts.getOrCreate(accountIndex);
}
}
@@ -164,11 +164,11 @@ abstract class ElectrumWalletBase
}
final coinType = _coinTypeFor(currency);
- final purpose = _purposeForType(record.type);
+ final purpose = purposeForType(record.type);
return "m/$purpose'/$coinType'/${record.accountIndex}'";
}
- List<BitcoinAddressType> supportedAddressTypes(WalletType type) {
+ static List<BitcoinAddressType> supportedAddressTypes(WalletType type) {
switch (type) {
case WalletType.bitcoin:
return BITCOIN_ADDRESS_TYPES;
@@ -309,8 +309,7 @@ abstract class ElectrumWalletBase
final Bip32Slip10Secp256k1 accountHD;
final String? _mnemonic;
- final mainHdByTypeAndAccount = <int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>>{};
- final sideHdByTypeAndAccount = <int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>>{};
+ late final ElectrumAccounts accounts;
Bip32Slip10Secp256k1 get mainHd => accountHD.childKey(Bip32KeyIndex(0));
@@ -343,55 +342,15 @@ abstract class ElectrumWalletBase
bool _isSyncing = false;
Future<WalletInfoAccount> loadCurrentAccount() async {
- final accounts = await walletInfo.getAccounts();
- final current = accounts.firstWhere(
+ final accountInfos = await walletInfo.getAccounts();
+ final current = accountInfos.firstWhere(
(account) => account.accountIndex == currentAccountIndex,
- orElse: () => accounts.first,
+ orElse: () => accountInfos.first,
);
return current;
}
- Future<List<int>> loadAccountIndexes() async {
- if (!hasAccountsSupport) return [0];
-
- final accounts = await walletInfo.getAccounts();
- return accounts.map((account) => account.accountIndex).toList();
- }
-
- void _prepareHdForAccount(int accountIndex, CryptoCurrency? currency) {
- if (mainHdByTypeAndAccount.containsKey(accountIndex)) return;
-
- // For the first account, we support all address types. For extra accounts, we only support SegwitAddresType.p2wpkh.
- final supportedTypes =
- accountIndex == 0 ? supportedAddressTypes(walletInfo.type) : EXTRA_ACCOUNT_ADDRESS_TYPES;
- final isElectrumDerivation = derivationInfo.derivationType == DerivationType.electrum;
- final canDeriveFromSeed = _masterHD != null && currency != null;
-
- final mainMap = mainHdByTypeAndAccount[accountIndex] ??= {};
- final sideMap = sideHdByTypeAndAccount[accountIndex] ??= {};
-
- if (canDeriveFromSeed && !isElectrumDerivation) {
- final coinType = _coinTypeFor(currency);
- final accountHdByPath = <String, Bip32Slip10Secp256k1>{};
-
- for (final type in supportedTypes) {
- final accountPath = "m/${_purposeForType(type)}'/$coinType'/$accountIndex'";
- final accountHd = accountHdByPath[accountPath] ??=
- _masterHD!.derivePath(accountPath) as Bip32Slip10Secp256k1;
-
- mainMap[type] = accountHd.childKey(Bip32KeyIndex(0));
- sideMap[type] = accountHd.childKey(Bip32KeyIndex(1));
- }
- } else {
- // case for Electrum derivation or when we don't have seed but only xpub (view only wallet)
- for (final type in supportedTypes) {
- mainMap[type] = mainHd; // accountHD.child(0)
- sideMap[type] = sideHd; // accountHD.child(1)
- }
- }
- }
-
ElectrumBalance balanceForAccount(int accountIndex) =>
accountBalances[accountIndex] ?? ElectrumBalance.zero(currency);
@@ -418,7 +377,7 @@ abstract class ElectrumWalletBase
newBalances[accountIndex] = current;
}
- for (final accountIndex in walletAddresses.accountIndexes) {
+ for (final accountIndex in accounts.indexes) {
newBalances.putIfAbsent(accountIndex, () => ElectrumBalance.zero(currency));
}
@@ -505,16 +464,14 @@ abstract class ElectrumWalletBase
@action
Future<void> setCurrentAccount(int accountIndex) async {
- final isNewAccount = !walletAddresses.accountIndexes.contains(accountIndex);
+ final isNewAccount = !accounts.contains(accountIndex);
if (isNewAccount) {
- walletAddresses.accountIndexes.add(accountIndex);
-
accountBalances[accountIndex] = ElectrumBalance.zero(currency);
}
await walletInfo.setSelectedAccount(accountIndex);
- _prepareHdForAccount(accountIndex, currency);
+ final account = accounts.getOrCreate(accountIndex);
walletAddresses.currentAccountIndex = accountIndex;
@@ -525,7 +482,7 @@ abstract class ElectrumWalletBase
if (isNewAccount) {
await walletAddresses.prepareAccountAddresses(
accountIndex,
- types: accountIndex == 0 ? BITCOIN_ADDRESS_TYPES : EXTRA_ACCOUNT_ADDRESS_TYPES,
+ types: account.supportedTypes,
);
await walletAddresses.updateAddressesInBox();
}
@@ -540,11 +497,7 @@ abstract class ElectrumWalletBase
if (isNewAccount && !_isSyncing) {
final histories = <String, ElectrumTransactionInfo>{};
- final typesToFetch = accountIndex == 0 ? BITCOIN_ADDRESS_TYPES : EXTRA_ACCOUNT_ADDRESS_TYPES;
- // Explicit for clarity — fetchTransactionsForAddressTypeBatch already skips types
- // with no addresses for this account, so this doesn't change RPC calls, just intent.
-
- for (final addressType in typesToFetch) {
+ for (final addressType in account.supportedTypes) {
if (shouldUseBatchFetching) {
await fetchTransactionsForAddressTypeBatch(histories, addressType,
accountIndex: accountIndex);
@@ -685,25 +638,32 @@ abstract class ElectrumWalletBase
String? publicKey;
// `keys` is wallet-level metadata
- final hd =
- mainHdByTypeAndAccount[0]?[SegwitAddresType.p2wpkh] ?? mainHd;
+ if (_masterHD == null) {
+ return BitcoinWalletKeys(
+ wif: '',
+ privateKey: '',
+ publicKey: '',
+ xpub: xpub,
+ masterFingerprint: '',
+ );
+ }
try {
- wif = WifEncoder.encode(hd.privateKey.raw, netVer: network.wifNetVer);
+ wif = WifEncoder.encode(_masterHD!.privateKey.raw, netVer: network.wifNetVer);
} catch (_) {}
try {
- privateKey = hd.privateKey.toHex();
+ privateKey = _masterHD!.privateKey.toExtended;
} catch (_) {}
try {
- publicKey = hd.publicKey.toHex();
+ publicKey = _masterHD!.publicKey.toHex();
} catch (_) {}
return BitcoinWalletKeys(
wif: wif ?? '',
privateKey: privateKey ?? '',
publicKey: publicKey ?? '',
xpub: xpub,
- masterFingerprint: _masterHD?.fingerPrint.toHex() ?? '',
+ masterFingerprint: _masterHD!.fingerPrint.toHex() ?? '',
);
}
@@ -732,14 +692,8 @@ abstract class ElectrumWalletBase
static const int _autoSaveInterval = 1;
Future<void> init() async {
- final accountIndexes = await loadAccountIndexes();
-
- for (final accountIndex in accountIndexes) {
- _prepareHdForAccount(accountIndex, currency);
- }
-
- await walletAddresses.init(accountIndexes: accountIndexes);
+ await walletAddresses.init();
await transactionHistory.init();
await cleanUpDuplicateUnspentCoins();
_seedAccountBalancesFromAddressRecords();
@@ -2460,7 +2414,7 @@ abstract class ElectrumWalletBase
newBalances[addr.accountIndex] = current;
}
- for (final accountIndex in walletAddresses.accountIndexes) {
+ for (final accountIndex in accounts.indexes) {
newBalances.putIfAbsent(accountIndex, () => ElectrumBalance.zero(currency));
}
@@ -3372,21 +3326,14 @@ abstract class ElectrumWalletBase
while (accountIndex < maxProbAccounts) {
final isAccountProbe = accountIndex > 0;
- if (!mainHdByTypeAndAccount.containsKey(accountIndex)) {
- _prepareHdForAccount(accountIndex, currency);
- }
+ final isNewAccount = !accounts.contains(accountIndex);
+ final addressTypesForAccount = accounts.getOrCreate(accountIndex).supportedTypes;
- if (!walletAddresses.accountIndexes.contains(accountIndex)) {
- walletAddresses.accountIndexes.add(accountIndex);
- await walletAddresses.prepareAccountAddresses(
- accountIndex,
- types: isAccountProbe ? EXTRA_ACCOUNT_ADDRESS_TYPES : BITCOIN_ADDRESS_TYPES,
- );
+ if (isNewAccount) {
+ await walletAddresses.prepareAccountAddresses(accountIndex, types: addressTypesForAccount);
}
- final probeTypes = isAccountProbe ? EXTRA_ACCOUNT_ADDRESS_TYPES : BITCOIN_ADDRESS_TYPES;
-
- for (final addressType in probeTypes) {
+ for (final addressType in addressTypesForAccount) {
if (shouldUseBatchFetching) {
await fetchTransactionsForAddressTypeBatch(
historiesWithDetails,
@@ -3412,18 +3359,21 @@ abstract class ElectrumWalletBase
persistedAccounts.any((account) => account.accountIndex == accountIndex);
if (isAccountProbe && !isUserAccount) {
- walletAddresses.accountIndexes.remove(accountIndex);
- walletAddresses.removeAddressesForAccount(accountIndex);
+ await walletAddresses.removeAddressesForAccount(accountIndex);
+ accounts.remove(accountIndex);
}
break;
}
// If the account has history, add it to the wallet (if it's not the first account).
if (isAccountProbe) {
- await walletInfo.addAccount(
- accountIndex: accountIndex,
- label: "Account $accountIndex",
- );
+ final persisted = await walletInfo.getAccounts();
+ if (!persisted.any((a) => a.accountIndex == accountIndex)) {
+ await walletInfo.addAccount(
+ accountIndex: accountIndex,
+ label: accounts[accountIndex]!.label,
+ );
+ }
}
// Move on to the next account index
accountIndex++;
@@ -4171,14 +4121,14 @@ abstract class ElectrumWalletBase
if (hasAccountsSupport) {
final perAccount = <int, ElectrumBalance>{};
- final accounts = <int>{
+ final accountIndexes = <int>{
...confirmedByAccount.keys,
...unconfirmedByAccount.keys,
...frozenByAccount.keys,
- ...walletAddresses.accountIndexes,
+ ...accounts.indexes,
};
- for (final account in accounts) {
+ for (final account in accountIndexes) {
perAccount[account] = ElectrumBalance(
confirmed: Money.fromInt(confirmedByAccount[account] ?? 0, currency),
unconfirmed: Money.fromInt(unconfirmedByAccount[account] ?? 0, currency),
@@ -4732,21 +4682,14 @@ abstract class ElectrumWalletBase
}
}
- Bip32Slip10Secp256k1 _hdForAddressRecord({required BaseBitcoinAddressRecord record}) {
- final addrType = record.type;
-
- if (record.isLegacyDerivation) {
- return record.isHidden ? walletAddresses.legacySideHd : walletAddresses.legacyMainHd;
- }
-
- final accountIndex = record.accountIndex;
-
- if (record.isHidden) {
- return sideHdByTypeAndAccount[accountIndex]?[addrType] ?? sideHd;
- } else {
- return mainHdByTypeAndAccount[accountIndex]?[addrType] ?? mainHd;
- }
- }
+ Bip32Slip10Secp256k1 _hdForAddressRecord({required BaseBitcoinAddressRecord record}) =>
+ accounts.hdFor(
+ accountIndex: record.accountIndex,
+ type: record.type,
+ isChange: record.isHidden,
+ isLegacy: record.isLegacyDerivation,
+ ) ??
+ (record.isHidden ? sideHd : mainHd);
}
class ScanNode {
### cw_bitcoin/lib/electrum_wallet_addresses.dart
@@ -8,6 +8,7 @@ import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:breez_sdk_spark_flutter/breez_sdk_spark.dart';
import 'package:cw_bitcoin/bitcoin_address_record.dart';
import 'package:cw_bitcoin/bitcoin_unspent.dart';
+import "package:cw_bitcoin/electrum_account.dart";
import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/lightning/lightning_addres_type.dart';
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
@@ -76,12 +77,7 @@ int firstFreeIndex(Set<int> takenIndexes) {
abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
ElectrumWalletAddressesBase(
WalletInfo walletInfo, {
- required this.mainHdByTypeAndAccount,
- required this.sideHdByTypeAndAccount,
- required this.accountIndexes,
- required this.currentAccountIndex,
- required this.legacyMainHd,
- required this.legacySideHd,
+ required this.accounts,
required this.network,
required this.isHardwareWallet,
List<BitcoinAddressRecord>? initialAddresses,
@@ -92,6 +88,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
List<BitcoinAddressRecord>? initialMwebAddresses,
Bip32Slip10Secp256k1? masterHd,
BitcoinAddressType? initialAddressPageType,
+ this.currentAccountIndex = 0,
this.lightningWallet,
}) : _addresses = ObservableList<BitcoinAddressRecord>.of((initialAddresses ?? []).toSet()),
addressesByReceiveType =
@@ -104,12 +101,6 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
.toSet()),
currentReceiveAddressIndexByType = initialRegularAddressIndex ?? {},
currentChangeAddressIndexByType = initialChangeAddressIndex ?? {},
- _addressPageType = _resolveInitialAddressPageType(
- initialAddressPageType: initialAddressPageType,
- walletInfo: walletInfo,
- mainHdByTypeAndAccount: mainHdByTypeAndAccount,
- currentAccountIndex: currentAccountIndex,
- ),
silentAddresses = ObservableList<BitcoinSilentPaymentAddressRecord>.of(
(initialSilentAddresses ?? []).toSet()),
currentSilentAddressIndex = initialSilentAddressIndex,
@@ -118,6 +109,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
lockedReceiveAddressByType = ObservableMap<BitcoinAddressType, String>(),
lightningAddress = lightningWallet?.cachedAddress,
super(walletInfo) {
+ _addressPageType = _resolveInitialAddressPageType(initialAddressPageType);
if (masterHd != null) {
final silentPaymentsHd = masterHd.derivePath(SILENT_PAYMENTS_ACCOUNT_PATH);
@@ -176,17 +168,14 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
// TODO: add this variable in `litecoin_wallet_addresses` and just add a cast in cw_bitcoin to use it
final ObservableList<BitcoinAddressRecord> mwebAddresses;
final BasedUtxoNetwork network;
- final Map<int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>> mainHdByTypeAndAccount;
- final Map<int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>> sideHdByTypeAndAccount;
- List<int> accountIndexes;
+ final ElectrumAccounts accounts;
- @observable
- int currentAccountIndex;
- final Bip32Slip10Secp256k1 legacyMainHd;
- final Bip32Slip10Secp256k1 legacySideHd;
final bool isHardwareWallet;
LightningWallet? lightningWallet;
+ @observable
+ int currentAccountIndex;
+
@observable
ObservableMap<BitcoinAddressType, String> lockedReceiveAddressByType;
@@ -237,9 +226,8 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
"Error: Unable to fetch your Lightning address, please check your network connection.";
}
- final accountIndexForCheck = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
- if (!_isAddressTypeSupportedForAccount(addressPageType, accountIndexForCheck)) {
- printV("addressPageType $addressPageType is not supported for account $accountIndexForCheck");
+ if (!_isAddressTypeSupportedForAccount(addressPageType, currentAccountIndex)) {
+ printV("addressPageType $addressPageType is not supported for account $currentAccountIndex");
return "";
}
@@ -350,7 +338,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return silentAddress?.toString() ?? '';
}
- return _firstAddressForType(addressPageType);
+ return _firstReceiveAddressForType(addressPageType);
}
String get payjoinCompatibleAddress {
@@ -359,19 +347,14 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
? SegwitAddresType.p2wpkh
: addressPageType;
- return _firstAddressForType(addrType);
+ return _firstReceiveAddressForType(addrType);
}
- String _firstAddressForType(BitcoinAddressType addrType) {
- final mainMap = walletInfo.type == WalletType.bitcoin
- ? mainHdByTypeAndAccount[currentAccountIndex]
- : mainHdByTypeAndAccount[0];
+ String _firstReceiveAddressForType(BitcoinAddressType addrType) {
+ final hd = accounts.receiveHd(currentAccountIndex, addrType);
+ if (hd == null) return "";
- final mainHd = mainMap?[addrType] ?? mainMap?.values.first;
-
- if (mainHd == null) return '';
-
- return getAddress(index: 0, hd: mainHd, addressType: addrType);
+ return getAddress(index: 0, hd: hd, addressType: addrType);
}
Map<String, int> currentReceiveAddressIndexByType;
@@ -412,11 +395,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
});
@override
- Future<void> init({List<int> accountIndexes = const []}) async {
- final effectiveAccountIndexes =
- accountIndexes.isNotEmpty ? accountIndexes : this.accountIndexes;
-
- if (accountIndexes.isNotEmpty) this.accountIndexes = accountIndexes;
+ Future<void> init() async {
if (walletInfo.type == WalletType.bitcoinCash) {
await _generateInitialAddresses(type: P2pkhAddressType.p2pkh);
} else if (walletInfo.type == WalletType.litecoin) {
@@ -427,11 +406,11 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
} else if (walletInfo.type == WalletType.dogecoin) {
await _generateInitialAddresses(type: P2pkhAddressType.p2pkh);
} else if (walletInfo.type == WalletType.bitcoin) {
- for (final accountIndex in effectiveAccountIndexes) {
+ for (final accountIndex in accounts.indexes) {
await prepareAccountAddresses(
accountIndex,
- types: accountIndex == 0 ? BITCOIN_ADDRESS_TYPES : EXTRA_ACCOUNT_ADDRESS_TYPES,
+ types: accounts[accountIndex]!.supportedTypes,
includeLegacy: accountIndex == 0,
);
}
@@ -487,10 +466,8 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return address;
}
- bool _isCurrentAccountAddress(BitcoinAddressRecord addressRecord) {
- return walletInfo.type != WalletType.bitcoin ||
- addressRecord.accountIndex == currentAccountIndex;
- }
+ bool _isCurrentAccountAddress(BitcoinAddressRecord addressRecord) =>
+ addressRecord.accountIndex == currentAccountIndex;
Map<String, String> get labels {
final G = ECPublic.fromBytes(BigintUtils.toBytes(Curves.generatorSecp256k1.x, length: 32));
@@ -563,22 +540,24 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return address;
}
- final accountIndex = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
-
final newAddressIndex = firstFreeIndex(
- _takenStandardIndexes(isHidden: false, type: addressPageType, accountIndex: accountIndex),
+ _takenStandardIndexes(
+ isHidden: false,
+ type: addressPageType,
+ accountIndex: currentAccountIndex,
+ ),
);
final hd = _hdForAddressGeneration(
isHidden: false,
type: addressPageType,
isLegacyDerivation: false,
- accountIndex: accountIndex,
+ accountIndex: currentAccountIndex,
);
final address = BitcoinAddressRecord(
getAddress(index: newAddressIndex, hd: hd, addressType: addressPageType),
index: newAddressIndex,
- accountIndex: accountIndex,
+ accountIndex: currentAccountIndex,
isHidden: false,
isHiddenChecked: true,
isLegacyDerivation: false,
@@ -1075,11 +1054,8 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
type is! LightningAddressType && type != SilentPaymentsAddresType.p2sp;
BitcoinAddressType resolvedType = type;
- if (needsAccountScopedHd) {
- final accountIndex = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
- if (!_isAddressTypeSupportedForAccount(type, accountIndex)) {
- resolvedType = EXTRA_ACCOUNT_ADDRESS_TYPES.first;
- }
+ if (needsAccountScopedHd && !_isAddressTypeSupportedForAccount(type, currentAccountIndex)) {
+ resolvedType = EXTRA_ACCOUNT_ADDRESS_TYPES.first;
}
_addressPageType = resolvedType;
@@ -1124,39 +1100,25 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
}
- bool _isAddressTypeSupportedForAccount(BitcoinAddressType type, int accountIndex) {
- final effectiveAccountIndex = walletInfo.type == WalletType.bitcoin ? accountIndex : 0;
- return mainHdByTypeAndAccount[effectiveAccountIndex]?.containsKey(type) ?? false;
- }
+ bool _isAddressTypeSupportedForAccount(BitcoinAddressType type, int accountIndex) =>
+ accounts[accountIndex]?.supportedTypes.contains(type) ?? false;
+
+ BitcoinAddressType _resolveInitialAddressPageType(BitcoinAddressType? initialAddressPageType) {
- static BitcoinAddressType _resolveInitialAddressPageType({
- required BitcoinAddressType? initialAddressPageType,
- required WalletInfo walletInfo,
- required Map<int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>> mainHdByTypeAndAccount,
- required int currentAccountIndex,
- }) {
final resolved = initialAddressPageType ??
(walletInfo.addressPageType != null
? walletInfo.addressPageType == LightningAddressType.p2l.value
? LightningAddressType.p2l
: BitcoinAddressType.fromValue(walletInfo.addressPageType!)
: SegwitAddresType.p2wpkh);
- // Non-account-scoped address types (Lightning, Silent Payments) don't need
- // an HD map entry.
if (resolved is LightningAddressType || resolved == SilentPaymentsAddresType.p2sp) {
return resolved;
}
- final effectiveAccountIndex = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
-
- final isValid = mainHdByTypeAndAccount[effectiveAccountIndex]?.containsKey(resolved) ?? false;
-
- if (!isValid) {
- return EXTRA_ACCOUNT_ADDRESS_TYPES.first;
- }
-
- return resolved;
+ return _isAddressTypeSupportedForAccount(resolved, currentAccountIndex)
+ ? resolved
+ : EXTRA_ACCOUNT_ADDRESS_TYPES.first;
}
Bip32Slip10Secp256k1 _hdForAddressGeneration({
@@ -1165,32 +1127,16 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
required bool isLegacyDerivation,
int accountIndex = 0,
}) {
- if (isLegacyDerivation) {
- if (accountIndex != 0) {
- throw UnsupportedAddressTypeForAccountException(
- "Legacy derivation is only supported for the first account");
- }
-
- return isHidden ? legacySideHd : legacyMainHd;
- }
-
- final effectiveAccountIndex = walletInfo.type == WalletType.bitcoin ? accountIndex : 0;
-
- final map = isHidden
- ? sideHdByTypeAndAccount[effectiveAccountIndex]
- : mainHdByTypeAndAccount[effectiveAccountIndex];
-
- if (map == null) {
- throw UnsupportedAddressTypeForAccountException(
- "HD map not found for account $effectiveAccountIndex");
- }
-
- final hd = map[type];
+ final hd = accounts.hdFor(
+ accountIndex: accountIndex,
+ type: type,
+ isChange: isHidden,
+ isLegacy: isLegacyDerivation,
+ );
if (hd == null) {
throw UnsupportedAddressTypeForAccountException(
- "HD not found for account $accountIndex type $type");
+ "No HD for account $accountIndex, type $type, legacy $isLegacyDerivation");
}
-
return hd;
}
### cw_bitcoin/lib/litecoin_wallet.dart
@@ -118,12 +118,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
initialRegularAddressIndex: initialRegularAddressIndex,
initialChangeAddressIndex: initialChangeAddressIndex,
initialMwebAddresses: initialMwebAddresses,
- mainHdByTypeAndAccount: mainHdByTypeAndAccount,
- sideHdByTypeAndAccount: sideHdByTypeAndAccount,
- accountIndexes: [currentAccountIndex],
- currentAccountIndex: currentAccountIndex,
- legacyMainHd: mainHd,
- legacySideHd: sideHd,
+ accounts: accounts,
network: network,
mwebHd: mwebHd,
mwebEnabled: mwebEnabled,
### cw_bitcoin/lib/litecoin_wallet_addresses.dart
@@ -25,12 +25,7 @@ class LitecoinWalletAddresses = LitecoinWalletAddressesBase with _$LitecoinWalle
abstract class LitecoinWalletAddressesBase extends ElectrumWalletAddresses with Store {
LitecoinWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByTypeAndAccount,
- required super.sideHdByTypeAndAccount,
- required super.accountIndexes,
- required super.currentAccountIndex,
- required super.legacyMainHd,
- required super.legacySideHd,
+ required super.accounts,
required super.network,
required super.isHardwareWallet,
required this.mwebHd,
@@ -70,9 +65,9 @@ abstract class LitecoinWalletAddressesBase extends ElectrumWalletAddresses with
List.filled(32, 0);
@override
- Future<void> init({List<int> accountIndexes = const []}) async {
+ Future<void> init() async {
if (!isHardwareWallet) await initMwebAddresses();
- await super.init(accountIndexes: accountIndexes);
+ await super.init();
}
@computed
@@ -152,10 +147,9 @@ abstract class LitecoinWalletAddressesBase extends ElectrumWalletAddresses with
BitcoinAddressType? addressType,
}) {
if (addressType == SegwitAddresType.mweb) {
- if (mwebAddrs.length == 0) {
- return "";
- }
- return hd == legacySideHd ? mwebAddrs[0] : mwebAddrs[index + 1];
+ if (mwebAddrs.isEmpty) return "";
+ final isChange = accounts.isLegacyChange(hd);
+ return isChange ? mwebAddrs[0] : mwebAddrs[index + 1];
}
return generateP2WPKHAddress(hd: hd, index: index, network: network);
}
### cw_bitcoin/test/address_index_test.dart
@@ -2,6 +2,7 @@ import "package:bitcoin_base/bitcoin_base.dart";
import "package:blockchain_utils/blockchain_utils.dart";
import "package:cw_bitcoin/bitcoin_address_record.dart";
import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_account.dart";
import "package:cw_bitcoin/electrum_wallet_addresses.dart";
import "package:cw_bitcoin/payjoin/manager.dart";
import "package:cw_bitcoin/utils.dart";
@@ -20,8 +21,6 @@ final Bip32Slip10Secp256k1 _p2wpkhReceiveHd = _hd("m/84'/0'/0'/0");
final Bip32Slip10Secp256k1 _p2wpkhChangeHd = _hd("m/84'/0'/0'/1");
final Bip32Slip10Secp256k1 _p2pkhReceiveHd = _hd("m/44'/0'/0'/0");
final Bip32Slip10Secp256k1 _p2pkhChangeHd = _hd("m/44'/0'/0'/1");
-final Bip32Slip10Secp256k1 _legacyReceiveHd = _hd("m/0'/0");
-final Bip32Slip10Secp256k1 _legacyChangeHd = _hd("m/0'/1");
BitcoinAddressRecord _record(
int index, {
@@ -77,34 +76,26 @@ class _NoPayjoin implements PayjoinManager {
dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
}
+ElectrumAccounts _accounts({required Bip32Slip10Secp256k1 legacyAccountHd}) => ElectrumAccounts(
+ primaryTypes: [SegwitAddresType.p2wpkh, P2pkhAddressType.p2pkh],
+ accountHd: legacyAccountHd,
+ masterHd: _master,
+ coinType: 0,
+)..getOrCreate(0);
+
class _Addresses extends BitcoinWalletAddresses {
_Addresses(
- super.walletInfo, {
- required List<BitcoinAddressRecord> records,
- required Bip32Slip10Secp256k1 legacyReceiveHd,
- required Bip32Slip10Secp256k1 legacyChangeHd,
- }) : super(
- mainHdByTypeAndAccount: {
- 0: {
- SegwitAddresType.p2wpkh: _p2wpkhReceiveHd,
- P2pkhAddressType.p2pkh: _p2pkhReceiveHd,
- },
- },
- sideHdByTypeAndAccount: {
- 0: {
- SegwitAddresType.p2wpkh: _p2wpkhChangeHd,
- P2pkhAddressType.p2pkh: _p2pkhChangeHd,
- },
- },
- accountIndexes: [0],
- currentAccountIndex: 0,
- legacyMainHd: legacyReceiveHd,
- legacySideHd: legacyChangeHd,
- network: BitcoinNetwork.mainnet,
- isHardwareWallet: false,
- payjoinManager: _NoPayjoin(),
- initialAddresses: records,
- );
+ super.walletInfo, {
+ required List<BitcoinAddressRecord> records,
+ required Bip32Slip10Secp256k1 legacyAccountHd,
+ }) : super(
+ accounts: _accounts(legacyAccountHd: legacyAccountHd),
+ currentAccountIndex: 0,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ initialAddresses: records,
+ );
@override
Future<void> saveAddressesInBox() async {}
@@ -130,8 +121,7 @@ Future<_Addresses> _addresses(
final _Addresses addresses = _Addresses(
walletInfo,
records: records,
- legacyReceiveHd: legacyIsSameChain ? _p2wpkhReceiveHd : _legacyReceiveHd,
- legacyChangeHd: legacyIsSameChain ? _p2wpkhChangeHd : _legacyChangeHd,
+ legacyAccountHd: legacyIsSameChain ? _hd("m/84'/0'/0'") : _hd("m/0'"),
);
await walletInfo.getManualAddresses();
return addresses;
### cw_bitcoin/test/bitcoin_message_sign_test.dart
@@ -5,6 +5,7 @@ import "package:blockchain_utils/blockchain_utils.dart";
import "package:cw_bitcoin/bitcoin_address_record.dart";
import "package:cw_bitcoin/bitcoin_message_sign.dart";
import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_account.dart";
import "package:cw_bitcoin/electrum_wallet.dart";
import "package:cw_bitcoin/payjoin/manager.dart";
import "package:cw_bitcoin/utils.dart";
@@ -50,25 +51,24 @@ class _NoUnspentsBox implements Box<UnspentCoinsInfo> {
dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
}
+ElectrumAccounts _accounts() => ElectrumAccounts(
+ primaryTypes: [SegwitAddresType.p2wpkh],
+ accountHd: _master.derivePath("m/84'/0'/0'") as Bip32Slip10Secp256k1,
+ masterHd: _master,
+ coinType: 0,
+)..getOrCreate(0);
+
class _Addresses extends BitcoinWalletAddresses {
_Addresses(super.walletInfo, List<BitcoinAddressRecord> records)
: super(
- mainHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _receiveHd},
- },
- sideHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _changeHd},
- },
- accountIndexes: [0],
- currentAccountIndex: 0,
- legacyMainHd: _receiveHd,
- legacySideHd: _changeHd,
- network: BitcoinNetwork.mainnet,
- isHardwareWallet: false,
- payjoinManager: _NoPayjoin(),
- masterHd: _master,
- initialAddresses: records,
- );
+ accounts: _accounts(),
+ currentAccountIndex: 0,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ masterHd: _master,
+ initialAddresses: records,
+ );
@override
Future<void> saveAddressesInBox() async {}
### cw_bitcoin/test/bitcoin_wallet_addresses_picker_test.dart
@@ -2,6 +2,7 @@ import "package:bitcoin_base/bitcoin_base.dart";
import "package:blockchain_utils/blockchain_utils.dart";
import "package:cw_bitcoin/bitcoin_address_record.dart";
import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_account.dart";
import "package:cw_bitcoin/electrum_wallet_addresses.dart";
import "package:cw_bitcoin/litecoin_wallet_addresses.dart";
import "package:cw_bitcoin/payjoin/manager.dart";
@@ -46,19 +47,25 @@ class _NoPayjoin implements PayjoinManager {
dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
}
+ElectrumAccounts _bitcoinAccounts() => ElectrumAccounts(
+ primaryTypes: [SegwitAddresType.p2wpkh],
+ accountHd: _hd("m/84'/0'/0'"),
+ masterHd: _master,
+ coinType: 0,
+)..getOrCreate(0);
+
+ElectrumAccounts _litecoinAccounts() => ElectrumAccounts(
+ primaryTypes: LITECOIN_ADDRESS_TYPES,
+ accountHd: _hd("m/84'/2'/0'"),
+ masterHd: _master,
+ coinType: 2,
+)..getOrCreate(0);
+
class _BitcoinAddresses extends BitcoinWalletAddresses {
_BitcoinAddresses(super.walletInfo)
: super(
- mainHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _receiveHd},
- },
- sideHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _changeHd},
- },
- accountIndexes: [0],
+ accounts: _bitcoinAccounts(),
currentAccountIndex: 0,
- legacyMainHd: _receiveHd,
- legacySideHd: _changeHd,
network: BitcoinNetwork.mainnet,
isHardwareWallet: false,
payjoinManager: _NoPayjoin(),
@@ -83,16 +90,7 @@ class _BitcoinAddresses extends BitcoinWalletAddresses {
class _LitecoinAddresses extends LitecoinWalletAddresses {
_LitecoinAddresses(super.walletInfo)
: super(
- mainHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _ltcReceiveHd, SegwitAddresType.mweb: _ltcReceiveHd},
- },
- sideHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _ltcChangeHd, SegwitAddresType.mweb: _ltcChangeHd},
- },
- accountIndexes: [0],
- currentAccountIndex: 0,
- legacyMainHd: _ltcReceiveHd,
- legacySideHd: _ltcChangeHd,
+ accounts: _litecoinAccounts(),
network: LitecoinNetwork.mainnet,
isHardwareWallet: false,
mwebHd: null,
@@ -178,7 +176,8 @@ void main() {
expect(addresses.address, _mweb);
expect(addresses.addressesMap[_mweb], "Active - MWEB");
- expect(addresses.addressesMap.values.where((label) => label.startsWith("Active")), hasLength(1));
+ expect(
+ addresses.addressesMap.values.where((label) => label.startsWith("Active")), hasLength(1));
expect(addresses.addressForBuy, _ltcReceive[1]);
});
### cw_bitcoin/test/electrum_wallet_connection_test.dart
@@ -7,6 +7,7 @@ import "package:bitcoin_base/bitcoin_base.dart";
import "package:blockchain_utils/blockchain_utils.dart";
import "package:cw_bitcoin/bitcoin_address_record.dart";
import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_account.dart";
import "package:cw_bitcoin/electrum_wallet.dart";
import "package:cw_bitcoin/payjoin/manager.dart";
import "package:cw_bitcoin/utils.dart";
@@ -42,33 +43,32 @@ class _NoUnspentsBox implements Box<UnspentCoinsInfo> {
dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
}
+ElectrumAccounts _accounts() => ElectrumAccounts(
+ primaryTypes: [SegwitAddresType.p2wpkh],
+ accountHd: _master.derivePath("m/84'/0'/0'") as Bip32Slip10Secp256k1,
+ masterHd: _master,
+ coinType: 0,
+)..getOrCreate(0);
+
class _Addresses extends BitcoinWalletAddresses {
_Addresses(super.walletInfo)
: super(
- mainHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _receiveHd},
- },
- sideHdByTypeAndAccount: {
- 0: {SegwitAddresType.p2wpkh: _changeHd},
- },
- accountIndexes: [0],
- currentAccountIndex: 0,
- legacyMainHd: _receiveHd,
- legacySideHd: _changeHd,
+ accounts: _accounts(),
+ currentAccountIndex: 0,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ masterHd: _master,
+ initialAddresses: [
+ for (var i = 0; i < _addressCount; i++)
+ BitcoinAddressRecord(
+ generateP2WPKHAddress(hd: _receiveHd, network: BitcoinNetwork.mainnet, index: i),
+ index: i,
+ type: SegwitAddresType.p2wpkh,
network: BitcoinNetwork.mainnet,
- isHardwareWallet: false,
- payjoinManager: _NoPayjoin(),
- masterHd: _master,
- initialAddresses: [
- for (var i = 0; i < _addressCount; i++)
- BitcoinAddressRecord(
- generateP2WPKHAddress(hd: _receiveHd, network: BitcoinNetwork.mainnet, index: i),
- index: i,
- type: SegwitAddresType.p2wpkh,
- network: BitcoinNetwork.mainnet,
- ),
- ],
- );
+ ),
+ ],
+ );
@override
Future<void> saveAddressesInBox() async {}
### cw_bitcoin/test/litecoin_mweb_change_address_test.dart
@@ -0,0 +1,103 @@
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/electrum_account.dart";
+import "package:cw_bitcoin/electrum_wallet_addresses.dart";
+import "package:cw_bitcoin/litecoin_wallet_addresses.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+final _master = Bip32Slip10Secp256k1.fromSeed(List<int>.generate(64, (i) => i));
+
+Bip32Slip10Secp256k1 _derive(String path) => _master.derivePath(path) as Bip32Slip10Secp256k1;
+
+final _accountHd = _derive("m/84'/2'/0'");
+
+const _mwebChange = "mweb_change";
+
+WalletInfo _walletInfo() => WalletInfo.external(
+ id: "litecoin_mweb_change_test",
+ name: "litecoin_mweb_change_test",
+ type: WalletType.litecoin,
+ isRecovery: false,
+ restoreHeight: 0,
+ date: DateTime(2026),
+ dirPath: "",
+ path: "",
+ address: "",
+ );
+
+ElectrumAccounts _accounts() => ElectrumAccounts(
+ primaryTypes: LITECOIN_ADDRESS_TYPES,
+ accountHd: _accountHd,
+ masterHd: _master,
+ coinType: 2,
+)..getOrCreate(0);
+
+LitecoinWalletAddresses _addresses(ElectrumAccounts accounts) {
+ final addresses = LitecoinWalletAddresses(
+ _walletInfo(),
+ accounts: accounts,
+ network: LitecoinNetwork.mainnet,
+ isHardwareWallet: false,
+ mwebHd: null,
+ mwebEnabled: false,
+ scanSecretOverride: null,
+ spendPubkeyOverride: null,
+ initialAddresses: [],
+ );
+ addresses.mwebAddrs
+ ..clear()
+ ..add(_mwebChange)
+ ..addAll([for (var i = 0; i < 30; i++) "mweb_receive_$i"]);
+ return addresses;
+}
+
+void main() {
+ setUpAll(() async {
+ sqfliteFfiInit();
+ db = await databaseFactoryFfi.openDatabase(inMemoryDatabasePath);
+ await db!.execute("CREATE TABLE walletInfoAddress "
+ "(walletInfoAddressId INTEGER PRIMARY KEY, walletInfoId INTEGER, type INTEGER, "
+ "address TEXT)");
+ });
+
+ test("standard MWEB change key does not map to the MWEB change address", () {
+ final accounts = _accounts();
+ final addresses = _addresses(accounts);
+ final changeHd = accounts.hdFor(
+ accountIndex: 0,
+ type: SegwitAddresType.mweb,
+ isChange: true,
+ )!;
+
+ final address = addresses.getAddress(
+ index: 0,
+ hd: changeHd,
+ addressType: SegwitAddresType.mweb,
+ );
+
+ expect(address, "mweb_receive_0");
+ });
+
+ test("legacy change key maps to the MWEB change address", () {
+ final accounts = _accounts();
+ final addresses = _addresses(accounts);
+ final legacyChangeHd = accounts.hdFor(
+ accountIndex: 0,
+ type: SegwitAddresType.mweb,
+ isChange: true,
+ isLegacy: true,
+ )!;
+
+ final address = addresses.getAddress(
+ index: 0,
+ hd: legacyChangeHd,
+ addressType: SegwitAddresType.mweb,
+ );
+
+ expect(address, _mwebChange);
+ });
+}
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet.dart
@@ -62,12 +62,7 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
initialAddresses: initialAddresses,
initialRegularAddressIndex: initialRegularAddressIndex,
initialChangeAddressIndex: initialChangeAddressIndex,
- mainHdByTypeAndAccount: mainHdByTypeAndAccount,
- sideHdByTypeAndAccount: sideHdByTypeAndAccount,
- accountIndexes: [currentAccountIndex],
- currentAccountIndex: currentAccountIndex,
- legacyMainHd: mainHd,
- legacySideHd: sideHd,
+ accounts: accounts,
network: network,
initialAddressPageType: addressPageType,
isHardwareWallet: walletInfo.isHardwareWallet,
@@ -88,8 +83,7 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
List<BitcoinAddressRecord>? initialAddresses,
ElectrumBalance? initialBalance,
Map<String, int>? initialRegularAddressIndex,
- Map<String, int>? initialChangeAddressIndex}) async {
- return BitcoinCashWallet(
+ Map<String, int>? initialChangeAddressIndex}) async => BitcoinCashWallet(
mnemonic: mnemonic,
password: password,
walletInfo: walletInfo,
@@ -104,7 +98,6 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
addressPageType: P2pkhAddressType.p2pkh,
passphrase: passphrase,
);
- }
static Future<BitcoinCashWallet> open({
required String name,
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet_addresses.dart
@@ -13,12 +13,7 @@ class BitcoinCashWalletAddresses = BitcoinCashWalletAddressesBase with _$Bitcoin
abstract class BitcoinCashWalletAddressesBase extends ElectrumWalletAddresses with Store {
BitcoinCashWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByTypeAndAccount,
- required super.sideHdByTypeAndAccount,
- required super.accountIndexes,
- required super.currentAccountIndex,
- required super.legacyMainHd,
- required super.legacySideHd,
+ required super.accounts,
required super.network,
required super.isHardwareWallet,
super.initialAddresses,
### cw_dogecoin/lib/src/dogecoin_wallet.dart
@@ -54,12 +54,7 @@ abstract class DogeCoinWalletBase extends ElectrumWallet with Store {
initialAddresses: initialAddresses,
initialRegularAddressIndex: initialRegularAddressIndex,
initialChangeAddressIndex: initialChangeAddressIndex,
- mainHdByTypeAndAccount: mainHdByTypeAndAccount,
- sideHdByTypeAndAccount: sideHdByTypeAndAccount,
- accountIndexes: [currentAccountIndex],
- currentAccountIndex: currentAccountIndex,
- legacyMainHd: mainHd,
- legacySideHd: sideHd,
+ accounts: accounts,
network: network,
initialAddressPageType: addressPageType,
isHardwareWallet: walletInfo.isHardwareWallet,
### cw_dogecoin/lib/src/dogecoin_wallet_addresses.dart
@@ -13,12 +13,7 @@ class DogeCoinWalletAddresses = DogeCoinWalletAddressesBase with _$DogeCoinWalle
abstract class DogeCoinWalletAddressesBase extends ElectrumWalletAddresses with Store {
DogeCoinWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByTypeAndAccount,
- required super.sideHdByTypeAndAccount,
- required super.accountIndexes,
- required super.currentAccountIndex,
- required super.legacyMainHd,
- required super.legacySideHd,
+ required super.accounts,
required super.network,
required super.isHardwareWallet,
super.initialAddresses,
### lib/view_model/wallet_keys_view_model.dart
@@ -227,10 +227,8 @@ abstract class WalletKeysViewModelBase with Store {
if ((electrumKeys['wif'] ?? '').isNotEmpty)
StandartListItem(title: "WIF", value: electrumKeys['wif']!),
if ((electrumKeys['privateKey'] ?? '').isNotEmpty)
- StandartListItem(title: S.current.private_key, value: electrumKeys['privateKey']!),
- if (electrumKeys['publicKey'] != null)
- StandartListItem(title: S.current.public_key, value: electrumKeys['publicKey']!),
- if (electrumKeys['xpub'] != null)
+ StandartListItem(title: "xPrv", value: electrumKeys['privateKey']!),
+ if ((electrumKeys['xpub'] ?? '').isNotEmpty)
StandartListItem(title: "xPub", value: electrumKeys['xpub']!),
]);
break;Why this scored 32/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.