diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index fd2f31fed..5c63a319a 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2523,10 +2523,33 @@ bool CWallet::SetCryptedHDSeed(const uint256& seedFp, const std::vectorWriteCryptedHDSeed(seedFp, vchCryptedSecret); - else - return CWalletDB(strWalletFile).WriteCryptedHDSeed(seedFp, vchCryptedSecret); + // Write the encrypted record, then drop the plaintext one. Both go + // through the same CWalletDB (and therefore the same transaction when + // EncryptWallet supplied pwalletdbEncryption), because CDB::Rewrite at + // the end of EncryptWallet copies every surviving record into the fresh + // file -- a leftover plaintext "hdseed" would keep the unencrypted seed + // on disk for the life of the wallet. + // + // The erase is deliberately best-effort: a hard failure here propagates + // into CCryptoKeyStore::EncryptKeys, which CWallet::EncryptWallet turns + // into assert(false) with half the keys encrypted in memory. A logged + // warning is strictly better than that. + if (pwalletdbEncryption) { + if (!pwalletdbEncryption->WriteCryptedHDSeed(seedFp, vchCryptedSecret)) + return false; + if (!pwalletdbEncryption->EraseHDSeed(seedFp)) + LogPrintf("%s: WARNING: could not erase the plaintext hdseed record; " + "the unencrypted HD seed may remain in wallet.dat\n", __func__); + return true; + } else { + CWalletDB walletdb(strWalletFile); + if (!walletdb.WriteCryptedHDSeed(seedFp, vchCryptedSecret)) + return false; + if (!walletdb.EraseHDSeed(seedFp)) + LogPrintf("%s: WARNING: could not erase the plaintext hdseed record; " + "the unencrypted HD seed may remain in wallet.dat\n", __func__); + return true; + } } return false; } diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index 478a5ec24..4f159f9a1 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -1335,6 +1335,16 @@ bool CWalletDB::WriteCryptedHDSeed(const uint256& seedFp, const std::vector& vchCryptedSecret); + //! Remove the PLAINTEXT hdseed record. Must be called once the seed has been + //! written in encrypted form: CDB::Rewrite (invoked at the end of + //! CWallet::EncryptWallet) copies whatever records still exist into the new + //! file, so a leftover "hdseed" leaves the unencrypted seed on disk forever. + bool EraseHDSeed(const uint256& seedFp); //! write the hdchain model (external chain child index counter) bool WriteHDChain(const CHDChain& chain);