diff --git a/src/keystore.cpp b/src/keystore.cpp index 4ab089e03..cbcc6d7ca 100644 --- a/src/keystore.cpp +++ b/src/keystore.cpp @@ -136,3 +136,25 @@ bool CBasicKeyStore::HaveWatchOnly() const LOCK(cs_KeyStore); return (!setWatchOnly.empty()); } + +CKeyID GetKeyForDestination(const CKeyStore& store, const CTxDestination& dest) +{ + // Only supports destinations which map to single public keys, i.e. P2PKH, + // P2WPKH, and P2SH-P2WPKH. + if (auto id = boost::get(&dest)) { + return *id; + } + if (auto witness_id = boost::get(&dest)) { + return CKeyID(*witness_id); + } + if (auto script_id = boost::get(&dest)) { + CScript script; + CTxDestination inner_dest; + if (store.GetCScript(*script_id, script) && ExtractDestination(script, inner_dest)) { + if (auto inner_witness_id = boost::get(&inner_dest)) { + return CKeyID(*inner_witness_id); + } + } + } + return CKeyID(); +} diff --git a/src/keystore.h b/src/keystore.h index 4e6d8e8a2..0f3b5706f 100644 --- a/src/keystore.h +++ b/src/keystore.h @@ -78,4 +78,7 @@ public: typedef std::vector > CKeyingMaterial; typedef std::map > > CryptedKeyMap; +/** Return the CKeyID of the key involved in a script (if there is a unique one). */ +CKeyID GetKeyForDestination(const CKeyStore& store, const CTxDestination& dest); + #endif // BITCOIN_KEYSTORE_H