Skip to content

Commit

Permalink
No longer ever reuse keypool indexes
Browse files Browse the repository at this point in the history
This fixes an issue where you could reserve a keypool entry, then
top up the keypool, writing out a new key at the given index, then
return they key from the pool. This isnt likely to cause issues,
but given there is no reason to ever re-use keypool indexes
(they're 64 bits...), best to avoid it alltogether.
  • Loading branch information
TheBlueMatt committed Jul 17, 2017
1 parent 0b01935 commit 1fc8c3d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
14 changes: 5 additions & 9 deletions src/wallet/wallet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3211,21 +3211,17 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
internal = true;
}

if (!setInternalKeyPool.empty()) {
nEnd = *(setInternalKeyPool.rbegin()) + 1;
}
if (!setExternalKeyPool.empty()) {
nEnd = std::max(nEnd, *(setExternalKeyPool.rbegin()) + 1);
}
assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
int64_t index = ++m_max_keypool_index;

if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(walletdb, internal), internal))) {
if (!walletdb.WritePool(index, CKeyPool(GenerateNewKey(walletdb, internal), internal))) {
throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
}

if (internal) {
setInternalKeyPool.insert(nEnd);
setInternalKeyPool.insert(index);
} else {
setExternalKeyPool.insert(nEnd);
setExternalKeyPool.insert(index);
}
}
if (missingInternal + missingExternal > 0) {
Expand Down
5 changes: 4 additions & 1 deletion src/wallet/wallet.h
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface

std::set<int64_t> setInternalKeyPool;
std::set<int64_t> setExternalKeyPool;
int64_t m_max_keypool_index;

int64_t nTimeFirstKey;

Expand Down Expand Up @@ -743,13 +744,14 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface
}
}

void LoadKeyPool(int nIndex, const CKeyPool &keypool)
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
{
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_max_keypool_index = std::max(m_max_keypool_index, nIndex);

// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
Expand Down Expand Up @@ -795,6 +797,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface
nAccountingEntryNumber = 0;
nNextResend = 0;
nLastResend = 0;
m_max_keypool_index = 0;
nTimeFirstKey = 0;
fBroadcastTransactions = false;
nRelockTime = 0;
Expand Down

0 comments on commit 1fc8c3d

Please sign in to comment.