- Fix signing messages to include change addresses as well
What changed, and why it matters
This commit fixes a bug in how Cake Wallet signs Bitcoin-style messages. Previously, the app could not correctly sign messages with 'change addresses' (a special type of address used when sending leftover funds back to yourself). The fix moves the address lookup logic into a shared helper so all wallet types use the same rules, and it adds tests proving that both regular and change addresses can now be signed. It also blocks signing with Taproot and MWEB addresses, which would otherwise produce misleading signatures. There is no direct evidence in the commit that this was exploited or reported as a security flaw.
Review the updated Ledger plugin commits referenced in pubspec.lock for any security-relevant changes, since the commit updates ledger-bitcoin, ledger-ethereum, and ledger-litecoin git refs. Otherwise, treat this as a correctness/refactoring patch and ensure the new tests pass.
Security signals we found
Refactor centralizes address validation and derivation-path construction for hardware signing
Change addresses are now included in address lookup, fixing a functional signing bug
Taproot and MWEB addresses are explicitly rejected for message signing
New unit tests cover receive/change address signing and address-type restrictions
Ledger plugin git refs updated in pubspec.lock (contextual, no diff details shown)
Evidence from the diff
The patch refactors message signing across Bitcoin, Litecoin, Bitcoin Cash, and Dogecoin wallets. A new helper getSigningAddressRecord replaces assertCanSignBitcoinMessage and now searches walletAddresses.allAddresses (which includes change addresses) instead of only receive addresses. The hardware-wallet signing path is moved from BitcoinWalletBase/LitecoinWalletBase into the shared ElectrumWallet.signMessage, using the resolved address record’s index and isHidden flag to build the correct BIP32 derivation path. Subclasses now only implement signMessageWithKey for the actual ECDSA signing. Tests verify that receive and change addresses produce distinct, verifiable signatures and that unknown, Taproot, and MWEB addresses are rejected.
Changed components
cw_bitcoin/lib/bitcoin_message_sign.dartcw_bitcoin/lib/electrum_wallet.dartcw_bitcoin/lib/bitcoin_wallet.dartcw_bitcoin/lib/litecoin_wallet.dartcw_bitcoin_cash/lib/src/bitcoin_cash_wallet.dartcw_dogecoin/lib/src/dogecoin_wallet.dartcw_bitcoin/test/bitcoin_message_sign_test.dartInspect captured patch +260 / −136
### cw_bitcoin/lib/bitcoin_message_sign.dart
@@ -1,19 +1,29 @@
+import "package:bitcoin_base/bitcoin_base.dart" show SegwitAddresType;
+import "package:cw_bitcoin/bitcoin_address_record.dart";
+
/// A blank address uses the wallet's main key. Any other address has to be
-/// one this wallet can derive. Silent payment addresses are not in that set,
-/// and signing them with the main key would look like proof for the wrong key.
-void assertCanSignBitcoinMessage({
+/// one this wallet can derive a key for. Silent payment and MWEB addresses
+/// have no such key, and signing them with another key would look like proof
+/// for the wrong key.
+BitcoinAddressRecord? getSigningAddressRecord({
required String? address,
- required bool heldByWallet,
- required bool isTaproot,
+ required Iterable<BitcoinAddressRecord> walletAddresses,
}) {
- final requested = address != null && address.trim().isNotEmpty;
- if (!requested) {
- return;
+ final requested = address?.trim() ?? "";
+ if (requested.isEmpty) {
+ return null;
}
- if (!heldByWallet) {
- throw UnsupportedError('Cannot sign a message for an address this wallet does not hold');
+
+ final record = walletAddresses.where((candidate) => candidate.address == requested).firstOrNull;
+ if (record == null) {
+ throw UnsupportedError("Cannot sign a message for an address this wallet does not hold");
}
- if (isTaproot) {
- throw UnsupportedError('Cannot sign message with Taproot address');
+ if (record.type == SegwitAddresType.p2tr) {
+ throw UnsupportedError("Cannot sign message with Taproot address");
}
+ if (record.type == SegwitAddresType.mweb) {
+ throw UnsupportedError("Cannot sign message with an MWEB address");
+ }
+
+ return record;
}
### cw_bitcoin/lib/bitcoin_wallet.dart
@@ -700,26 +700,6 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
}
}
- @override
- Future<String> signMessage(String message, {String? address = null}) async {
- if (walletInfo.isHardwareWallet) {
- final addressEntry = address != null
- ? walletAddresses.allAddresses.firstWhere((element) => element.address == address)
- : null;
- final index = addressEntry?.index ?? 0;
- final isChange = addressEntry?.isHidden == true ? 1 : 0;
- final derivationInfo = await walletInfo.getDerivationInfo();
- final accountPath = derivationInfo.derivationPath;
- final derivationPath = accountPath != null ? "$accountPath/$isChange/$index" : null;
-
- final signature = await hardwareWalletService!
- .signMessage(message: ascii.encode(message), derivationPath: derivationPath);
- return base64Encode(signature);
- }
-
- return super.signMessage(message, address: address);
- }
-
@override
bool receiveOptionAvailable(ReceivePageOption option) {
final isExtraAccount = currentAccountIndex > 0;
### cw_bitcoin/lib/electrum_wallet.dart
@@ -4279,22 +4279,33 @@ abstract class ElectrumWalletBase
void setExceptionHandler(void Function(FlutterErrorDetails) onError) => _onError = onError;
@override
- Future<String> signMessage(String message, {String? address = null}) async {
- final requested = address != null && address.trim().isNotEmpty;
- final addressRecord = requested
- ? walletAddresses.allAddresses.firstWhereOrNull((addr) => addr.address == address)
- : null;
-
- assertCanSignBitcoinMessage(
+ Future<String> signMessage(String message, {String? address}) async {
+ final addressRecord = getSigningAddressRecord(
address: address,
- heldByWallet: addressRecord != null,
- isTaproot: addressRecord?.type == SegwitAddresType.p2tr,
+ walletAddresses: walletAddresses.allAddresses,
);
+ if (walletInfo.isHardwareWallet) {
+ final index = addressRecord?.index ?? 0;
+ final isChange = addressRecord?.isHidden == true ? 1 : 0;
+ final derivationInfo = await walletInfo.getDerivationInfo();
+ final accountPath = derivationInfo.derivationPath;
+ final derivationPath = accountPath != null ? "$accountPath/$isChange/$index" : null;
+
+ final signature = await hardwareWalletService!
+ .signMessage(message: ascii.encode(message), derivationPath: derivationPath);
+ return base64Encode(signature);
+ }
+
final hd = addressRecord != null
? _hdForAddressRecord(record: addressRecord).childKey(Bip32KeyIndex(addressRecord.index))
: mainHd;
+ return signMessageWithKey(message, hd);
+ }
+
+ @protected
+ String signMessageWithKey(String message, Bip32Slip10Secp256k1 hd) {
final priv = ECPrivate.fromHex(hd.privateKey.privKey.toHex());
String messagePrefix = '\x18Bitcoin Signed Message:\n';
### cw_bitcoin/lib/litecoin_wallet.dart
@@ -1433,26 +1433,8 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
}
@override
- Future<String> signMessage(String message, {String? address}) async {
- final addressEntry = address != null
- ? walletAddresses.allAddresses.firstWhere((element) => element.address == address)
- : null;
-
- if (walletInfo.isHardwareWallet) {
- final index = addressEntry?.index ?? 0;
- final isChange = addressEntry?.isHidden == true ? 1 : 0;
- final derivationInfo = await walletInfo.getDerivationInfo();
- final accountPath = derivationInfo.derivationPath;
- final derivationPath = accountPath != null ? "$accountPath/$isChange/$index" : null;
-
- final signature = await hardwareWalletService!
- .signMessage(message: ascii.encode(message), derivationPath: derivationPath);
-
- return base64Encode(signature);
- }
-
- final HD = addressEntry == null ? mainHd : mainHd.childKey(Bip32KeyIndex(addressEntry.index));
- final priv = ECPrivate.fromHex(HD.privateKey.privKey.toHex());
+ String signMessageWithKey(String message, Bip32Slip10Secp256k1 hd) {
+ final priv = ECPrivate.fromHex(hd.privateKey.privKey.toHex());
final privateKey = ECDSAPrivateKey.fromBytes(
priv.toBytes(),
### cw_bitcoin/test/bitcoin_message_sign_test.dart
@@ -1,45 +1,213 @@
-import 'package:cw_bitcoin/bitcoin_message_sign.dart';
-import 'package:flutter_test/flutter_test.dart';
+import "dart:typed_data";
+
+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_message_sign.dart";
+import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_wallet.dart";
+import "package:cw_bitcoin/payjoin/manager.dart";
+import "package:cw_bitcoin/utils.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/encryption_file_utils.dart";
+import "package:cw_core/unspent_coins_info.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:hive/hive.dart";
+import "package:shared_preferences/shared_preferences.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+final _master = Bip32Slip10Secp256k1.fromSeed(List<int>.generate(64, (i) => i));
+final _receiveHd = _master.derivePath("m/84'/0'/0'/0") as Bip32Slip10Secp256k1;
+final _changeHd = _master.derivePath("m/84'/0'/0'/1") as Bip32Slip10Secp256k1;
+
+String _p2wpkh(Bip32Slip10Secp256k1 hd, int index) =>
+ generateP2WPKHAddress(hd: hd, network: BitcoinNetwork.mainnet, index: index);
+
+BitcoinAddressRecord _record(
+ String address, {
+ int index = 0,
+ BitcoinAddressType type = SegwitAddresType.p2wpkh,
+ bool isHidden = false,
+}) =>
+ BitcoinAddressRecord(
+ address,
+ index: index,
+ type: type,
+ isHidden: isHidden,
+ network: BitcoinNetwork.mainnet,
+ );
+
+class _NoPayjoin implements PayjoinManager {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _NoUnspentsBox implements Box<UnspentCoinsInfo> {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+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,
+ );
+
+ @override
+ Future<void> saveAddressesInBox() async {}
+}
+
+ElectrumWallet _wallet(List<BitcoinAddressRecord> records) {
+ final walletInfo = WalletInfo.external(
+ id: "sign_message_test",
+ name: "sign_message_test",
+ type: WalletType.bitcoin,
+ isRecovery: false,
+ restoreHeight: 0,
+ date: DateTime(2026),
+ dirPath: "",
+ path: "",
+ address: "",
+ );
+ return ElectrumWallet(
+ password: "",
+ walletInfo: walletInfo,
+ derivationInfo: DerivationInfo(
+ derivationType: DerivationType.bip39,
+ derivationPath: "m/84'/0'/0'",
+ ),
+ unspentCoinsInfo: _NoUnspentsBox(),
+ network: BitcoinNetwork.mainnet,
+ encryptionFileUtils: encryptionFileUtilsFor(false),
+ seedBytes: Uint8List.fromList(List<int>.generate(64, (i) => i)),
+ currency: CryptoCurrency.btc,
+ )..walletAddresses = _Addresses(walletInfo, records);
+}
void main() {
- test('blank address still uses the main key', () {
- expect(
- () => assertCanSignBitcoinMessage(address: '', heldByWallet: false, isTaproot: false),
- returnsNormally,
+ group("getSigningAddressRecord", () {
+ final receive = _record(_p2wpkh(_receiveHd, 0));
+ final change = _record(_p2wpkh(_changeHd, 0), isHidden: true);
+ final taproot = _record(
+ "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0",
+ type: SegwitAddresType.p2tr,
);
- expect(
- () => assertCanSignBitcoinMessage(address: null, heldByWallet: false, isTaproot: false),
- returnsNormally,
+ final mweb = BitcoinAddressRecord(
+ "ltcmweb1qqexample",
+ index: 0,
+ type: SegwitAddresType.mweb,
+ network: null,
);
- });
+ final walletAddresses = [receive, change, taproot, mweb];
- test('refuses an address the wallet does not hold', () {
- expect(
- () => assertCanSignBitcoinMessage(
- address: 'sp1qqexample',
- heldByWallet: false,
- isTaproot: false,
- ),
- throwsA(isA<UnsupportedError>()),
- );
+ test("blank address still uses the main key", () {
+ for (final address in [null, "", " "]) {
+ expect(
+ getSigningAddressRecord(address: address, walletAddresses: walletAddresses),
+ isNull,
+ );
+ }
+ expect(getSigningAddressRecord(address: null, walletAddresses: []), isNull);
+ });
+
+ test("refuses an address the wallet does not hold", () {
+ expect(
+ () => getSigningAddressRecord(
+ address: "sp1qqexample",
+ walletAddresses: walletAddresses,
+ ),
+ throwsA(isA<UnsupportedError>()),
+ );
+ expect(
+ () => getSigningAddressRecord(address: receive.address, walletAddresses: []),
+ throwsA(isA<UnsupportedError>()),
+ );
+ });
+
+ test("refuses taproot and MWEB addresses the wallet holds", () {
+ for (final record in [taproot, mweb]) {
+ expect(
+ () => getSigningAddressRecord(address: record.address, walletAddresses: walletAddresses),
+ throwsA(isA<UnsupportedError>()),
+ );
+ }
+ });
+
+ test("returns the held record for a receive or change address", () {
+ expect(
+ getSigningAddressRecord(address: receive.address, walletAddresses: walletAddresses),
+ same(receive),
+ );
+ expect(
+ getSigningAddressRecord(address: change.address, walletAddresses: walletAddresses),
+ same(change),
+ );
+ });
+
+ test("ignores whitespace around a pasted address", () {
+ expect(
+ getSigningAddressRecord(
+ address: " ${receive.address}\n",
+ walletAddresses: walletAddresses,
+ ),
+ same(receive),
+ );
+ });
});
- test('refuses taproot and allows a held receive address', () {
- expect(
- () => assertCanSignBitcoinMessage(
- address: 'bc1pexample',
- heldByWallet: true,
- isTaproot: true,
- ),
- throwsA(isA<UnsupportedError>()),
- );
- expect(
- () => assertCanSignBitcoinMessage(
- address: 'bc1qexample',
- heldByWallet: true,
- isTaproot: false,
- ),
- returnsNormally,
- );
+ group("ElectrumWallet.signMessage", () {
+ setUpAll(() async {
+ sqfliteFfiInit();
+ db = await databaseFactoryFfi.openDatabase(inMemoryDatabasePath);
+ await db!.execute(
+ "CREATE TABLE walletInfoAddress "
+ "(walletInfoAddressId INTEGER PRIMARY KEY, walletInfoId INTEGER, type INTEGER, "
+ "address TEXT)",
+ );
+ });
+
+ setUp(() => SharedPreferences.setMockInitialValues({}));
+
+ test("signs receive and change addresses with their own keys", () async {
+ final receive = _p2wpkh(_receiveHd, 1);
+ final change = _p2wpkh(_changeHd, 1);
+ final wallet = _wallet([
+ _record(receive, index: 1),
+ _record(change, index: 1, isHidden: true),
+ ]);
+
+ final receiveSignature = await wallet.signMessage("test", address: receive);
+ final changeSignature = await wallet.signMessage("test", address: change);
+
+ expect(await wallet.verifyMessage("test", receiveSignature, address: receive), isTrue);
+ expect(await wallet.verifyMessage("test", changeSignature, address: change), isTrue);
+ expect(await wallet.verifyMessage("test", changeSignature, address: receive), isFalse);
+ });
+
+ test("refuses an address the wallet does not hold", () async {
+ final wallet = _wallet([_record(_p2wpkh(_receiveHd, 1), index: 1)]);
+
+ await expectLater(
+ wallet.signMessage("test", address: _p2wpkh(_receiveHd, 2)),
+ throwsA(isA<UnsupportedError>()),
+ );
+ });
});
}
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet.dart
@@ -1,5 +1,3 @@
-import "dart:convert";
-
import "package:bitbox/bitbox.dart" as bitbox;
import "package:bitcoin_base/bitcoin_base.dart";
import "package:blockchain_utils/blockchain_utils.dart";
@@ -232,27 +230,9 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
}
@override
- Future<String> signMessage(String message, {String? address}) async {
- final addressEntry = address != null
- ? walletAddresses.allAddresses.firstWhere((element) => element.address == address, orElse: () => null)
- : null;
-
- if (walletInfo.isHardwareWallet) {
- final index = addressEntry?.index ?? 0;
- final isChange = addressEntry?.isHidden == true ? 1 : 0;
- final derivationInfo = await walletInfo.getDerivationInfo();
- final accountPath = derivationInfo.derivationPath;
- final derivationPath = accountPath != null ? "$accountPath/$isChange/$index" : null;
-
- final signature = await hardwareWalletService!
- .signMessage(message: ascii.encode(message), derivationPath: derivationPath);
-
- return base64Encode(signature);
- }
-
- final HD = addressEntry == null ? mainHd : mainHd.childKey(Bip32KeyIndex(addressEntry.index));
+ String signMessageWithKey(String message, Bip32Slip10Secp256k1 hd) {
final priv = ECPrivate.fromWif(
- WifEncoder.encode(HD.privateKey.raw, netVer: network.wifNetVer),
+ WifEncoder.encode(hd.privateKey.raw, netVer: network.wifNetVer),
netVersion: network.wifNetVer,
);
return priv.signMessage(StringUtils.encode(message));
### cw_dogecoin/lib/src/dogecoin_wallet.dart
@@ -169,16 +169,9 @@ abstract class DogeCoinWalletBase extends ElectrumWallet with Store {
}
@override
- Future<String> signMessage(String message, {String? address = null}) async {
- int? index;
- try {
- index = address != null
- ? walletAddresses.allAddresses.firstWhere((element) => element.address == address).index
- : null;
- } catch (_) {}
- final HD = index == null ? mainHd : mainHd.childKey(Bip32KeyIndex(index));
+ String signMessageWithKey(String message, Bip32Slip10Secp256k1 hd) {
final priv = ECPrivate.fromWif(
- WifEncoder.encode(HD.privateKey.raw, netVer: network.wifNetVer),
+ WifEncoder.encode(hd.privateKey.raw, netVer: network.wifNetVer),
netVersion: network.wifNetVer,
);
return priv.signMessage(StringUtils.encode(message));
### pubspec.lock
@@ -1860,17 +1860,17 @@ packages:
dependency: "direct overridden"
description:
path: "packages/ledger-bitcoin"
- ref: "75bba8632c529debf30ee2b1858530009fa6440b"
- resolved-ref: "75bba8632c529debf30ee2b1858530009fa6440b"
+ ref: bd86993c6c41085f9b2aa0b723f734bc4f6bf508
+ resolved-ref: bd86993c6c41085f9b2aa0b723f734bc4f6bf508
url: "https://github.com/cake-tech/ledger-flutter-plus-plugins"
source: git
version: "0.0.3"
ledger_ethereum:
dependency: "direct overridden"
description:
path: "packages/ledger-ethereum"
- ref: f4761cd5171d4c1e2e42fd3298261650539fb2db
- resolved-ref: f4761cd5171d4c1e2e42fd3298261650539fb2db
+ ref: bd86993c6c41085f9b2aa0b723f734bc4f6bf508
+ resolved-ref: bd86993c6c41085f9b2aa0b723f734bc4f6bf508
url: "https://github.com/cake-tech/ledger-flutter-plus-plugins"
source: git
version: "0.0.5"
@@ -1887,8 +1887,8 @@ packages:
dependency: "direct overridden"
description:
path: "packages/ledger-litecoin"
- ref: "75bba8632c529debf30ee2b1858530009fa6440b"
- resolved-ref: "75bba8632c529debf30ee2b1858530009fa6440b"
+ ref: bd86993c6c41085f9b2aa0b723f734bc4f6bf508
+ resolved-ref: bd86993c6c41085f9b2aa0b723f734bc4f6bf508
url: "https://github.com/cake-tech/ledger-flutter-plus-plugins"
source: git
version: "0.0.2"
@@ -2459,7 +2459,7 @@ packages:
source: git
version: "5.0.5"
progressive_blur:
- dependency: "direct main"
+ dependency: "direct overridden"
description:
path: "."
ref: "6ec8d0ccf46b1629a46ab68f31e26df489bac958"
@@ -3488,7 +3488,7 @@ packages:
source: git
version: "6.5.0"
yaml:
- dependency: "direct main"
+ dependency: "direct overridden"
description:
path: "pkgs/yaml"
ref: "27f829e3752382beae9deb1e87029f9ed52ef32e"Why this scored 51/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.