Merge #17381: LegacyScriptPubKeyMan code cleanups

05b224a175 Add missing SetupGeneration error handling in EncryptWallet (Russell Yanofsky)
bfd826a675 Clean up nested scope in GetReservedDestination (Russell Yanofsky)
491a599b37 Get rid of confusing LegacyScriptPubKeyMan::TopUpKeyPool method (Russell Yanofsky)
4a0abf694e Pass CTxDestination to ScriptPubKeyMan::GetMetadata (Russell Yanofsky)
b07b07cd87 Add EnsureLegacyScriptPubKeyMan and use in rpcwallet.cpp (Russell Yanofsky)

Pull request description:

  This PR implements suggested code cleanups from #17300 and #17304 review comments

ACKs for top commit:
  Sjors:
    re-ACK 05b224a
  laanwj:
    Code review ACK 05b224a175

Tree-SHA512: 12fd86637088515b744c028e0501c5d21a9cf9ee9c9cfd70e9cb65d44611ea5643abd5f6f101105caa5aff015d74de606f074f08af7dae8429f929d21288ab45
This commit is contained in:
Wladimir J. van der Laan 2019-11-06 17:14:45 +01:00
commit 976cc766c4
No known key found for this signature in database
GPG key ID: 1E4AED62986CD25D
6 changed files with 56 additions and 67 deletions

View file

@ -87,15 +87,6 @@ static void RescanWallet(CWallet& wallet, const WalletRescanReserver& reserver,
} }
} }
static LegacyScriptPubKeyMan& GetLegacyScriptPubKeyMan(CWallet& wallet)
{
LegacyScriptPubKeyMan* spk_man = wallet.GetLegacyScriptPubKeyMan();
if (!spk_man) {
throw JSONRPCError(RPC_WALLET_ERROR, "This type of wallet does not support this command");
}
return *spk_man;
}
UniValue importprivkey(const JSONRPCRequest& request) UniValue importprivkey(const JSONRPCRequest& request)
{ {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
@ -134,7 +125,7 @@ UniValue importprivkey(const JSONRPCRequest& request)
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled");
} }
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*wallet); EnsureLegacyScriptPubKeyMan(*wallet);
WalletRescanReserver reserver(pwallet); WalletRescanReserver reserver(pwallet);
bool fRescan = true; bool fRescan = true;
@ -262,7 +253,7 @@ UniValue importaddress(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*pwallet); EnsureLegacyScriptPubKeyMan(*pwallet);
std::string strLabel; std::string strLabel;
if (!request.params[1].isNull()) if (!request.params[1].isNull())
@ -465,7 +456,7 @@ UniValue importpubkey(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*wallet); EnsureLegacyScriptPubKeyMan(*wallet);
std::string strLabel; std::string strLabel;
if (!request.params[1].isNull()) if (!request.params[1].isNull())
@ -549,7 +540,7 @@ UniValue importwallet(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*wallet); EnsureLegacyScriptPubKeyMan(*wallet);
if (pwallet->chain().havePruned()) { if (pwallet->chain().havePruned()) {
// Exit early and print an error. // Exit early and print an error.
@ -708,7 +699,7 @@ UniValue dumpprivkey(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*wallet); LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*wallet);
auto locked_chain = pwallet->chain().lock(); auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet); LOCK(pwallet->cs_wallet);
@ -759,7 +750,7 @@ UniValue dumpwallet(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*wallet); LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*wallet);
auto locked_chain = pwallet->chain().lock(); auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet); LOCK(pwallet->cs_wallet);
@ -1346,7 +1337,7 @@ UniValue importmulti(const JSONRPCRequest& mainRequest)
RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ}); RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});
LegacyScriptPubKeyMan& spk_man = GetLegacyScriptPubKeyMan(*wallet); EnsureLegacyScriptPubKeyMan(*wallet);
const UniValue& requests = mainRequest.params[0]; const UniValue& requests = mainRequest.params[0];

View file

@ -124,6 +124,15 @@ void EnsureWalletIsUnlocked(const CWallet* pwallet)
} }
} }
LegacyScriptPubKeyMan& EnsureLegacyScriptPubKeyMan(CWallet& wallet)
{
LegacyScriptPubKeyMan* spk_man = wallet.GetLegacyScriptPubKeyMan();
if (!spk_man) {
throw JSONRPCError(RPC_WALLET_ERROR, "This type of wallet does not support this command");
}
return *spk_man;
}
static void WalletTxToJSON(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain, const CWalletTx& wtx, UniValue& entry) static void WalletTxToJSON(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain, const CWalletTx& wtx, UniValue& entry)
{ {
int confirms = wtx.GetDepthInMainChain(locked_chain); int confirms = wtx.GetDepthInMainChain(locked_chain);
@ -966,10 +975,7 @@ static UniValue addmultisigaddress(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan* spk_man = pwallet->GetLegacyScriptPubKeyMan(); LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
if (!spk_man) {
throw JSONRPCError(RPC_WALLET_ERROR, "This type of wallet does not support this command");
}
auto locked_chain = pwallet->chain().lock(); auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet); LOCK(pwallet->cs_wallet);
@ -987,7 +993,7 @@ static UniValue addmultisigaddress(const JSONRPCRequest& request)
if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) { if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) {
pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str())); pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str()));
} else { } else {
pubkeys.push_back(AddrToPubKey(spk_man, keys_or_addrs[i].get_str())); pubkeys.push_back(AddrToPubKey(&spk_man, keys_or_addrs[i].get_str()));
} }
} }
@ -1000,7 +1006,7 @@ static UniValue addmultisigaddress(const JSONRPCRequest& request)
// Construct using pay-to-script-hash: // Construct using pay-to-script-hash:
CScript inner; CScript inner;
CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, *spk_man, inner); CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, spk_man, inner);
pwallet->SetAddressBook(dest, label, "send"); pwallet->SetAddressBook(dest, label, "send");
UniValue result(UniValue::VOBJ); UniValue result(UniValue::VOBJ);
@ -3759,15 +3765,7 @@ UniValue getaddressinfo(const JSONRPCRequest& request)
ScriptPubKeyMan* spk_man = pwallet->GetScriptPubKeyMan(); ScriptPubKeyMan* spk_man = pwallet->GetScriptPubKeyMan();
if (spk_man) { if (spk_man) {
CKeyID key_id = GetKeyForDestination(*provider, dest); if (const CKeyMetadata* meta = spk_man->GetMetadata(dest)) {
const CKeyMetadata* meta = nullptr;
if (!key_id.IsNull()) {
meta = spk_man->GetMetadata(key_id);
}
if (!meta) {
meta = spk_man->GetMetadata(CScriptID(scriptPubKey));
}
if (meta) {
ret.pushKV("timestamp", meta->nCreateTime); ret.pushKV("timestamp", meta->nCreateTime);
if (meta->has_key_origin) { if (meta->has_key_origin) {
ret.pushKV("hdkeypath", WriteHDKeypath(meta->key_origin.path)); ret.pushKV("hdkeypath", WriteHDKeypath(meta->key_origin.path));
@ -3933,10 +3931,7 @@ UniValue sethdseed(const JSONRPCRequest& request)
}, },
}.Check(request); }.Check(request);
LegacyScriptPubKeyMan* spk_man = pwallet->GetLegacyScriptPubKeyMan(); LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
if (!spk_man) {
throw JSONRPCError(RPC_WALLET_ERROR, "This type of wallet does not support this command");
}
if (pwallet->chain().isInitialBlockDownload()) { if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot set a new HD seed while still in Initial Block Download"); throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot set a new HD seed while still in Initial Block Download");
@ -3963,22 +3958,22 @@ UniValue sethdseed(const JSONRPCRequest& request)
CPubKey master_pub_key; CPubKey master_pub_key;
if (request.params[1].isNull()) { if (request.params[1].isNull()) {
master_pub_key = spk_man->GenerateNewSeed(); master_pub_key = spk_man.GenerateNewSeed();
} else { } else {
CKey key = DecodeSecret(request.params[1].get_str()); CKey key = DecodeSecret(request.params[1].get_str());
if (!key.IsValid()) { if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
} }
if (HaveKey(*spk_man, key)) { if (HaveKey(spk_man, key)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)");
} }
master_pub_key = spk_man->DeriveNewSeed(key); master_pub_key = spk_man.DeriveNewSeed(key);
} }
spk_man->SetHDSeed(master_pub_key); spk_man.SetHDSeed(master_pub_key);
if (flush_key_pool) spk_man->NewKeyPool(); if (flush_key_pool) spk_man.NewKeyPool();
return NullUniValue; return NullUniValue;
} }

View file

@ -12,6 +12,7 @@
class CRPCTable; class CRPCTable;
class CWallet; class CWallet;
class JSONRPCRequest; class JSONRPCRequest;
class LegacyScriptPubKeyMan;
class UniValue; class UniValue;
struct PartiallySignedTransaction; struct PartiallySignedTransaction;
class CTransaction; class CTransaction;
@ -40,6 +41,7 @@ std::shared_ptr<CWallet> GetWalletForJSONRPCRequest(const JSONRPCRequest& reques
std::string HelpRequiringPassphrase(const CWallet*); std::string HelpRequiringPassphrase(const CWallet*);
void EnsureWalletIsUnlocked(const CWallet*); void EnsureWalletIsUnlocked(const CWallet*);
bool EnsureWalletIsAvailable(const CWallet*, bool avoidException); bool EnsureWalletIsAvailable(const CWallet*, bool avoidException);
LegacyScriptPubKeyMan& EnsureLegacyScriptPubKeyMan(CWallet& wallet);
UniValue getaddressinfo(const JSONRPCRequest& request); UniValue getaddressinfo(const JSONRPCRequest& request);
UniValue signrawtransactionwithwallet(const JSONRPCRequest& request); UniValue signrawtransactionwithwallet(const JSONRPCRequest& request);

View file

@ -14,7 +14,7 @@
bool LegacyScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error) bool LegacyScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error)
{ {
error.clear(); error.clear();
TopUpKeyPool(); TopUp();
// Generate a new key that is added to wallet // Generate a new key that is added to wallet
CPubKey new_key; CPubKey new_key;
@ -264,10 +264,8 @@ bool LegacyScriptPubKeyMan::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
bool LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool) bool LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
{ {
{ if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
if (!ReserveKeyFromKeyPool(index, keypool, internal)) { return false;
return false;
}
} }
return true; return true;
} }
@ -282,11 +280,6 @@ void LegacyScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, cons
ReturnKey(index, internal, pubkey); ReturnKey(index, internal, pubkey);
} }
bool LegacyScriptPubKeyMan::TopUp(unsigned int size)
{
return TopUpKeyPool(size);
}
void LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script) void LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
{ {
AssertLockHeld(cs_wallet); AssertLockHeld(cs_wallet);
@ -297,7 +290,7 @@ void LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
WalletLogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__); WalletLogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
MarkReserveKeysAsUsed(mi->second); MarkReserveKeysAsUsed(mi->second);
if (!TopUpKeyPool()) { if (!TopUp()) {
WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__); WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
} }
} }
@ -401,7 +394,7 @@ bool LegacyScriptPubKeyMan::Upgrade(int prev_version, std::string& error)
} }
// Regenerate the keypool if upgraded to HD // Regenerate the keypool if upgraded to HD
if (hd_upgrade) { if (hd_upgrade) {
if (!TopUpKeyPool()) { if (!TopUp()) {
error = _("Unable to generate keys").translated; error = _("Unable to generate keys").translated;
return false; return false;
} }
@ -476,18 +469,24 @@ int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
return nTimeFirstKey; return nTimeFirstKey;
} }
const CKeyMetadata* LegacyScriptPubKeyMan::GetMetadata(uint160 id) const const CKeyMetadata* LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
{ {
AssertLockHeld(cs_wallet); AssertLockHeld(cs_wallet);
auto it = mapKeyMetadata.find(CKeyID(id));
if (it != mapKeyMetadata.end()) { CKeyID key_id = GetKeyForDestination(*this, dest);
return &it->second; if (!key_id.IsNull()) {
} else { auto it = mapKeyMetadata.find(key_id);
auto it2 = m_script_metadata.find(CScriptID(id)); if (it != mapKeyMetadata.end()) {
if (it2 != m_script_metadata.end()) { return &it->second;
return &it2->second;
} }
} }
CScript scriptPubKey = GetScriptForDestination(dest);
auto it = m_script_metadata.find(CScriptID(scriptPubKey));
if (it != m_script_metadata.end()) {
return &it->second;
}
return nullptr; return nullptr;
} }
@ -1023,7 +1022,7 @@ bool LegacyScriptPubKeyMan::NewKeyPool()
m_pool_key_to_index.clear(); m_pool_key_to_index.clear();
if (!TopUpKeyPool()) { if (!TopUp()) {
return false; return false;
} }
WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n"); WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
@ -1031,7 +1030,7 @@ bool LegacyScriptPubKeyMan::NewKeyPool()
return true; return true;
} }
bool LegacyScriptPubKeyMan::TopUpKeyPool(unsigned int kpSize) bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
{ {
if (!CanGenerateKeys()) { if (!CanGenerateKeys()) {
return false; return false;
@ -1148,7 +1147,7 @@ bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& key
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
TopUpKeyPool(); TopUp();
bool fReturningInternal = fRequestedInternal; bool fReturningInternal = fRequestedInternal;
fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);

View file

@ -186,7 +186,8 @@ public:
virtual int64_t GetTimeFirstKey() const { return 0; } virtual int64_t GetTimeFirstKey() const { return 0; }
virtual const CKeyMetadata* GetMetadata(uint160 id) const { return nullptr; } //! Return address metadata
virtual const CKeyMetadata* GetMetadata(const CTxDestination& dest) const { return nullptr; }
}; };
class LegacyScriptPubKeyMan : public ScriptPubKeyMan, public FillableSigningProvider class LegacyScriptPubKeyMan : public ScriptPubKeyMan, public FillableSigningProvider
@ -302,7 +303,7 @@ public:
int64_t GetTimeFirstKey() const override; int64_t GetTimeFirstKey() const override;
const CKeyMetadata* GetMetadata(uint160 id) const override; const CKeyMetadata* GetMetadata(const CTxDestination& dest) const override;
bool CanGetAddresses(bool internal = false) override; bool CanGetAddresses(bool internal = false) override;
@ -355,7 +356,6 @@ public:
//! Load a keypool entry //! Load a keypool entry
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool TopUpKeyPool(unsigned int kpSize = 0);
bool NewKeyPool(); bool NewKeyPool();
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);

View file

@ -572,7 +572,9 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
// if we are using HD, replace the HD seed with a new one // if we are using HD, replace the HD seed with a new one
if (auto spk_man = m_spk_man.get()) { if (auto spk_man = m_spk_man.get()) {
if (spk_man->IsHDEnabled()) { if (spk_man->IsHDEnabled()) {
spk_man->SetupGeneration(true); if (!spk_man->SetupGeneration(true)) {
return false;
}
} }
} }
Lock(); Lock();