Check for overflow in IncrementAccountCounter().

This commit is contained in:
therealyingtong 2022-04-08 14:27:51 +08:00
parent 8750178432
commit 0da6bcef72
2 changed files with 16 additions and 4 deletions

View File

@ -522,7 +522,11 @@ std::pair<UnifiedFullViewingKey, libzcash::AccountId> CWallet::GenerateNewUnifie
while (true) { while (true) {
auto accountId = hdChain.GetAccountCounter(); auto accountId = hdChain.GetAccountCounter();
auto generated = GenerateUnifiedSpendingKeyForAccount(accountId); auto generated = GenerateUnifiedSpendingKeyForAccount(accountId);
hdChain.IncrementAccountCounter(); auto account = hdChain.IncrementAccountCounter();
if (!account.has_value()) {
throw std::runtime_error(
"CWallet::GenerateNewUnifiedSpendingKey(): Account counter overflowed (2^31 - 1).");
}
if (generated.has_value()) { if (generated.has_value()) {
// Update the persisted chain information // Update the persisted chain information

View File

@ -11,6 +11,7 @@
#include "key.h" #include "key.h"
#include "keystore.h" #include "keystore.h"
#include "zcash/Address.hpp" #include "zcash/Address.hpp"
#include "zcash/address/zip32.h"
#include <list> #include <list>
#include <stdint.h> #include <stdint.h>
@ -103,9 +104,16 @@ public:
return accountCounter; return accountCounter;
} }
void IncrementAccountCounter() { /** Increments the account counter by 1 and returns it. Returns std::nullopt
// TODO: We should check for overflow somewhere and handle it. * if the increment operation would cause an overflow. */
accountCounter += 1; std::optional<uint32_t> IncrementAccountCounter() {
auto newAccountCounter = accountCounter + 1;
if (newAccountCounter > (HARDENED_KEY_LIMIT - 1)) {
return std::nullopt;
} else {
accountCounter = newAccountCounter;
return newAccountCounter;
}
} }
uint32_t GetLegacyTKeyCounter(bool external) { uint32_t GetLegacyTKeyCounter(bool external) {