fix: don't leave a ghost WalletInfo row when wallet creation fails (#3830)
What changed, and why it matters
This commit fixes a bug in Cake Wallet where creating or restoring an EVM wallet could leave a 'ghost' wallet entry in the app's list. The ghost appeared because the wallet's metadata was saved to the app's database before the actual wallet file was written. If the next step failed—for example, because the private key was invalid—the app showed a wallet that could never be opened. The fix validates the private key before saving anything, and cleans up the metadata row if the wallet file was never actually created. It also makes sure the cleanup only happens when the wallet directory is empty, so it doesn't accidentally delete real wallets.
Treat as a reliability/DoS bug rather than an active exploit. Review whether other wallet services (non-EVM) have the same metadata-before-file persistence pattern and apply similar early validation and cleanup. Verify the directory-empty check behaves correctly on all supported platforms, especially Windows. No immediate security advisory is required, but a release note mentioning the fix is appropriate.
Security signals we found
State inconsistency between database metadata and on-disk wallet files
Untrusted user input (private key) reaching cryptographic initialization before validation
Ghost wallet entry causing persistent UI error (PathNotFoundException) on subsequent opens
Cleanup logic gated on empty directory to avoid deleting wallets with persisted files
Cross-platform path handling corrected (previous substring match failed on Windows)
Evidence from the diff
The patch addresses a state inconsistency in wallet creation for EVM chains. EVMChainWalletService.restoreFromKeys now validates the private key via EVMChainUtils.isValidPrivateKey before persisting WalletInfo, throwing BadKeysException early. WalletCreationVM._create now wraps process(credentials) in a try/catch and calls a new helper, _removeWalletInfoOfEmptyWalletDir, which deletes the WalletInfo row only if the wallet directory does not exist or is empty. The validation accepts any even-length hex string parseable by EthPrivateKey.fromHex and rejects zero-mod-secp256k1-order keys. Tests are added for these cases.
Changed components
cw_evm/lib/evm_chain_wallet_service.dartcw_evm/lib/utils/evm_chain_utils.dartlib/view_model/wallet_creation_vm.dartEVM wallet restore-from-private-key flowWalletInfo metadata storeInspect captured patch +102 / −2
### cw_evm/lib/evm_chain_wallet_service.dart
@@ -18,6 +18,7 @@ import 'package:cw_evm/evm_chain_exceptions.dart';
import 'package:cw_evm/evm_chain_registry.dart';
import 'package:cw_evm/evm_chain_wallet.dart';
import 'package:cw_evm/evm_chain_wallet_creation_credentials.dart';
+import "package:cw_evm/utils/evm_chain_utils.dart";
/// Unified service for all EVM chains (Ethereum, Polygon, Base, Arbitrum, etc.)
///
@@ -260,6 +261,10 @@ class EVMChainWalletService extends WalletService<
EVMChainRestoreWalletFromPrivateKey credentials, {
bool? isTestnet,
}) async {
+ if (!EVMChainUtils.isValidPrivateKey(credentials.privateKey)) {
+ throw const BadKeysException("Invalid private key. Expected a hex-encoded private key.");
+ }
+
final walletInfo = credentials.walletInfo!;
// Get chainId from wallet type
### cw_evm/lib/utils/evm_chain_utils.dart
@@ -1,8 +1,29 @@
import "package:cw_evm/evm_chain_transaction_priority.dart";
-import "package:web3dart/web3dart.dart" show EtherAmount, EtherUnit;
+import "package:web3dart/web3dart.dart" show EtherAmount, EtherUnit, EthPrivateKey;
/// Utility class for chain-specific EVM chain operations
class EVMChainUtils {
+ static final BigInt _secp256k1Order = BigInt.parse(
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141",
+ radix: 16,
+ );
+
+ /// Whether [privateKey] restores a usable wallet. It accepts exactly what wallets have
+ /// always been restored from, any even-length hex (optionally 0x-prefixed) that
+ /// [EthPrivateKey.fromHex] parses, so a key that restored on an earlier version still
+ /// restores here. It rejects hex that does not parse and keys that are zero modulo the
+ /// secp256k1 order, which have no key pair and could never sign anything.
+ static bool isValidPrivateKey(String privateKey) {
+ final EthPrivateKey key;
+ try {
+ key = EthPrivateKey.fromHex(privateKey);
+ } catch (_) {
+ return false;
+ }
+
+ return key.privateKeyInt % _secp256k1Order != BigInt.zero;
+ }
+
static int getTotalPriorityFee(EVMChainTransactionPriority priority, int chainId) =>
switch (chainId) {
1 => _ethereumPriorityFee(priority),
### cw_evm/test/evm_chain_private_key_test.dart
@@ -0,0 +1,49 @@
+import "package:cw_evm/utils/evm_chain_utils.dart";
+import "package:flutter_test/flutter_test.dart";
+
+void main() {
+ group("EVMChainUtils.isValidPrivateKey", () {
+ const validKey = "4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318";
+ const curveOrder = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
+ final curveOrderInt = BigInt.parse(curveOrder, radix: 16);
+
+ String hexOf(BigInt value) {
+ final hex = value.toRadixString(16);
+ return hex.length.isOdd ? "0$hex" : hex;
+ }
+
+ test("accepts a 32-byte hex key with or without a 0x prefix, in either case", () {
+ expect(EVMChainUtils.isValidPrivateKey(validKey), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey("0x$validKey"), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey(validKey.toUpperCase()), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey(hexOf(curveOrderInt - BigInt.one)), isTrue);
+ });
+
+ test("keeps accepting the other even lengths that restored on earlier versions", () {
+ expect(EVMChainUtils.isValidPrivateKey("01"), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey(validKey.substring(0, 62)), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey("${validKey}00"), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey("$validKey$validKey"), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey("f" * 64), isTrue);
+ expect(EVMChainUtils.isValidPrivateKey(hexOf(curveOrderInt + BigInt.one)), isTrue);
+ });
+
+ test("rejects input that EthPrivateKey.fromHex cannot parse", () {
+ expect(EVMChainUtils.isValidPrivateKey("not a private key"), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("z" * 64), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("0X$validKey"), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey(validKey.substring(0, 63)), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("$validKey "), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("$validKey\n"), isFalse);
+ });
+
+ test("rejects empty input and keys that are zero modulo the curve order", () {
+ expect(EVMChainUtils.isValidPrivateKey(""), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("0x"), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("00"), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey("0" * 64), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey(curveOrder), isFalse);
+ expect(EVMChainUtils.isValidPrivateKey(hexOf(curveOrderInt * BigInt.two)), isFalse);
+ });
+ });
+}
### lib/view_model/wallet_creation_vm.dart
@@ -1,3 +1,5 @@
+import "dart:io";
+
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
@@ -129,7 +131,13 @@ abstract class WalletCreationVMBase with Store {
);
printV("derivationInfo: ${(await credentials.walletInfo!.getDerivationInfo()).toJson()}");
- final wallet = await process(credentials);
+ final WalletBase wallet;
+ try {
+ wallet = await process(credentials);
+ } catch (_) {
+ await _removeWalletInfoOfEmptyWalletDir(credentials.walletInfo!, dirPath);
+ rethrow;
+ }
final isNonSeedWallet = isRecovery ? wallet.seed == null : false;
credentials.walletInfo!.isNonSeedWallet = isNonSeedWallet;
@@ -151,6 +159,23 @@ abstract class WalletCreationVMBase with Store {
}
}
+ /// A failed [process] can leave the WalletInfo row that the wallet's `init()` saved
+ /// without any wallet file on disk, so the wallet shows up in the list but can never be
+ /// opened. Drop that row when nothing was written to [dirPath]. Anything in the directory
+ /// means the coin got as far as writing its files, and then the row is kept as before.
+ Future<void> _removeWalletInfoOfEmptyWalletDir(WalletInfo walletInfo, String dirPath) async {
+ try {
+ final dir = Directory(dirPath);
+ if (dir.existsSync() && dir.listSync().isNotEmpty) {
+ return;
+ }
+
+ await WalletInfo.delete(walletInfo);
+ } catch (e) {
+ printV("Failed to remove the WalletInfo of the failed wallet creation: $e");
+ }
+ }
+
DerivationInfo getDefaultCreateDerivation() {
final useBip39ForBitcoin = seedSettingsViewModel.bitcoinSeedType.type == DerivationType.bip39;
final useBip39ForNano = seedSettingsViewModel.nanoSeedType.type == DerivationType.bip39;Why this scored 45/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.