From 82da47ef2349a057e63486b3ba84b86dc533f860 Mon Sep 17 00:00:00 2001 From: hihiben Date: Mon, 19 Jun 2017 14:32:54 +0800 Subject: [PATCH] Fix SearchKeyPool and ReserveKeyFromKeyPool Avoid the potential error that is caused by unable to erase a key that does not exist in the key pool --- src/wallet/wallet.cpp | 15 +++++++++------ src/wallet/wallet.h | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 50b7ccd7..b9d996dd 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2611,7 +2611,7 @@ void CWallet::ViewKeyPool(std::vector& keys) } } -int64_t CWallet::SearchKeyPool(const CBitcoinAddress& address) const +bool CWallet::SearchKeyPool(int64_t& nIndex, const CBitcoinAddress& address) const { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); @@ -2620,10 +2620,12 @@ int64_t CWallet::SearchKeyPool(const CBitcoinAddress& address) const CKeyPool keypool; if (!walletdb.ReadPool(*it, keypool)) throw runtime_error(_(__func__) + "() : read failed"); - if (address == CBitcoinAddress(keypool.vchPubKey.GetID())) - return (*it); + if (address == CBitcoinAddress(keypool.vchPubKey.GetID())) { + nIndex = *it; + return true; + } } - return -1; + return false; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) @@ -2657,12 +2659,13 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, const CB { LOCK(cs_wallet); - // Get the oldest key + // Return if the key pool is empty if (setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); - nIndex = SearchKeyPool(address); + if (!SearchKeyPool(nIndex, address)) + return; setKeyPool.erase(nIndex); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error(_(__func__) + "() : read failed"); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 9fe23e2c..81efc9fe 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -680,7 +680,7 @@ class CWallet : public CHDKeyStore, public CValidationInterface bool AddKeyPool(CPubKey& key); bool EraseKeyPool(); void ViewKeyPool(std::vector& keys); - int64_t SearchKeyPool(const CBitcoinAddress& address) const; + bool SearchKeyPool(int64_t& nIndex, const CBitcoinAddress& address) const; void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool); void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, const CBitcoinAddress& address); void KeepKey(int64_t nIndex);