Branch data Line data Source code
# 1 : : // Copyright (c) 2019-2021 The Bitcoin Core developers
# 2 : : // Distributed under the MIT software license, see the accompanying
# 3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
# 4 : :
# 5 : : #include <key_io.h>
# 6 : : #include <logging.h>
# 7 : : #include <outputtype.h>
# 8 : : #include <script/descriptor.h>
# 9 : : #include <script/sign.h>
# 10 : : #include <util/bip32.h>
# 11 : : #include <util/strencodings.h>
# 12 : : #include <util/string.h>
# 13 : : #include <util/system.h>
# 14 : : #include <util/time.h>
# 15 : : #include <util/translation.h>
# 16 : : #include <wallet/scriptpubkeyman.h>
# 17 : :
# 18 : : #include <optional>
# 19 : :
# 20 : : namespace wallet {
# 21 : : //! Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value. See BIP 32 for more details.
# 22 : : const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
# 23 : :
# 24 : : bool LegacyScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, bilingual_str& error)
# 25 : 9112 : {
# 26 [ - + ]: 9112 : if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
# 27 : 0 : error = _("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types");
# 28 : 0 : return false;
# 29 : 0 : }
# 30 : 9112 : assert(type != OutputType::BECH32M);
# 31 : :
# 32 : 9112 : LOCK(cs_KeyStore);
# 33 : 9112 : error.clear();
# 34 : :
# 35 : : // Generate a new key that is added to wallet
# 36 : 9112 : CPubKey new_key;
# 37 [ + + ]: 9112 : if (!GetKeyFromPool(new_key, type)) {
# 38 : 4 : error = _("Error: Keypool ran out, please call keypoolrefill first");
# 39 : 4 : return false;
# 40 : 4 : }
# 41 : 9108 : LearnRelatedScripts(new_key, type);
# 42 : 9108 : dest = GetDestinationForKey(new_key, type);
# 43 : 9108 : return true;
# 44 : 9112 : }
# 45 : :
# 46 : : typedef std::vector<unsigned char> valtype;
# 47 : :
# 48 : : namespace {
# 49 : :
# 50 : : /**
# 51 : : * This is an enum that tracks the execution context of a script, similar to
# 52 : : * SigVersion in script/interpreter. It is separate however because we want to
# 53 : : * distinguish between top-level scriptPubKey execution and P2SH redeemScript
# 54 : : * execution (a distinction that has no impact on consensus rules).
# 55 : : */
# 56 : : enum class IsMineSigVersion
# 57 : : {
# 58 : : TOP = 0, //!< scriptPubKey execution
# 59 : : P2SH = 1, //!< P2SH redeemScript
# 60 : : WITNESS_V0 = 2, //!< P2WSH witness script execution
# 61 : : };
# 62 : :
# 63 : : /**
# 64 : : * This is an internal representation of isminetype + invalidity.
# 65 : : * Its order is significant, as we return the max of all explored
# 66 : : * possibilities.
# 67 : : */
# 68 : : enum class IsMineResult
# 69 : : {
# 70 : : NO = 0, //!< Not ours
# 71 : : WATCH_ONLY = 1, //!< Included in watch-only balance
# 72 : : SPENDABLE = 2, //!< Included in all balances
# 73 : : INVALID = 3, //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
# 74 : : };
# 75 : :
# 76 : : bool PermitsUncompressed(IsMineSigVersion sigversion)
# 77 : 1060743 : {
# 78 [ + + ][ + + ]: 1060743 : return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
# 79 : 1060743 : }
# 80 : :
# 81 : : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
# 82 : 3343 : {
# 83 [ + + ]: 5421 : for (const valtype& pubkey : pubkeys) {
# 84 : 5421 : CKeyID keyID = CPubKey(pubkey).GetID();
# 85 [ + + ]: 5421 : if (!keystore.HaveKey(keyID)) return false;
# 86 : 5421 : }
# 87 : 2591 : return true;
# 88 : 3343 : }
# 89 : :
# 90 : : //! Recursively solve script and return spendable/watchonly/invalid status.
# 91 : : //!
# 92 : : //! @param keystore legacy key and script store
# 93 : : //! @param scriptPubKey script to solve
# 94 : : //! @param sigversion script type (top-level / redeemscript / witnessscript)
# 95 : : //! @param recurse_scripthash whether to recurse into nested p2sh and p2wsh
# 96 : : //! scripts or simply treat any script that has been
# 97 : : //! stored in the keystore as spendable
# 98 : : IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
# 99 : 2134806 : {
# 100 : 2134806 : IsMineResult ret = IsMineResult::NO;
# 101 : :
# 102 : 2134806 : std::vector<valtype> vSolutions;
# 103 : 2134806 : TxoutType whichType = Solver(scriptPubKey, vSolutions);
# 104 : :
# 105 : 2134806 : CKeyID keyID;
# 106 [ - + ]: 2134806 : switch (whichType) {
# 107 [ + + ]: 7125 : case TxoutType::NONSTANDARD:
# 108 [ + + ]: 154276 : case TxoutType::NULL_DATA:
# 109 [ + + ]: 155187 : case TxoutType::WITNESS_UNKNOWN:
# 110 [ + + ]: 180549 : case TxoutType::WITNESS_V1_TAPROOT:
# 111 : 180549 : break;
# 112 [ + + ]: 13925 : case TxoutType::PUBKEY:
# 113 : 13925 : keyID = CPubKey(vSolutions[0]).GetID();
# 114 [ + + ][ + + ]: 13925 : if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
# 115 : 352 : return IsMineResult::INVALID;
# 116 : 352 : }
# 117 [ + + ]: 13573 : if (keystore.HaveKey(keyID)) {
# 118 : 10708 : ret = std::max(ret, IsMineResult::SPENDABLE);
# 119 : 10708 : }
# 120 : 13573 : break;
# 121 [ + + ]: 784068 : case TxoutType::WITNESS_V0_KEYHASH:
# 122 : 784068 : {
# 123 [ + + ]: 784068 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
# 124 : : // P2WPKH inside P2WSH is invalid.
# 125 : 1 : return IsMineResult::INVALID;
# 126 : 1 : }
# 127 [ + + ][ + + ]: 784067 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
# [ + + ]
# 128 : : // We do not support bare witness outputs unless the P2SH version of it would be
# 129 : : // acceptable as well. This protects against matching before segwit activates.
# 130 : : // This also applies to the P2WSH case.
# 131 : 269665 : break;
# 132 : 269665 : }
# 133 : 514402 : ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
# 134 : 514402 : break;
# 135 : 784067 : }
# 136 [ + + ]: 1042946 : case TxoutType::PUBKEYHASH:
# 137 : 1042946 : keyID = CKeyID(uint160(vSolutions[0]));
# 138 [ + + ]: 1042946 : if (!PermitsUncompressed(sigversion)) {
# 139 : 515359 : CPubKey pubkey;
# 140 [ + + ][ + + ]: 515359 : if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
# 141 : 777 : return IsMineResult::INVALID;
# 142 : 777 : }
# 143 : 515359 : }
# 144 [ + + ]: 1042169 : if (keystore.HaveKey(keyID)) {
# 145 : 952486 : ret = std::max(ret, IsMineResult::SPENDABLE);
# 146 : 952486 : }
# 147 : 1042169 : break;
# 148 [ + + ]: 86193 : case TxoutType::SCRIPTHASH:
# 149 : 86193 : {
# 150 [ + + ]: 86193 : if (sigversion != IsMineSigVersion::TOP) {
# 151 : : // P2SH inside P2WSH or P2SH is invalid.
# 152 : 2 : return IsMineResult::INVALID;
# 153 : 2 : }
# 154 : 86191 : CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
# 155 : 86191 : CScript subscript;
# 156 [ + + ]: 86191 : if (keystore.GetCScript(scriptID, subscript)) {
# 157 [ + + ]: 31000 : ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
# 158 : 31000 : }
# 159 : 86191 : break;
# 160 : 86193 : }
# 161 [ + + ]: 21927 : case TxoutType::WITNESS_V0_SCRIPTHASH:
# 162 : 21927 : {
# 163 [ + + ]: 21927 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
# 164 : : // P2WSH inside P2WSH is invalid.
# 165 : 1 : return IsMineResult::INVALID;
# 166 : 1 : }
# 167 [ + + ][ + + ]: 21926 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
# [ + + ]
# 168 : 14081 : break;
# 169 : 14081 : }
# 170 : 7845 : uint160 hash;
# 171 : 7845 : CRIPEMD160().Write(vSolutions[0].data(), vSolutions[0].size()).Finalize(hash.begin());
# 172 : 7845 : CScriptID scriptID = CScriptID(hash);
# 173 : 7845 : CScript subscript;
# 174 [ + + ]: 7845 : if (keystore.GetCScript(scriptID, subscript)) {
# 175 [ + + ]: 7821 : ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
# 176 : 7821 : }
# 177 : 7845 : break;
# 178 : 21926 : }
# 179 : :
# 180 [ + + ]: 5198 : case TxoutType::MULTISIG:
# 181 : 5198 : {
# 182 : : // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
# 183 [ + + ]: 5198 : if (sigversion == IsMineSigVersion::TOP) {
# 184 : 1326 : break;
# 185 : 1326 : }
# 186 : :
# 187 : : // Only consider transactions "mine" if we own ALL the
# 188 : : // keys involved. Multi-signature transactions that are
# 189 : : // partially owned (somebody else has a key that can spend
# 190 : : // them) enable spend-out-from-under-you attacks, especially
# 191 : : // in shared-wallet situations.
# 192 : 3872 : std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
# 193 [ + + ]: 3872 : if (!PermitsUncompressed(sigversion)) {
# 194 [ + + ]: 6857 : for (size_t i = 0; i < keys.size(); i++) {
# 195 [ + + ]: 4540 : if (keys[i].size() != 33) {
# 196 : 529 : return IsMineResult::INVALID;
# 197 : 529 : }
# 198 : 4540 : }
# 199 : 2846 : }
# 200 [ + + ]: 3343 : if (HaveKeys(keys, keystore)) {
# 201 : 2591 : ret = std::max(ret, IsMineResult::SPENDABLE);
# 202 : 2591 : }
# 203 : 3343 : break;
# 204 : 3872 : }
# 205 : 2134806 : } // no default case, so the compiler can warn about missing cases
# 206 : :
# 207 [ + + ][ + + ]: 2133144 : if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
# 208 : 13975 : ret = std::max(ret, IsMineResult::WATCH_ONLY);
# 209 : 13975 : }
# 210 : 2133144 : return ret;
# 211 : 2134806 : }
# 212 : :
# 213 : : } // namespace
# 214 : :
# 215 : : isminetype LegacyScriptPubKeyMan::IsMine(const CScript& script) const
# 216 : 929496 : {
# 217 [ - + ]: 929496 : switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
# 218 [ + + ]: 1590 : case IsMineResult::INVALID:
# 219 [ + + ]: 516991 : case IsMineResult::NO:
# 220 : 516991 : return ISMINE_NO;
# 221 [ + + ]: 11140 : case IsMineResult::WATCH_ONLY:
# 222 : 11140 : return ISMINE_WATCH_ONLY;
# 223 [ + + ]: 401365 : case IsMineResult::SPENDABLE:
# 224 : 401365 : return ISMINE_SPENDABLE;
# 225 : 929496 : }
# 226 : 0 : assert(false);
# 227 : 0 : }
# 228 : :
# 229 : : bool LegacyScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
# 230 : 53 : {
# 231 : 53 : {
# 232 : 53 : LOCK(cs_KeyStore);
# 233 : 53 : assert(mapKeys.empty());
# 234 : :
# 235 : 0 : bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
# 236 : 53 : bool keyFail = false;
# 237 : 53 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
# 238 : 53 : WalletBatch batch(m_storage.GetDatabase());
# 239 [ + + ]: 134 : for (; mi != mapCryptedKeys.end(); ++mi)
# 240 : 116 : {
# 241 : 116 : const CPubKey &vchPubKey = (*mi).second.first;
# 242 : 116 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
# 243 : 116 : CKey key;
# 244 [ - + ]: 116 : if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
# 245 : 0 : {
# 246 : 0 : keyFail = true;
# 247 : 0 : break;
# 248 : 0 : }
# 249 : 116 : keyPass = true;
# 250 [ + + ]: 116 : if (fDecryptionThoroughlyChecked)
# 251 : 35 : break;
# 252 : 81 : else {
# 253 : : // Rewrite these encrypted keys with checksums
# 254 : 81 : batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
# 255 : 81 : }
# 256 : 116 : }
# 257 [ + - ][ - + ]: 53 : if (keyPass && keyFail)
# 258 : 0 : {
# 259 : 0 : LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
# 260 : 0 : throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
# 261 : 0 : }
# 262 [ - + ][ - + ]: 53 : if (keyFail || (!keyPass && !accept_no_keys))
# [ # # ]
# 263 : 0 : return false;
# 264 : 53 : fDecryptionThoroughlyChecked = true;
# 265 : 53 : }
# 266 : 0 : return true;
# 267 : 53 : }
# 268 : :
# 269 : : bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
# 270 : 18 : {
# 271 : 18 : LOCK(cs_KeyStore);
# 272 : 18 : encrypted_batch = batch;
# 273 [ - + ]: 18 : if (!mapCryptedKeys.empty()) {
# 274 : 0 : encrypted_batch = nullptr;
# 275 : 0 : return false;
# 276 : 0 : }
# 277 : :
# 278 : 18 : KeyMap keys_to_encrypt;
# 279 : 18 : keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
# 280 [ + + ]: 18 : for (const KeyMap::value_type& mKey : keys_to_encrypt)
# 281 : 276 : {
# 282 : 276 : const CKey &key = mKey.second;
# 283 : 276 : CPubKey vchPubKey = key.GetPubKey();
# 284 : 276 : CKeyingMaterial vchSecret(key.begin(), key.end());
# 285 : 276 : std::vector<unsigned char> vchCryptedSecret;
# 286 [ - + ]: 276 : if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
# 287 : 0 : encrypted_batch = nullptr;
# 288 : 0 : return false;
# 289 : 0 : }
# 290 [ - + ]: 276 : if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
# 291 : 0 : encrypted_batch = nullptr;
# 292 : 0 : return false;
# 293 : 0 : }
# 294 : 276 : }
# 295 : 18 : encrypted_batch = nullptr;
# 296 : 18 : return true;
# 297 : 18 : }
# 298 : :
# 299 : : bool LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool, bilingual_str& error)
# 300 : 3004 : {
# 301 [ - + ]: 3004 : if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
# 302 : 0 : error = _("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types");
# 303 : 0 : return false;
# 304 : 0 : }
# 305 : 3004 : assert(type != OutputType::BECH32M);
# 306 : :
# 307 : 3004 : LOCK(cs_KeyStore);
# 308 [ + + ]: 3004 : if (!CanGetAddresses(internal)) {
# 309 : 12 : error = _("Error: Keypool ran out, please call keypoolrefill first");
# 310 : 12 : return false;
# 311 : 12 : }
# 312 : :
# 313 [ + + ]: 2992 : if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
# 314 : 4 : error = _("Error: Keypool ran out, please call keypoolrefill first");
# 315 : 4 : return false;
# 316 : 4 : }
# 317 : 2988 : address = GetDestinationForKey(keypool.vchPubKey, type);
# 318 : 2988 : return true;
# 319 : 2992 : }
# 320 : :
# 321 : : bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
# 322 : 14 : {
# 323 : 14 : LOCK(cs_KeyStore);
# 324 : :
# 325 : 14 : auto it = m_inactive_hd_chains.find(seed_id);
# 326 [ - + ]: 14 : if (it == m_inactive_hd_chains.end()) {
# 327 : 0 : return false;
# 328 : 0 : }
# 329 : :
# 330 : 14 : CHDChain& chain = it->second;
# 331 : :
# 332 [ + + ]: 14 : if (internal) {
# 333 : 6 : chain.m_next_internal_index = std::max(chain.m_next_internal_index, index + 1);
# 334 : 8 : } else {
# 335 : 8 : chain.m_next_external_index = std::max(chain.m_next_external_index, index + 1);
# 336 : 8 : }
# 337 : :
# 338 : 14 : TopUpChain(chain, 0);
# 339 : :
# 340 : 14 : return true;
# 341 : 14 : }
# 342 : :
# 343 : : std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
# 344 : 71641 : {
# 345 : 71641 : LOCK(cs_KeyStore);
# 346 : 71641 : std::vector<WalletDestination> result;
# 347 : : // extract addresses and check if they match with an unused keypool key
# 348 [ + + ]: 71641 : for (const auto& keyid : GetAffectedKeys(script, *this)) {
# 349 : 67570 : std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
# 350 [ + + ]: 67570 : if (mi != m_pool_key_to_index.end()) {
# 351 : 43 : WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
# 352 [ + + ]: 177 : for (const auto& keypool : MarkReserveKeysAsUsed(mi->second)) {
# 353 : : // derive all possible destinations as any of them could have been used
# 354 [ + + ]: 531 : for (const auto& type : LEGACY_OUTPUT_TYPES) {
# 355 : 531 : const auto& dest = GetDestinationForKey(keypool.vchPubKey, type);
# 356 : 531 : result.push_back({dest, keypool.fInternal});
# 357 : 531 : }
# 358 : 177 : }
# 359 : :
# 360 [ + + ]: 43 : if (!TopUp()) {
# 361 : 1 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
# 362 : 1 : }
# 363 : 43 : }
# 364 : :
# 365 : : // Find the key's metadata and check if it's seed id (if it has one) is inactive, i.e. it is not the current m_hd_chain seed id.
# 366 : : // If so, TopUp the inactive hd chain
# 367 : 67570 : auto it = mapKeyMetadata.find(keyid);
# 368 [ + + ]: 67570 : if (it != mapKeyMetadata.end()){
# 369 : 67568 : CKeyMetadata meta = it->second;
# 370 [ + + ][ + + ]: 67568 : if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
# 371 : 14 : std::vector<uint32_t> path;
# 372 [ + - ]: 14 : if (meta.has_key_origin) {
# 373 : 14 : path = meta.key_origin.path;
# 374 [ # # ]: 14 : } else if (!ParseHDKeypath(meta.hdKeypath, path)) {
# 375 : 0 : WalletLogPrintf("%s: Adding inactive seed keys failed, invalid hdKeypath: %s\n",
# 376 : 0 : __func__,
# 377 : 0 : meta.hdKeypath);
# 378 : 0 : }
# 379 [ - + ]: 14 : if (path.size() != 3) {
# 380 : 0 : WalletLogPrintf("%s: Adding inactive seed keys failed, invalid path size: %d, has_key_origin: %s\n",
# 381 : 0 : __func__,
# 382 : 0 : path.size(),
# 383 : 0 : meta.has_key_origin);
# 384 : 14 : } else {
# 385 : 14 : bool internal = (path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
# 386 : 14 : int64_t index = path[2] & ~BIP32_HARDENED_KEY_LIMIT;
# 387 : :
# 388 [ - + ]: 14 : if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
# 389 : 0 : WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
# 390 : 0 : }
# 391 : 14 : }
# 392 : 14 : }
# 393 : 67568 : }
# 394 : 67570 : }
# 395 : :
# 396 : 71641 : return result;
# 397 : 71641 : }
# 398 : :
# 399 : : void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
# 400 : 111 : {
# 401 : 111 : LOCK(cs_KeyStore);
# 402 [ - + ][ - + ]: 111 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
# 403 : 0 : return;
# 404 : 0 : }
# 405 : :
# 406 : 111 : std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
# 407 [ + + ]: 9107 : for (auto& meta_pair : mapKeyMetadata) {
# 408 : 9107 : CKeyMetadata& meta = meta_pair.second;
# 409 [ + + ][ + + ]: 9107 : if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin && meta.hdKeypath != "s") { // If the hdKeypath is "s", that's the seed and it doesn't have a key origin
# [ - + ]
# 410 : 0 : CKey key;
# 411 : 0 : GetKey(meta.hd_seed_id, key);
# 412 : 0 : CExtKey masterKey;
# 413 : 0 : masterKey.SetSeed(key);
# 414 : : // Add to map
# 415 : 0 : CKeyID master_id = masterKey.key.GetPubKey().GetID();
# 416 : 0 : std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
# 417 [ # # ]: 0 : if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
# 418 : 0 : throw std::runtime_error("Invalid stored hdKeypath");
# 419 : 0 : }
# 420 : 0 : meta.has_key_origin = true;
# 421 [ # # ]: 0 : if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
# 422 : 0 : meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
# 423 : 0 : }
# 424 : :
# 425 : : // Write meta to wallet
# 426 : 0 : CPubKey pubkey;
# 427 [ # # ]: 0 : if (GetPubKey(meta_pair.first, pubkey)) {
# 428 : 0 : batch->WriteKeyMetadata(meta, pubkey, true);
# 429 : 0 : }
# 430 : 0 : }
# 431 : 9107 : }
# 432 : 111 : }
# 433 : :
# 434 : : bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
# 435 : 240 : {
# 436 [ + + ][ - + ]: 240 : if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
# [ - + ]
# 437 : 0 : return false;
# 438 : 0 : }
# 439 : :
# 440 : 240 : SetHDSeed(GenerateNewSeed());
# 441 [ - + ]: 240 : if (!NewKeyPool()) {
# 442 : 0 : return false;
# 443 : 0 : }
# 444 : 240 : return true;
# 445 : 240 : }
# 446 : :
# 447 : : bool LegacyScriptPubKeyMan::IsHDEnabled() const
# 448 : 66972 : {
# 449 : 66972 : return !m_hd_chain.seed_id.IsNull();
# 450 : 66972 : }
# 451 : :
# 452 : : bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
# 453 : 21389 : {
# 454 : 21389 : LOCK(cs_KeyStore);
# 455 : : // Check if the keypool has keys
# 456 : 21389 : bool keypool_has_keys;
# 457 [ + + ][ + - ]: 21389 : if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
# 458 : 3110 : keypool_has_keys = setInternalKeyPool.size() > 0;
# 459 : 18279 : } else {
# 460 : 18279 : keypool_has_keys = KeypoolCountExternalKeys() > 0;
# 461 : 18279 : }
# 462 : : // If the keypool doesn't have keys, check if we can generate them
# 463 [ + + ]: 21389 : if (!keypool_has_keys) {
# 464 : 8147 : return CanGenerateKeys();
# 465 : 8147 : }
# 466 : 13242 : return keypool_has_keys;
# 467 : 21389 : }
# 468 : :
# 469 : : bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
# 470 : 0 : {
# 471 : 0 : LOCK(cs_KeyStore);
# 472 : :
# 473 [ # # ]: 0 : if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
# 474 : : // Nothing to do here if private keys are not enabled
# 475 : 0 : return true;
# 476 : 0 : }
# 477 : :
# 478 : 0 : bool hd_upgrade = false;
# 479 : 0 : bool split_upgrade = false;
# 480 [ # # ][ # # ]: 0 : if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
# 481 : 0 : WalletLogPrintf("Upgrading wallet to HD\n");
# 482 : 0 : m_storage.SetMinVersion(FEATURE_HD);
# 483 : :
# 484 : : // generate a new master key
# 485 : 0 : CPubKey masterPubKey = GenerateNewSeed();
# 486 : 0 : SetHDSeed(masterPubKey);
# 487 : 0 : hd_upgrade = true;
# 488 : 0 : }
# 489 : : // Upgrade to HD chain split if necessary
# 490 [ # # ][ # # ]: 0 : if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
# 491 : 0 : WalletLogPrintf("Upgrading wallet to use HD chain split\n");
# 492 : 0 : m_storage.SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
# 493 : 0 : split_upgrade = FEATURE_HD_SPLIT > prev_version;
# 494 : : // Upgrade the HDChain
# 495 [ # # ]: 0 : if (m_hd_chain.nVersion < CHDChain::VERSION_HD_CHAIN_SPLIT) {
# 496 : 0 : m_hd_chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
# 497 [ # # ]: 0 : if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(m_hd_chain)) {
# 498 : 0 : throw std::runtime_error(std::string(__func__) + ": writing chain failed");
# 499 : 0 : }
# 500 : 0 : }
# 501 : 0 : }
# 502 : : // Mark all keys currently in the keypool as pre-split
# 503 [ # # ]: 0 : if (split_upgrade) {
# 504 : 0 : MarkPreSplitKeys();
# 505 : 0 : }
# 506 : : // Regenerate the keypool if upgraded to HD
# 507 [ # # ]: 0 : if (hd_upgrade) {
# 508 [ # # ]: 0 : if (!NewKeyPool()) {
# 509 : 0 : error = _("Unable to generate keys");
# 510 : 0 : return false;
# 511 : 0 : }
# 512 : 0 : }
# 513 : 0 : return true;
# 514 : 0 : }
# 515 : :
# 516 : : bool LegacyScriptPubKeyMan::HavePrivateKeys() const
# 517 : 13 : {
# 518 : 13 : LOCK(cs_KeyStore);
# 519 [ - + ][ - + ]: 13 : return !mapKeys.empty() || !mapCryptedKeys.empty();
# 520 : 13 : }
# 521 : :
# 522 : : void LegacyScriptPubKeyMan::RewriteDB()
# 523 : 0 : {
# 524 : 0 : LOCK(cs_KeyStore);
# 525 : 0 : setInternalKeyPool.clear();
# 526 : 0 : setExternalKeyPool.clear();
# 527 : 0 : m_pool_key_to_index.clear();
# 528 : : // Note: can't top-up keypool here, because wallet is locked.
# 529 : : // User will be prompted to unlock wallet the next operation
# 530 : : // that requires a new key.
# 531 : 0 : }
# 532 : :
# 533 : 1221 : static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
# 534 [ + + ]: 1221 : if (setKeyPool.empty()) {
# 535 : 294 : return GetTime();
# 536 : 294 : }
# 537 : :
# 538 : 927 : CKeyPool keypool;
# 539 : 927 : int64_t nIndex = *(setKeyPool.begin());
# 540 [ - + ]: 927 : if (!batch.ReadPool(nIndex, keypool)) {
# 541 : 0 : throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
# 542 : 0 : }
# 543 : 927 : assert(keypool.vchPubKey.IsValid());
# 544 : 0 : return keypool.nTime;
# 545 : 927 : }
# 546 : :
# 547 : : std::optional<int64_t> LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
# 548 : 651 : {
# 549 : 651 : LOCK(cs_KeyStore);
# 550 : :
# 551 : 651 : WalletBatch batch(m_storage.GetDatabase());
# 552 : :
# 553 : : // load oldest key from keypool, get time and return
# 554 : 651 : int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
# 555 [ + + ][ + - ]: 651 : if (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
# 556 : 570 : oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
# 557 [ - + ]: 570 : if (!set_pre_split_keypool.empty()) {
# 558 : 0 : oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
# 559 : 0 : }
# 560 : 570 : }
# 561 : :
# 562 : 651 : return oldestKey;
# 563 : 651 : }
# 564 : :
# 565 : : size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
# 566 : 18930 : {
# 567 : 18930 : LOCK(cs_KeyStore);
# 568 : 18930 : return setExternalKeyPool.size() + set_pre_split_keypool.size();
# 569 : 18930 : }
# 570 : :
# 571 : : unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
# 572 : 1141 : {
# 573 : 1141 : LOCK(cs_KeyStore);
# 574 : 1141 : return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
# 575 : 1141 : }
# 576 : :
# 577 : : int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
# 578 : 58 : {
# 579 : 58 : LOCK(cs_KeyStore);
# 580 : 58 : return nTimeFirstKey;
# 581 : 58 : }
# 582 : :
# 583 : : std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
# 584 : 516347 : {
# 585 : 516347 : return std::make_unique<LegacySigningProvider>(*this);
# 586 : 516347 : }
# 587 : :
# 588 : : bool LegacyScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
# 589 : 673515 : {
# 590 : 673515 : IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
# 591 [ + + ][ + + ]: 673515 : if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
# 592 : : // If ismine, it means we recognize keys or script ids in the script, or
# 593 : : // are watching the script itself, and we can at least provide metadata
# 594 : : // or solving information, even if not able to sign fully.
# 595 : 588683 : return true;
# 596 : 588683 : } else {
# 597 : : // If, given the stuff in sigdata, we could make a valid sigature, then we can provide for this script
# 598 : 84832 : ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
# 599 [ + + ]: 84832 : if (!sigdata.signatures.empty()) {
# 600 : : // If we could make signatures, make sure we have a private key to actually make a signature
# 601 : 156 : bool has_privkeys = false;
# 602 [ + + ]: 188 : for (const auto& key_sig_pair : sigdata.signatures) {
# 603 : 188 : has_privkeys |= HaveKey(key_sig_pair.first);
# 604 : 188 : }
# 605 : 156 : return has_privkeys;
# 606 : 156 : }
# 607 : 84676 : return false;
# 608 : 84832 : }
# 609 : 673515 : }
# 610 : :
# 611 : : bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
# 612 : 3531 : {
# 613 : 3531 : return ::SignTransaction(tx, this, coins, sighash, input_errors);
# 614 : 3531 : }
# 615 : :
# 616 : : SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
# 617 : 8 : {
# 618 : 8 : CKey key;
# 619 [ - + ]: 8 : if (!GetKey(ToKeyID(pkhash), key)) {
# 620 : 0 : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
# 621 : 0 : }
# 622 : :
# 623 [ + - ]: 8 : if (MessageSign(key, message, str_sig)) {
# 624 : 8 : return SigningResult::OK;
# 625 : 8 : }
# 626 : 0 : return SigningResult::SIGNING_FAILED;
# 627 : 8 : }
# 628 : :
# 629 : : TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
# 630 : 287 : {
# 631 [ + - ]: 287 : if (n_signed) {
# 632 : 287 : *n_signed = 0;
# 633 : 287 : }
# 634 [ + + ]: 709 : for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
# 635 : 423 : const CTxIn& txin = psbtx.tx->vin[i];
# 636 : 423 : PSBTInput& input = psbtx.inputs.at(i);
# 637 : :
# 638 [ + + ]: 423 : if (PSBTInputSigned(input)) {
# 639 : 21 : continue;
# 640 : 21 : }
# 641 : :
# 642 : : // Get the Sighash type
# 643 [ + + ][ + + ]: 402 : if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
# [ - + ]
# 644 : 0 : return TransactionError::SIGHASH_MISMATCH;
# 645 : 0 : }
# 646 : :
# 647 : : // Check non_witness_utxo has specified prevout
# 648 [ + + ]: 402 : if (input.non_witness_utxo) {
# 649 [ + + ]: 370 : if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
# 650 : 1 : return TransactionError::MISSING_INPUTS;
# 651 : 1 : }
# 652 [ + + ]: 370 : } else if (input.witness_utxo.IsNull()) {
# 653 : : // There's no UTXO so we can just skip this now
# 654 : 25 : continue;
# 655 : 25 : }
# 656 : 376 : SignatureData sigdata;
# 657 : 376 : input.FillSignatureData(sigdata);
# 658 : 376 : SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
# 659 : :
# 660 : 376 : bool signed_one = PSBTInputSigned(input);
# 661 [ + - ][ + + ]: 376 : if (n_signed && (signed_one || !sign)) {
# [ + + ]
# 662 : : // If sign is false, we assume that we _could_ sign if we get here. This
# 663 : : // will never have false negatives; it is hard to tell under what i
# 664 : : // circumstances it could have false positives.
# 665 : 348 : (*n_signed)++;
# 666 : 348 : }
# 667 : 376 : }
# 668 : :
# 669 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
# 670 [ + + ]: 729 : for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
# 671 : 443 : UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
# 672 : 443 : }
# 673 : :
# 674 : 286 : return TransactionError::OK;
# 675 : 287 : }
# 676 : :
# 677 : : std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
# 678 : 781 : {
# 679 : 781 : LOCK(cs_KeyStore);
# 680 : :
# 681 : 781 : CKeyID key_id = GetKeyForDestination(*this, dest);
# 682 [ + + ]: 781 : if (!key_id.IsNull()) {
# 683 : 646 : auto it = mapKeyMetadata.find(key_id);
# 684 [ + + ]: 646 : if (it != mapKeyMetadata.end()) {
# 685 : 632 : return std::make_unique<CKeyMetadata>(it->second);
# 686 : 632 : }
# 687 : 646 : }
# 688 : :
# 689 : 149 : CScript scriptPubKey = GetScriptForDestination(dest);
# 690 : 149 : auto it = m_script_metadata.find(CScriptID(scriptPubKey));
# 691 [ + + ]: 149 : if (it != m_script_metadata.end()) {
# 692 : 37 : return std::make_unique<CKeyMetadata>(it->second);
# 693 : 37 : }
# 694 : :
# 695 : 112 : return nullptr;
# 696 : 149 : }
# 697 : :
# 698 : : uint256 LegacyScriptPubKeyMan::GetID() const
# 699 : 513 : {
# 700 : 513 : return uint256::ONE;
# 701 : 513 : }
# 702 : :
# 703 : : /**
# 704 : : * Update wallet first key creation time. This should be called whenever keys
# 705 : : * are added to the wallet, with the oldest key creation time.
# 706 : : */
# 707 : : void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
# 708 : 33277 : {
# 709 : 33277 : AssertLockHeld(cs_KeyStore);
# 710 [ + + ]: 33277 : if (nCreateTime <= 1) {
# 711 : : // Cannot determine birthday information, so set the wallet birthday to
# 712 : : // the beginning of time.
# 713 : 715 : nTimeFirstKey = 1;
# 714 [ + + ][ + + ]: 32562 : } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
# 715 : 482 : nTimeFirstKey = nCreateTime;
# 716 : 482 : }
# 717 : 33277 : }
# 718 : :
# 719 : : bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
# 720 : 10972 : {
# 721 : 10972 : return AddKeyPubKeyInner(key, pubkey);
# 722 : 10972 : }
# 723 : :
# 724 : : bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
# 725 : 280 : {
# 726 : 280 : LOCK(cs_KeyStore);
# 727 : 280 : WalletBatch batch(m_storage.GetDatabase());
# 728 : 280 : return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
# 729 : 280 : }
# 730 : :
# 731 : : bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
# 732 : 21226 : {
# 733 : 21226 : AssertLockHeld(cs_KeyStore);
# 734 : :
# 735 : : // Make sure we aren't adding private keys to private key disabled wallets
# 736 : 21226 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
# 737 : :
# 738 : : // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
# 739 : : // which is overridden below. To avoid flushes, the database handle is
# 740 : : // tunneled through to it.
# 741 : 0 : bool needsDB = !encrypted_batch;
# 742 [ + - ]: 21226 : if (needsDB) {
# 743 : 21226 : encrypted_batch = &batch;
# 744 : 21226 : }
# 745 [ - + ]: 21226 : if (!AddKeyPubKeyInner(secret, pubkey)) {
# 746 [ # # ]: 0 : if (needsDB) encrypted_batch = nullptr;
# 747 : 0 : return false;
# 748 : 0 : }
# 749 [ + - ]: 21226 : if (needsDB) encrypted_batch = nullptr;
# 750 : :
# 751 : : // check if we need to remove from watch-only
# 752 : 21226 : CScript script;
# 753 : 21226 : script = GetScriptForDestination(PKHash(pubkey));
# 754 [ + + ]: 21226 : if (HaveWatchOnly(script)) {
# 755 : 4 : RemoveWatchOnly(script);
# 756 : 4 : }
# 757 : 21226 : script = GetScriptForRawPubKey(pubkey);
# 758 [ + + ]: 21226 : if (HaveWatchOnly(script)) {
# 759 : 4 : RemoveWatchOnly(script);
# 760 : 4 : }
# 761 : :
# 762 [ + + ]: 21226 : if (!m_storage.HasEncryptionKeys()) {
# 763 : 20410 : return batch.WriteKey(pubkey,
# 764 : 20410 : secret.GetPrivKey(),
# 765 : 20410 : mapKeyMetadata[pubkey.GetID()]);
# 766 : 20410 : }
# 767 : 816 : m_storage.UnsetBlankWalletFlag(batch);
# 768 : 816 : return true;
# 769 : 21226 : }
# 770 : :
# 771 : : bool LegacyScriptPubKeyMan::LoadCScript(const CScript& redeemScript)
# 772 : 2868 : {
# 773 : : /* A sanity check was added in pull #3843 to avoid adding redeemScripts
# 774 : : * that never can be redeemed. However, old wallets may still contain
# 775 : : * these. Do not add them to the wallet and warn. */
# 776 [ - + ]: 2868 : if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
# 777 : 0 : {
# 778 : 0 : std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
# 779 : 0 : WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
# 780 : 0 : return true;
# 781 : 0 : }
# 782 : :
# 783 : 2868 : return FillableSigningProvider::AddCScript(redeemScript);
# 784 : 2868 : }
# 785 : :
# 786 : : void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
# 787 : 11224 : {
# 788 : 11224 : LOCK(cs_KeyStore);
# 789 : 11224 : UpdateTimeFirstKey(meta.nCreateTime);
# 790 : 11224 : mapKeyMetadata[keyID] = meta;
# 791 : 11224 : }
# 792 : :
# 793 : : void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
# 794 : 258 : {
# 795 : 258 : LOCK(cs_KeyStore);
# 796 : 258 : UpdateTimeFirstKey(meta.nCreateTime);
# 797 : 258 : m_script_metadata[script_id] = meta;
# 798 : 258 : }
# 799 : :
# 800 : : bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
# 801 : 32198 : {
# 802 : 32198 : LOCK(cs_KeyStore);
# 803 [ + + ]: 32198 : if (!m_storage.HasEncryptionKeys()) {
# 804 : 31382 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
# 805 : 31382 : }
# 806 : :
# 807 [ - + ]: 816 : if (m_storage.IsLocked()) {
# 808 : 0 : return false;
# 809 : 0 : }
# 810 : :
# 811 : 816 : std::vector<unsigned char> vchCryptedSecret;
# 812 : 816 : CKeyingMaterial vchSecret(key.begin(), key.end());
# 813 [ - + ]: 816 : if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
# 814 : 0 : return false;
# 815 : 0 : }
# 816 : :
# 817 [ - + ]: 816 : if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
# 818 : 0 : return false;
# 819 : 0 : }
# 820 : 816 : return true;
# 821 : 816 : }
# 822 : :
# 823 : : bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
# 824 : 150 : {
# 825 : : // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
# 826 [ + - ]: 150 : if (!checksum_valid) {
# 827 : 150 : fDecryptionThoroughlyChecked = false;
# 828 : 150 : }
# 829 : :
# 830 : 150 : return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
# 831 : 150 : }
# 832 : :
# 833 : : bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
# 834 : 1242 : {
# 835 : 1242 : LOCK(cs_KeyStore);
# 836 : 1242 : assert(mapKeys.empty());
# 837 : :
# 838 : 0 : mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
# 839 : 1242 : ImplicitlyLearnRelatedKeyScripts(vchPubKey);
# 840 : 1242 : return true;
# 841 : 1242 : }
# 842 : :
# 843 : : bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
# 844 : : const std::vector<unsigned char> &vchCryptedSecret)
# 845 : 1092 : {
# 846 [ - + ]: 1092 : if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
# 847 : 0 : return false;
# 848 : 1092 : {
# 849 : 1092 : LOCK(cs_KeyStore);
# 850 [ + - ]: 1092 : if (encrypted_batch)
# 851 : 1092 : return encrypted_batch->WriteCryptedKey(vchPubKey,
# 852 : 1092 : vchCryptedSecret,
# 853 : 1092 : mapKeyMetadata[vchPubKey.GetID()]);
# 854 : 0 : else
# 855 : 0 : return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
# 856 : 0 : vchCryptedSecret,
# 857 : 0 : mapKeyMetadata[vchPubKey.GetID()]);
# 858 : 1092 : }
# 859 : 1092 : }
# 860 : :
# 861 : : bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const
# 862 : 659604 : {
# 863 : 659604 : LOCK(cs_KeyStore);
# 864 : 659604 : return setWatchOnly.count(dest) > 0;
# 865 : 659604 : }
# 866 : :
# 867 : : bool LegacyScriptPubKeyMan::HaveWatchOnly() const
# 868 : 610 : {
# 869 : 610 : LOCK(cs_KeyStore);
# 870 : 610 : return (!setWatchOnly.empty());
# 871 : 610 : }
# 872 : :
# 873 : : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
# 874 : 951 : {
# 875 : 951 : std::vector<std::vector<unsigned char>> solutions;
# 876 [ + + ]: 951 : return Solver(dest, solutions) == TxoutType::PUBKEY &&
# 877 [ + + ]: 951 : (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
# 878 : 951 : }
# 879 : :
# 880 : : bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
# 881 : 13 : {
# 882 : 13 : {
# 883 : 13 : LOCK(cs_KeyStore);
# 884 : 13 : setWatchOnly.erase(dest);
# 885 : 13 : CPubKey pubKey;
# 886 [ + + ]: 13 : if (ExtractPubKey(dest, pubKey)) {
# 887 : 6 : mapWatchKeys.erase(pubKey.GetID());
# 888 : 6 : }
# 889 : : // Related CScripts are not removed; having superfluous scripts around is
# 890 : : // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
# 891 : 13 : }
# 892 : :
# 893 [ + + ]: 13 : if (!HaveWatchOnly())
# 894 : 5 : NotifyWatchonlyChanged(false);
# 895 [ - + ]: 13 : if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
# 896 : 0 : return false;
# 897 : :
# 898 : 13 : return true;
# 899 : 13 : }
# 900 : :
# 901 : : bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest)
# 902 : 263 : {
# 903 : 263 : return AddWatchOnlyInMem(dest);
# 904 : 263 : }
# 905 : :
# 906 : : bool LegacyScriptPubKeyMan::AddWatchOnlyInMem(const CScript &dest)
# 907 : 938 : {
# 908 : 938 : LOCK(cs_KeyStore);
# 909 : 938 : setWatchOnly.insert(dest);
# 910 : 938 : CPubKey pubKey;
# 911 [ + + ]: 938 : if (ExtractPubKey(dest, pubKey)) {
# 912 : 337 : mapWatchKeys[pubKey.GetID()] = pubKey;
# 913 : 337 : ImplicitlyLearnRelatedKeyScripts(pubKey);
# 914 : 337 : }
# 915 : 938 : return true;
# 916 : 938 : }
# 917 : :
# 918 : : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
# 919 : 675 : {
# 920 [ - + ]: 675 : if (!AddWatchOnlyInMem(dest))
# 921 : 0 : return false;
# 922 : 675 : const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
# 923 : 675 : UpdateTimeFirstKey(meta.nCreateTime);
# 924 : 675 : NotifyWatchonlyChanged(true);
# 925 [ + - ]: 675 : if (batch.WriteWatchOnly(dest, meta)) {
# 926 : 675 : m_storage.UnsetBlankWalletFlag(batch);
# 927 : 675 : return true;
# 928 : 675 : }
# 929 : 0 : return false;
# 930 : 675 : }
# 931 : :
# 932 : : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
# 933 : 675 : {
# 934 : 675 : m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
# 935 : 675 : return AddWatchOnlyWithDB(batch, dest);
# 936 : 675 : }
# 937 : :
# 938 : : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest)
# 939 : 0 : {
# 940 : 0 : WalletBatch batch(m_storage.GetDatabase());
# 941 : 0 : return AddWatchOnlyWithDB(batch, dest);
# 942 : 0 : }
# 943 : :
# 944 : : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
# 945 : 0 : {
# 946 : 0 : m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
# 947 : 0 : return AddWatchOnly(dest);
# 948 : 0 : }
# 949 : :
# 950 : : void LegacyScriptPubKeyMan::LoadHDChain(const CHDChain& chain)
# 951 : 209 : {
# 952 : 209 : LOCK(cs_KeyStore);
# 953 : 209 : m_hd_chain = chain;
# 954 : 209 : }
# 955 : :
# 956 : : void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
# 957 : 254 : {
# 958 : 254 : LOCK(cs_KeyStore);
# 959 : : // Store the new chain
# 960 [ - + ]: 254 : if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
# 961 : 0 : throw std::runtime_error(std::string(__func__) + ": writing chain failed");
# 962 : 0 : }
# 963 : : // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
# 964 [ + + ]: 254 : if (!m_hd_chain.seed_id.IsNull()) {
# 965 : 15 : AddInactiveHDChain(m_hd_chain);
# 966 : 15 : }
# 967 : :
# 968 : 254 : m_hd_chain = chain;
# 969 : 254 : }
# 970 : :
# 971 : : void LegacyScriptPubKeyMan::AddInactiveHDChain(const CHDChain& chain)
# 972 : 29 : {
# 973 : 29 : LOCK(cs_KeyStore);
# 974 : 29 : assert(!chain.seed_id.IsNull());
# 975 : 0 : m_inactive_hd_chains[chain.seed_id] = chain;
# 976 : 29 : }
# 977 : :
# 978 : : bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
# 979 : 1082314 : {
# 980 : 1082314 : LOCK(cs_KeyStore);
# 981 [ + + ]: 1082314 : if (!m_storage.HasEncryptionKeys()) {
# 982 : 1012480 : return FillableSigningProvider::HaveKey(address);
# 983 : 1012480 : }
# 984 : 69834 : return mapCryptedKeys.count(address) > 0;
# 985 : 1082314 : }
# 986 : :
# 987 : : bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
# 988 : 1106404 : {
# 989 : 1106404 : LOCK(cs_KeyStore);
# 990 [ + + ]: 1106404 : if (!m_storage.HasEncryptionKeys()) {
# 991 : 1104228 : return FillableSigningProvider::GetKey(address, keyOut);
# 992 : 1104228 : }
# 993 : :
# 994 : 2176 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
# 995 [ + - ]: 2176 : if (mi != mapCryptedKeys.end())
# 996 : 2176 : {
# 997 : 2176 : const CPubKey &vchPubKey = (*mi).second.first;
# 998 : 2176 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
# 999 : 2176 : return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret, vchPubKey, keyOut);
# 1000 : 2176 : }
# 1001 : 0 : return false;
# 1002 : 2176 : }
# 1003 : :
# 1004 : : bool LegacyScriptPubKeyMan::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
# 1005 : 608546 : {
# 1006 : 608546 : CKeyMetadata meta;
# 1007 : 608546 : {
# 1008 : 608546 : LOCK(cs_KeyStore);
# 1009 : 608546 : auto it = mapKeyMetadata.find(keyID);
# 1010 [ + + ]: 608546 : if (it != mapKeyMetadata.end()) {
# 1011 : 607710 : meta = it->second;
# 1012 : 607710 : }
# 1013 : 608546 : }
# 1014 [ + + ]: 608546 : if (meta.has_key_origin) {
# 1015 : 332957 : std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
# 1016 : 332957 : info.path = meta.key_origin.path;
# 1017 : 332957 : } else { // Single pubkeys get the master fingerprint of themselves
# 1018 : 275589 : std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
# 1019 : 275589 : }
# 1020 : 608546 : return true;
# 1021 : 608546 : }
# 1022 : :
# 1023 : : bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
# 1024 : 37939 : {
# 1025 : 37939 : LOCK(cs_KeyStore);
# 1026 : 37939 : WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
# 1027 [ + + ]: 37939 : if (it != mapWatchKeys.end()) {
# 1028 : 6052 : pubkey_out = it->second;
# 1029 : 6052 : return true;
# 1030 : 6052 : }
# 1031 : 31887 : return false;
# 1032 : 37939 : }
# 1033 : :
# 1034 : : bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
# 1035 : 1164203 : {
# 1036 : 1164203 : LOCK(cs_KeyStore);
# 1037 [ + + ]: 1164203 : if (!m_storage.HasEncryptionKeys()) {
# 1038 [ + + ]: 1065122 : if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
# 1039 : 37645 : return GetWatchPubKey(address, vchPubKeyOut);
# 1040 : 37645 : }
# 1041 : 1027477 : return true;
# 1042 : 1065122 : }
# 1043 : :
# 1044 : 99081 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
# 1045 [ + + ]: 99081 : if (mi != mapCryptedKeys.end())
# 1046 : 98794 : {
# 1047 : 98794 : vchPubKeyOut = (*mi).second.first;
# 1048 : 98794 : return true;
# 1049 : 98794 : }
# 1050 : : // Check for watch-only pubkeys
# 1051 : 287 : return GetWatchPubKey(address, vchPubKeyOut);
# 1052 : 99081 : }
# 1053 : :
# 1054 : : CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
# 1055 : 19833 : {
# 1056 : 19833 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
# 1057 : 0 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
# 1058 : 19833 : AssertLockHeld(cs_KeyStore);
# 1059 : 19833 : bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
# 1060 : :
# 1061 : 19833 : CKey secret;
# 1062 : :
# 1063 : : // Create new metadata
# 1064 : 19833 : int64_t nCreationTime = GetTime();
# 1065 : 19833 : CKeyMetadata metadata(nCreationTime);
# 1066 : :
# 1067 : : // use HD key derivation if HD was enabled during wallet creation and a seed is present
# 1068 [ + - ]: 19833 : if (IsHDEnabled()) {
# 1069 [ + - ]: 19833 : DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
# 1070 : 19833 : } else {
# 1071 : 0 : secret.MakeNewKey(fCompressed);
# 1072 : 0 : }
# 1073 : :
# 1074 : : // Compressed public keys were introduced in version 0.6.0
# 1075 [ + - ]: 19833 : if (fCompressed) {
# 1076 : 19833 : m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
# 1077 : 19833 : }
# 1078 : :
# 1079 : 19833 : CPubKey pubkey = secret.GetPubKey();
# 1080 : 19833 : assert(secret.VerifyPubKey(pubkey));
# 1081 : :
# 1082 : 0 : mapKeyMetadata[pubkey.GetID()] = metadata;
# 1083 : 19833 : UpdateTimeFirstKey(nCreationTime);
# 1084 : :
# 1085 [ - + ]: 19833 : if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
# 1086 : 0 : throw std::runtime_error(std::string(__func__) + ": AddKey failed");
# 1087 : 0 : }
# 1088 : 19833 : return pubkey;
# 1089 : 19833 : }
# 1090 : :
# 1091 : : void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
# 1092 : 19833 : {
# 1093 : : // for now we use a fixed keypath scheme of m/0'/0'/k
# 1094 : 19833 : CKey seed; //seed (256bit)
# 1095 : 19833 : CExtKey masterKey; //hd master key
# 1096 : 19833 : CExtKey accountKey; //key at m/0'
# 1097 : 19833 : CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
# 1098 : 19833 : CExtKey childKey; //key at m/0'/0'/<n>'
# 1099 : :
# 1100 : : // try to get the seed
# 1101 [ - + ]: 19833 : if (!GetKey(hd_chain.seed_id, seed))
# 1102 : 0 : throw std::runtime_error(std::string(__func__) + ": seed not found");
# 1103 : :
# 1104 : 19833 : masterKey.SetSeed(seed);
# 1105 : :
# 1106 : : // derive m/0'
# 1107 : : // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
# 1108 : 19833 : masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
# 1109 : :
# 1110 : : // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
# 1111 : 19833 : assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
# 1112 [ + + ]: 19833 : accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
# 1113 : :
# 1114 : : // derive child key at next index, skip keys already known to the wallet
# 1115 : 19833 : do {
# 1116 : : // always derive hardened keys
# 1117 : : // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
# 1118 : : // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
# 1119 [ + + ]: 19833 : if (internal) {
# 1120 : 6766 : chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
# 1121 : 6766 : metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
# 1122 : 6766 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
# 1123 : 6766 : metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
# 1124 : 6766 : metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
# 1125 : 6766 : hd_chain.nInternalChainCounter++;
# 1126 : 6766 : }
# 1127 : 13067 : else {
# 1128 : 13067 : chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
# 1129 : 13067 : metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
# 1130 : 13067 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
# 1131 : 13067 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
# 1132 : 13067 : metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
# 1133 : 13067 : hd_chain.nExternalChainCounter++;
# 1134 : 13067 : }
# 1135 [ - + ]: 19833 : } while (HaveKey(childKey.key.GetPubKey().GetID()));
# 1136 : 19833 : secret = childKey.key;
# 1137 : 19833 : metadata.hd_seed_id = hd_chain.seed_id;
# 1138 : 19833 : CKeyID master_id = masterKey.key.GetPubKey().GetID();
# 1139 : 19833 : std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
# 1140 : 19833 : metadata.has_key_origin = true;
# 1141 : : // update the chain model in the database
# 1142 [ + + ][ - + ]: 19833 : if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
# 1143 : 0 : throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
# 1144 : 19833 : }
# 1145 : :
# 1146 : : void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
# 1147 : 8009 : {
# 1148 : 8009 : LOCK(cs_KeyStore);
# 1149 [ - + ]: 8009 : if (keypool.m_pre_split) {
# 1150 : 0 : set_pre_split_keypool.insert(nIndex);
# 1151 [ + + ]: 8009 : } else if (keypool.fInternal) {
# 1152 : 4071 : setInternalKeyPool.insert(nIndex);
# 1153 : 4071 : } else {
# 1154 : 3938 : setExternalKeyPool.insert(nIndex);
# 1155 : 3938 : }
# 1156 : 8009 : m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
# 1157 : 8009 : m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
# 1158 : :
# 1159 : : // If no metadata exists yet, create a default with the pool key's
# 1160 : : // creation time. Note that this may be overwritten by actually
# 1161 : : // stored metadata for that key later, which is fine.
# 1162 : 8009 : CKeyID keyid = keypool.vchPubKey.GetID();
# 1163 [ + - ]: 8009 : if (mapKeyMetadata.count(keyid) == 0)
# 1164 : 8009 : mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
# 1165 : 8009 : }
# 1166 : :
# 1167 : : bool LegacyScriptPubKeyMan::CanGenerateKeys() const
# 1168 : 21320 : {
# 1169 : : // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
# 1170 : 21320 : LOCK(cs_KeyStore);
# 1171 [ + + ][ - + ]: 21320 : return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
# 1172 : 21320 : }
# 1173 : :
# 1174 : : CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
# 1175 : 248 : {
# 1176 : 248 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
# 1177 : 0 : CKey key;
# 1178 : 248 : key.MakeNewKey(true);
# 1179 : 248 : return DeriveNewSeed(key);
# 1180 : 248 : }
# 1181 : :
# 1182 : : CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
# 1183 : 254 : {
# 1184 : 254 : int64_t nCreationTime = GetTime();
# 1185 : 254 : CKeyMetadata metadata(nCreationTime);
# 1186 : :
# 1187 : : // calculate the seed
# 1188 : 254 : CPubKey seed = key.GetPubKey();
# 1189 : 254 : assert(key.VerifyPubKey(seed));
# 1190 : :
# 1191 : : // set the hd keypath to "s" -> Seed, refers the seed to itself
# 1192 : 0 : metadata.hdKeypath = "s";
# 1193 : 254 : metadata.has_key_origin = false;
# 1194 : 254 : metadata.hd_seed_id = seed.GetID();
# 1195 : :
# 1196 : 254 : {
# 1197 : 254 : LOCK(cs_KeyStore);
# 1198 : :
# 1199 : : // mem store the metadata
# 1200 : 254 : mapKeyMetadata[seed.GetID()] = metadata;
# 1201 : :
# 1202 : : // write the key&metadata to the database
# 1203 [ - + ]: 254 : if (!AddKeyPubKey(key, seed))
# 1204 : 0 : throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
# 1205 : 254 : }
# 1206 : :
# 1207 : 254 : return seed;
# 1208 : 254 : }
# 1209 : :
# 1210 : : void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
# 1211 : 254 : {
# 1212 : 254 : LOCK(cs_KeyStore);
# 1213 : : // store the keyid (hash160) together with
# 1214 : : // the child index counter in the database
# 1215 : : // as a hdchain object
# 1216 : 254 : CHDChain newHdChain;
# 1217 [ + - ]: 254 : newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
# 1218 : 254 : newHdChain.seed_id = seed.GetID();
# 1219 : 254 : AddHDChain(newHdChain);
# 1220 : 254 : NotifyCanGetAddressesChanged();
# 1221 : 254 : WalletBatch batch(m_storage.GetDatabase());
# 1222 : 254 : m_storage.UnsetBlankWalletFlag(batch);
# 1223 : 254 : }
# 1224 : :
# 1225 : : /**
# 1226 : : * Mark old keypool keys as used,
# 1227 : : * and generate all new keys
# 1228 : : */
# 1229 : : bool LegacyScriptPubKeyMan::NewKeyPool()
# 1230 : 254 : {
# 1231 [ - + ]: 254 : if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
# 1232 : 0 : return false;
# 1233 : 0 : }
# 1234 : 254 : {
# 1235 : 254 : LOCK(cs_KeyStore);
# 1236 : 254 : WalletBatch batch(m_storage.GetDatabase());
# 1237 : :
# 1238 [ + + ]: 254 : for (const int64_t nIndex : setInternalKeyPool) {
# 1239 : 203 : batch.ErasePool(nIndex);
# 1240 : 203 : }
# 1241 : 254 : setInternalKeyPool.clear();
# 1242 : :
# 1243 [ + + ]: 254 : for (const int64_t nIndex : setExternalKeyPool) {
# 1244 : 203 : batch.ErasePool(nIndex);
# 1245 : 203 : }
# 1246 : 254 : setExternalKeyPool.clear();
# 1247 : :
# 1248 [ - + ]: 254 : for (const int64_t nIndex : set_pre_split_keypool) {
# 1249 : 0 : batch.ErasePool(nIndex);
# 1250 : 0 : }
# 1251 : 254 : set_pre_split_keypool.clear();
# 1252 : :
# 1253 : 254 : m_pool_key_to_index.clear();
# 1254 : :
# 1255 [ - + ]: 254 : if (!TopUp()) {
# 1256 : 0 : return false;
# 1257 : 0 : }
# 1258 : 254 : WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
# 1259 : 254 : }
# 1260 : 0 : return true;
# 1261 : 254 : }
# 1262 : :
# 1263 : : bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
# 1264 : 12933 : {
# 1265 [ + + ]: 12933 : if (!CanGenerateKeys()) {
# 1266 : 88 : return false;
# 1267 : 88 : }
# 1268 : :
# 1269 [ + + ]: 12845 : if (!TopUpChain(m_hd_chain, kpSize)) {
# 1270 : 41 : return false;
# 1271 : 41 : }
# 1272 [ + + ]: 12804 : for (auto& [chain_id, chain] : m_inactive_hd_chains) {
# 1273 [ - + ]: 226 : if (!TopUpChain(chain, kpSize)) {
# 1274 : 0 : return false;
# 1275 : 0 : }
# 1276 : 226 : }
# 1277 : 12804 : NotifyCanGetAddressesChanged();
# 1278 : 12804 : return true;
# 1279 : 12804 : }
# 1280 : :
# 1281 : : bool LegacyScriptPubKeyMan::TopUpChain(CHDChain& chain, unsigned int kpSize)
# 1282 : 13085 : {
# 1283 : 13085 : LOCK(cs_KeyStore);
# 1284 : :
# 1285 [ + + ]: 13085 : if (m_storage.IsLocked()) return false;
# 1286 : :
# 1287 : : // Top up key pool
# 1288 : 13044 : unsigned int nTargetSize;
# 1289 [ + + ]: 13044 : if (kpSize > 0) {
# 1290 : 16 : nTargetSize = kpSize;
# 1291 : 13028 : } else {
# 1292 : 13028 : nTargetSize = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{0});
# 1293 : 13028 : }
# 1294 : 13044 : int64_t target = std::max((int64_t) nTargetSize, int64_t{1});
# 1295 : :
# 1296 : : // count amount of available keys (internal, external)
# 1297 : : // make sure the keypool of external and internal keys fits the user selected target (-keypool)
# 1298 : 13044 : int64_t missingExternal;
# 1299 : 13044 : int64_t missingInternal;
# 1300 [ + + ]: 13044 : if (chain == m_hd_chain) {
# 1301 : 12804 : missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
# 1302 : 12804 : missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
# 1303 : 12804 : } else {
# 1304 : 240 : missingExternal = std::max(target - (chain.nExternalChainCounter - chain.m_next_external_index), int64_t{0});
# 1305 : 240 : missingInternal = std::max(target - (chain.nInternalChainCounter - chain.m_next_internal_index), int64_t{0});
# 1306 : 240 : }
# 1307 : :
# 1308 [ - + ][ - + ]: 13044 : if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
# 1309 : : // don't create extra internal keys
# 1310 : 0 : missingInternal = 0;
# 1311 : 0 : }
# 1312 : 13044 : bool internal = false;
# 1313 : 13044 : WalletBatch batch(m_storage.GetDatabase());
# 1314 [ + + ]: 32877 : for (int64_t i = missingInternal + missingExternal; i--;) {
# 1315 [ + + ]: 19833 : if (i < missingInternal) {
# 1316 : 6766 : internal = true;
# 1317 : 6766 : }
# 1318 : :
# 1319 : 19833 : CPubKey pubkey(GenerateNewKey(batch, chain, internal));
# 1320 [ + + ]: 19833 : if (chain == m_hd_chain) {
# 1321 : 19614 : AddKeypoolPubkeyWithDB(pubkey, internal, batch);
# 1322 : 19614 : }
# 1323 : 19833 : }
# 1324 [ + + ]: 13044 : if (missingInternal + missingExternal > 0) {
# 1325 [ + + ]: 12128 : if (chain == m_hd_chain) {
# 1326 : 12119 : WalletLogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
# 1327 : 12119 : } else {
# 1328 : 9 : WalletLogPrintf("inactive seed with id %s added %d external keys, %d internal keys\n", HexStr(chain.seed_id), missingExternal, missingInternal);
# 1329 : 9 : }
# 1330 : 12128 : }
# 1331 : 13044 : return true;
# 1332 : 13085 : }
# 1333 : :
# 1334 : : void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
# 1335 : 19752 : {
# 1336 : 19752 : LOCK(cs_KeyStore);
# 1337 : 19752 : assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
# 1338 : 0 : int64_t index = ++m_max_keypool_index;
# 1339 [ - + ]: 19752 : if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
# 1340 : 0 : throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
# 1341 : 0 : }
# 1342 [ + + ]: 19752 : if (internal) {
# 1343 : 6772 : setInternalKeyPool.insert(index);
# 1344 : 12980 : } else {
# 1345 : 12980 : setExternalKeyPool.insert(index);
# 1346 : 12980 : }
# 1347 : 19752 : m_pool_key_to_index[pubkey.GetID()] = index;
# 1348 : 19752 : }
# 1349 : :
# 1350 : : void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
# 1351 : 12025 : {
# 1352 : 12025 : assert(type != OutputType::BECH32M);
# 1353 : : // Remove from key pool
# 1354 : 0 : WalletBatch batch(m_storage.GetDatabase());
# 1355 : 12025 : batch.ErasePool(nIndex);
# 1356 : 12025 : CPubKey pubkey;
# 1357 : 12025 : bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
# 1358 : 12025 : assert(have_pk);
# 1359 : 0 : LearnRelatedScripts(pubkey, type);
# 1360 : 12025 : m_index_to_reserved_key.erase(nIndex);
# 1361 : 12025 : WalletLogPrintf("keypool keep %d\n", nIndex);
# 1362 : 12025 : }
# 1363 : :
# 1364 : : void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
# 1365 : 71 : {
# 1366 : : // Return to key pool
# 1367 : 71 : {
# 1368 : 71 : LOCK(cs_KeyStore);
# 1369 [ + - ]: 71 : if (fInternal) {
# 1370 : 71 : setInternalKeyPool.insert(nIndex);
# 1371 [ # # ]: 71 : } else if (!set_pre_split_keypool.empty()) {
# 1372 : 0 : set_pre_split_keypool.insert(nIndex);
# 1373 : 0 : } else {
# 1374 : 0 : setExternalKeyPool.insert(nIndex);
# 1375 : 0 : }
# 1376 : 71 : CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
# 1377 : 71 : m_pool_key_to_index[pubkey_id] = nIndex;
# 1378 : 71 : m_index_to_reserved_key.erase(nIndex);
# 1379 : 71 : NotifyCanGetAddressesChanged();
# 1380 : 71 : }
# 1381 : 71 : WalletLogPrintf("keypool return %d\n", nIndex);
# 1382 : 71 : }
# 1383 : :
# 1384 : : bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type, bool internal)
# 1385 : 9112 : {
# 1386 : 9112 : assert(type != OutputType::BECH32M);
# 1387 [ + + ]: 9112 : if (!CanGetAddresses(internal)) {
# 1388 : 1 : return false;
# 1389 : 1 : }
# 1390 : :
# 1391 : 9111 : CKeyPool keypool;
# 1392 : 9111 : {
# 1393 : 9111 : LOCK(cs_KeyStore);
# 1394 : 9111 : int64_t nIndex;
# 1395 [ + + ][ + - ]: 9111 : if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
# 1396 [ + - ]: 3 : if (m_storage.IsLocked()) return false;
# 1397 : 0 : WalletBatch batch(m_storage.GetDatabase());
# 1398 : 0 : result = GenerateNewKey(batch, m_hd_chain, internal);
# 1399 : 0 : return true;
# 1400 : 3 : }
# 1401 : 9108 : KeepDestination(nIndex, type);
# 1402 : 9108 : result = keypool.vchPubKey;
# 1403 : 9108 : }
# 1404 : 0 : return true;
# 1405 : 9111 : }
# 1406 : :
# 1407 : : bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
# 1408 : 12103 : {
# 1409 : 12103 : nIndex = -1;
# 1410 : 12103 : keypool.vchPubKey = CPubKey();
# 1411 : 12103 : {
# 1412 : 12103 : LOCK(cs_KeyStore);
# 1413 : :
# 1414 : 12103 : bool fReturningInternal = fRequestedInternal;
# 1415 [ + + ][ + - ]: 12103 : fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
# [ + - ]
# 1416 : 12103 : bool use_split_keypool = set_pre_split_keypool.empty();
# 1417 [ + - ][ + + ]: 12103 : std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
# 1418 : :
# 1419 : : // Get the oldest key
# 1420 [ + + ]: 12103 : if (setKeyPool.empty()) {
# 1421 : 7 : return false;
# 1422 : 7 : }
# 1423 : :
# 1424 : 12096 : WalletBatch batch(m_storage.GetDatabase());
# 1425 : :
# 1426 : 12096 : auto it = setKeyPool.begin();
# 1427 : 12096 : nIndex = *it;
# 1428 : 12096 : setKeyPool.erase(it);
# 1429 [ - + ]: 12096 : if (!batch.ReadPool(nIndex, keypool)) {
# 1430 : 0 : throw std::runtime_error(std::string(__func__) + ": read failed");
# 1431 : 0 : }
# 1432 : 12096 : CPubKey pk;
# 1433 [ - + ]: 12096 : if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
# 1434 : 0 : throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
# 1435 : 0 : }
# 1436 : : // If the key was pre-split keypool, we don't care about what type it is
# 1437 [ + - ][ - + ]: 12096 : if (use_split_keypool && keypool.fInternal != fReturningInternal) {
# 1438 : 0 : throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
# 1439 : 0 : }
# 1440 [ - + ]: 12096 : if (!keypool.vchPubKey.IsValid()) {
# 1441 : 0 : throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
# 1442 : 0 : }
# 1443 : :
# 1444 : 12096 : assert(m_index_to_reserved_key.count(nIndex) == 0);
# 1445 : 0 : m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
# 1446 : 12096 : m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
# 1447 : 12096 : WalletLogPrintf("keypool reserve %d\n", nIndex);
# 1448 : 12096 : }
# 1449 : 0 : NotifyCanGetAddressesChanged();
# 1450 : 12096 : return true;
# 1451 : 12096 : }
# 1452 : :
# 1453 : : void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
# 1454 : 21310 : {
# 1455 : 21310 : assert(type != OutputType::BECH32M);
# 1456 [ + - ][ + + ]: 21310 : if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
# [ + + ]
# 1457 : 20417 : CTxDestination witdest = WitnessV0KeyHash(key.GetID());
# 1458 : 20417 : CScript witprog = GetScriptForDestination(witdest);
# 1459 : : // Make sure the resulting program is solvable.
# 1460 : 20417 : assert(IsSolvable(*this, witprog));
# 1461 : 0 : AddCScript(witprog);
# 1462 : 20417 : }
# 1463 : 21310 : }
# 1464 : :
# 1465 : : void LegacyScriptPubKeyMan::LearnAllRelatedScripts(const CPubKey& key)
# 1466 : 177 : {
# 1467 : : // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
# 1468 : 177 : LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
# 1469 : 177 : }
# 1470 : :
# 1471 : : std::vector<CKeyPool> LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
# 1472 : 43 : {
# 1473 : 43 : AssertLockHeld(cs_KeyStore);
# 1474 : 43 : bool internal = setInternalKeyPool.count(keypool_id);
# 1475 [ + + ]: 43 : if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
# 1476 [ + + ][ + - ]: 43 : std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
# 1477 : 43 : auto it = setKeyPool->begin();
# 1478 : :
# 1479 : 43 : std::vector<CKeyPool> result;
# 1480 : 43 : WalletBatch batch(m_storage.GetDatabase());
# 1481 [ + + ]: 220 : while (it != std::end(*setKeyPool)) {
# 1482 : 207 : const int64_t& index = *(it);
# 1483 [ + + ]: 207 : if (index > keypool_id) break; // set*KeyPool is ordered
# 1484 : :
# 1485 : 177 : CKeyPool keypool;
# 1486 [ + - ]: 177 : if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
# 1487 : 177 : m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
# 1488 : 177 : }
# 1489 : 177 : LearnAllRelatedScripts(keypool.vchPubKey);
# 1490 : 177 : batch.ErasePool(index);
# 1491 : 177 : WalletLogPrintf("keypool index %d removed\n", index);
# 1492 : 177 : it = setKeyPool->erase(it);
# 1493 : 177 : result.push_back(std::move(keypool));
# 1494 : 177 : }
# 1495 : :
# 1496 : 43 : return result;
# 1497 : 43 : }
# 1498 : :
# 1499 : : std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
# 1500 : 72478 : {
# 1501 : 72478 : std::vector<CScript> dummy;
# 1502 : 72478 : FlatSigningProvider out;
# 1503 : 72478 : InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
# 1504 : 72478 : std::vector<CKeyID> ret;
# 1505 [ + + ]: 72478 : for (const auto& entry : out.pubkeys) {
# 1506 : 68149 : ret.push_back(entry.first);
# 1507 : 68149 : }
# 1508 : 72478 : return ret;
# 1509 : 72478 : }
# 1510 : :
# 1511 : : void LegacyScriptPubKeyMan::MarkPreSplitKeys()
# 1512 : 0 : {
# 1513 : 0 : WalletBatch batch(m_storage.GetDatabase());
# 1514 [ # # ]: 0 : for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
# 1515 : 0 : int64_t index = *it;
# 1516 : 0 : CKeyPool keypool;
# 1517 [ # # ]: 0 : if (!batch.ReadPool(index, keypool)) {
# 1518 : 0 : throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
# 1519 : 0 : }
# 1520 : 0 : keypool.m_pre_split = true;
# 1521 [ # # ]: 0 : if (!batch.WritePool(index, keypool)) {
# 1522 : 0 : throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
# 1523 : 0 : }
# 1524 : 0 : set_pre_split_keypool.insert(index);
# 1525 : 0 : it = setExternalKeyPool.erase(it);
# 1526 : 0 : }
# 1527 : 0 : }
# 1528 : :
# 1529 : : bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
# 1530 : 20594 : {
# 1531 : 20594 : WalletBatch batch(m_storage.GetDatabase());
# 1532 : 20594 : return AddCScriptWithDB(batch, redeemScript);
# 1533 : 20594 : }
# 1534 : :
# 1535 : : bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
# 1536 : 20704 : {
# 1537 [ - + ]: 20704 : if (!FillableSigningProvider::AddCScript(redeemScript))
# 1538 : 0 : return false;
# 1539 [ + + ]: 20704 : if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
# 1540 : 11867 : m_storage.UnsetBlankWalletFlag(batch);
# 1541 : 11867 : return true;
# 1542 : 11867 : }
# 1543 : 8837 : return false;
# 1544 : 20704 : }
# 1545 : :
# 1546 : : bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info)
# 1547 : 163 : {
# 1548 : 163 : LOCK(cs_KeyStore);
# 1549 : 163 : std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
# 1550 : 163 : mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
# 1551 : 163 : mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
# 1552 : 163 : mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
# 1553 : 163 : return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
# 1554 : 163 : }
# 1555 : :
# 1556 : : bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
# 1557 : 1266 : {
# 1558 : 1266 : WalletBatch batch(m_storage.GetDatabase());
# 1559 [ + + ]: 1266 : for (const auto& entry : scripts) {
# 1560 : 1169 : CScriptID id(entry);
# 1561 [ + + ]: 1169 : if (HaveCScript(id)) {
# 1562 : 1059 : WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
# 1563 : 1059 : continue;
# 1564 : 1059 : }
# 1565 [ - + ]: 110 : if (!AddCScriptWithDB(batch, entry)) {
# 1566 : 0 : return false;
# 1567 : 0 : }
# 1568 : :
# 1569 [ + + ]: 110 : if (timestamp > 0) {
# 1570 : 74 : m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
# 1571 : 74 : }
# 1572 : 110 : }
# 1573 [ + + ]: 1266 : if (timestamp > 0) {
# 1574 : 171 : UpdateTimeFirstKey(timestamp);
# 1575 : 171 : }
# 1576 : :
# 1577 : 1266 : return true;
# 1578 : 1266 : }
# 1579 : :
# 1580 : : bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
# 1581 : 1224 : {
# 1582 : 1224 : WalletBatch batch(m_storage.GetDatabase());
# 1583 [ + + ]: 1224 : for (const auto& entry : privkey_map) {
# 1584 : 1116 : const CKey& key = entry.second;
# 1585 : 1116 : CPubKey pubkey = key.GetPubKey();
# 1586 : 1116 : const CKeyID& id = entry.first;
# 1587 : 1116 : assert(key.VerifyPubKey(pubkey));
# 1588 : : // Skip if we already have the key
# 1589 [ + + ]: 1116 : if (HaveKey(id)) {
# 1590 : 3 : WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
# 1591 : 3 : continue;
# 1592 : 3 : }
# 1593 : 1113 : mapKeyMetadata[id].nCreateTime = timestamp;
# 1594 : : // If the private key is not present in the wallet, insert it.
# 1595 [ - + ]: 1113 : if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
# 1596 : 0 : return false;
# 1597 : 0 : }
# 1598 : 1113 : UpdateTimeFirstKey(timestamp);
# 1599 : 1113 : }
# 1600 : 1224 : return true;
# 1601 : 1224 : }
# 1602 : :
# 1603 : : bool LegacyScriptPubKeyMan::ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp)
# 1604 : 203 : {
# 1605 : 203 : WalletBatch batch(m_storage.GetDatabase());
# 1606 [ + + ]: 203 : for (const auto& entry : key_origins) {
# 1607 : 163 : AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
# 1608 : 163 : }
# 1609 [ + + ]: 231 : for (const CKeyID& id : ordered_pubkeys) {
# 1610 : 231 : auto entry = pubkey_map.find(id);
# 1611 [ + + ]: 231 : if (entry == pubkey_map.end()) {
# 1612 : 2 : continue;
# 1613 : 2 : }
# 1614 : 229 : const CPubKey& pubkey = entry->second;
# 1615 : 229 : CPubKey temp;
# 1616 [ + + ]: 229 : if (GetPubKey(id, temp)) {
# 1617 : : // Already have pubkey, skipping
# 1618 : 12 : WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
# 1619 : 12 : continue;
# 1620 : 12 : }
# 1621 [ - + ]: 217 : if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
# 1622 : 0 : return false;
# 1623 : 0 : }
# 1624 : 217 : mapKeyMetadata[id].nCreateTime = timestamp;
# 1625 : :
# 1626 : : // Add to keypool only works with pubkeys
# 1627 [ + + ]: 217 : if (add_keypool) {
# 1628 : 138 : AddKeypoolPubkeyWithDB(pubkey, internal, batch);
# 1629 : 138 : NotifyCanGetAddressesChanged();
# 1630 : 138 : }
# 1631 : 217 : }
# 1632 : 203 : return true;
# 1633 : 203 : }
# 1634 : :
# 1635 : : bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
# 1636 : 288 : {
# 1637 : 288 : WalletBatch batch(m_storage.GetDatabase());
# 1638 [ + + ]: 516 : for (const CScript& script : script_pub_keys) {
# 1639 [ + + ][ + + ]: 516 : if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
# 1640 [ - + ]: 458 : if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
# 1641 : 0 : return false;
# 1642 : 0 : }
# 1643 : 458 : }
# 1644 : 516 : }
# 1645 : 288 : return true;
# 1646 : 288 : }
# 1647 : :
# 1648 : : std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
# 1649 : 7 : {
# 1650 : 7 : LOCK(cs_KeyStore);
# 1651 [ + + ]: 7 : if (!m_storage.HasEncryptionKeys()) {
# 1652 : 6 : return FillableSigningProvider::GetKeys();
# 1653 : 6 : }
# 1654 : 1 : std::set<CKeyID> set_address;
# 1655 [ + + ]: 392 : for (const auto& mi : mapCryptedKeys) {
# 1656 : 392 : set_address.insert(mi.first);
# 1657 : 392 : }
# 1658 : 1 : return set_address;
# 1659 : 7 : }
# 1660 : :
# 1661 : : bool DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, bilingual_str& error)
# 1662 : 6184 : {
# 1663 : : // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
# 1664 [ - + ]: 6184 : if (!CanGetAddresses()) {
# 1665 : 0 : error = _("No addresses available");
# 1666 : 0 : return false;
# 1667 : 0 : }
# 1668 : 6184 : {
# 1669 : 6184 : LOCK(cs_desc_man);
# 1670 : 6184 : assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
# 1671 : 0 : std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
# 1672 : 6184 : assert(desc_addr_type);
# 1673 [ - + ]: 6184 : if (type != *desc_addr_type) {
# 1674 : 0 : throw std::runtime_error(std::string(__func__) + ": Types are inconsistent");
# 1675 : 0 : }
# 1676 : :
# 1677 : 6184 : TopUp();
# 1678 : :
# 1679 : : // Get the scriptPubKey from the descriptor
# 1680 : 6184 : FlatSigningProvider out_keys;
# 1681 : 6184 : std::vector<CScript> scripts_temp;
# 1682 [ - + ][ # # ]: 6184 : if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
# 1683 : : // We can't generate anymore keys
# 1684 : 0 : error = _("Error: Keypool ran out, please call keypoolrefill first");
# 1685 : 0 : return false;
# 1686 : 0 : }
# 1687 [ + + ]: 6184 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
# 1688 : : // We can't generate anymore keys
# 1689 : 8 : error = _("Error: Keypool ran out, please call keypoolrefill first");
# 1690 : 8 : return false;
# 1691 : 8 : }
# 1692 : :
# 1693 : 6176 : std::optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
# 1694 [ + - ][ + - ]: 6176 : if (out_script_type && out_script_type == type) {
# 1695 : 6176 : ExtractDestination(scripts_temp[0], dest);
# 1696 : 6176 : } else {
# 1697 : 0 : throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
# 1698 : 0 : }
# 1699 : 6176 : m_wallet_descriptor.next_index++;
# 1700 : 6176 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
# 1701 : 6176 : return true;
# 1702 : 6176 : }
# 1703 : 6176 : }
# 1704 : :
# 1705 : : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
# 1706 : 9329383 : {
# 1707 : 9329383 : LOCK(cs_desc_man);
# 1708 [ + + ]: 9329383 : if (m_map_script_pub_keys.count(script) > 0) {
# 1709 : 561995 : return ISMINE_SPENDABLE;
# 1710 : 561995 : }
# 1711 : 8767388 : return ISMINE_NO;
# 1712 : 9329383 : }
# 1713 : :
# 1714 : : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
# 1715 : 693 : {
# 1716 : 693 : LOCK(cs_desc_man);
# 1717 [ - + ]: 693 : if (!m_map_keys.empty()) {
# 1718 : 0 : return false;
# 1719 : 0 : }
# 1720 : :
# 1721 : 693 : bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
# 1722 : 693 : bool keyFail = false;
# 1723 [ + + ]: 693 : for (const auto& mi : m_map_crypted_keys) {
# 1724 : 597 : const CPubKey &pubkey = mi.second.first;
# 1725 : 597 : const std::vector<unsigned char> &crypted_secret = mi.second.second;
# 1726 : 597 : CKey key;
# 1727 [ - + ]: 597 : if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
# 1728 : 0 : keyFail = true;
# 1729 : 0 : break;
# 1730 : 0 : }
# 1731 : 597 : keyPass = true;
# 1732 [ + + ]: 597 : if (m_decryption_thoroughly_checked)
# 1733 : 433 : break;
# 1734 : 597 : }
# 1735 [ + - ][ - + ]: 693 : if (keyPass && keyFail) {
# 1736 : 0 : LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
# 1737 : 0 : throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
# 1738 : 0 : }
# 1739 [ - + ][ - + ]: 693 : if (keyFail || (!keyPass && !accept_no_keys)) {
# [ # # ]
# 1740 : 0 : return false;
# 1741 : 0 : }
# 1742 : 693 : m_decryption_thoroughly_checked = true;
# 1743 : 693 : return true;
# 1744 : 693 : }
# 1745 : :
# 1746 : : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
# 1747 : 88 : {
# 1748 : 88 : LOCK(cs_desc_man);
# 1749 [ - + ]: 88 : if (!m_map_crypted_keys.empty()) {
# 1750 : 0 : return false;
# 1751 : 0 : }
# 1752 : :
# 1753 [ + + ]: 88 : for (const KeyMap::value_type& key_in : m_map_keys)
# 1754 : 88 : {
# 1755 : 88 : const CKey &key = key_in.second;
# 1756 : 88 : CPubKey pubkey = key.GetPubKey();
# 1757 : 88 : CKeyingMaterial secret(key.begin(), key.end());
# 1758 : 88 : std::vector<unsigned char> crypted_secret;
# 1759 [ - + ]: 88 : if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
# 1760 : 0 : return false;
# 1761 : 0 : }
# 1762 : 88 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
# 1763 : 88 : batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
# 1764 : 88 : }
# 1765 : 88 : m_map_keys.clear();
# 1766 : 88 : return true;
# 1767 : 88 : }
# 1768 : :
# 1769 : : bool DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool, bilingual_str& error)
# 1770 : 2327 : {
# 1771 : 2327 : LOCK(cs_desc_man);
# 1772 : 2327 : bool result = GetNewDestination(type, address, error);
# 1773 : 2327 : index = m_wallet_descriptor.next_index - 1;
# 1774 : 2327 : return result;
# 1775 : 2327 : }
# 1776 : :
# 1777 : : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
# 1778 : 62 : {
# 1779 : 62 : LOCK(cs_desc_man);
# 1780 : : // Only return when the index was the most recent
# 1781 [ + - ]: 62 : if (m_wallet_descriptor.next_index - 1 == index) {
# 1782 : 62 : m_wallet_descriptor.next_index--;
# 1783 : 62 : }
# 1784 : 62 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
# 1785 : 62 : NotifyCanGetAddressesChanged();
# 1786 : 62 : }
# 1787 : :
# 1788 : : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
# 1789 : 54670 : {
# 1790 : 54670 : AssertLockHeld(cs_desc_man);
# 1791 [ + + ][ + + ]: 54670 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
# 1792 : 2277 : KeyMap keys;
# 1793 [ + + ]: 2277 : for (auto key_pair : m_map_crypted_keys) {
# 1794 : 2277 : const CPubKey& pubkey = key_pair.second.first;
# 1795 : 2277 : const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
# 1796 : 2277 : CKey key;
# 1797 : 2277 : DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey, key);
# 1798 : 2277 : keys[pubkey.GetID()] = key;
# 1799 : 2277 : }
# 1800 : 2277 : return keys;
# 1801 : 2277 : }
# 1802 : 52393 : return m_map_keys;
# 1803 : 54670 : }
# 1804 : :
# 1805 : : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
# 1806 : 46909 : {
# 1807 : 46909 : LOCK(cs_desc_man);
# 1808 : 46909 : unsigned int target_size;
# 1809 [ + + ]: 46909 : if (size > 0) {
# 1810 : 48 : target_size = size;
# 1811 : 46861 : } else {
# 1812 : 46861 : target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
# 1813 : 46861 : }
# 1814 : :
# 1815 : : // Calculate the new range_end
# 1816 : 46909 : int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
# 1817 : :
# 1818 : : // If the descriptor is not ranged, we actually just want to fill the first cache item
# 1819 [ + + ]: 46909 : if (!m_wallet_descriptor.descriptor->IsRange()) {
# 1820 : 6570 : new_range_end = 1;
# 1821 : 6570 : m_wallet_descriptor.range_end = 1;
# 1822 : 6570 : m_wallet_descriptor.range_start = 0;
# 1823 : 6570 : }
# 1824 : :
# 1825 : 46909 : FlatSigningProvider provider;
# 1826 : 46909 : provider.keys = GetKeys();
# 1827 : :
# 1828 : 46909 : WalletBatch batch(m_storage.GetDatabase());
# 1829 : 46909 : uint256 id = GetID();
# 1830 [ + + ]: 218149 : for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
# 1831 : 171454 : FlatSigningProvider out_keys;
# 1832 : 171454 : std::vector<CScript> scripts_temp;
# 1833 : 171454 : DescriptorCache temp_cache;
# 1834 : : // Maybe we have a cached xpub and we can expand from the cache first
# 1835 [ + + ]: 171454 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
# 1836 [ + + ]: 3674 : if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
# 1837 : 3674 : }
# 1838 : : // Add all of the scriptPubKeys to the scriptPubKey set
# 1839 [ + + ]: 171594 : for (const CScript& script : scripts_temp) {
# 1840 : 171594 : m_map_script_pub_keys[script] = i;
# 1841 : 171594 : }
# 1842 [ + + ]: 171240 : for (const auto& pk_pair : out_keys.pubkeys) {
# 1843 : 155424 : const CPubKey& pubkey = pk_pair.second;
# 1844 [ + + ]: 155424 : if (m_map_pubkeys.count(pubkey) != 0) {
# 1845 : : // We don't need to give an error here.
# 1846 : : // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
# 1847 : 5502 : continue;
# 1848 : 5502 : }
# 1849 : 149922 : m_map_pubkeys[pubkey] = i;
# 1850 : 149922 : }
# 1851 : : // Merge and write the cache
# 1852 : 171240 : DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
# 1853 [ - + ]: 171240 : if (!batch.WriteDescriptorCacheItems(id, new_items)) {
# 1854 : 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
# 1855 : 0 : }
# 1856 : 171240 : m_max_cached_index++;
# 1857 : 171240 : }
# 1858 : 46695 : m_wallet_descriptor.range_end = new_range_end;
# 1859 : 46695 : batch.WriteDescriptor(GetID(), m_wallet_descriptor);
# 1860 : :
# 1861 : : // By this point, the cache size should be the size of the entire range
# 1862 : 46695 : assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
# 1863 : :
# 1864 : 0 : NotifyCanGetAddressesChanged();
# 1865 : 46695 : return true;
# 1866 : 46909 : }
# 1867 : :
# 1868 : : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
# 1869 : 30470 : {
# 1870 : 30470 : LOCK(cs_desc_man);
# 1871 : 30470 : std::vector<WalletDestination> result;
# 1872 [ + - ]: 30470 : if (IsMine(script)) {
# 1873 : 30470 : int32_t index = m_map_script_pub_keys[script];
# 1874 [ + + ]: 30470 : if (index >= m_wallet_descriptor.next_index) {
# 1875 : 300 : WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
# 1876 : 300 : auto out_keys = std::make_unique<FlatSigningProvider>();
# 1877 : 300 : std::vector<CScript> scripts_temp;
# 1878 [ + + ]: 738 : while (index >= m_wallet_descriptor.next_index) {
# 1879 [ - + ]: 438 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
# 1880 : 0 : throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
# 1881 : 0 : }
# 1882 : 438 : CTxDestination dest;
# 1883 : 438 : ExtractDestination(scripts_temp[0], dest);
# 1884 : 438 : result.push_back({dest, std::nullopt});
# 1885 : 438 : m_wallet_descriptor.next_index++;
# 1886 : 438 : }
# 1887 : 300 : }
# 1888 [ - + ]: 30470 : if (!TopUp()) {
# 1889 : 0 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
# 1890 : 0 : }
# 1891 : 30470 : }
# 1892 : :
# 1893 : 30470 : return result;
# 1894 : 30470 : }
# 1895 : :
# 1896 : : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
# 1897 : 293 : {
# 1898 : 293 : LOCK(cs_desc_man);
# 1899 : 293 : WalletBatch batch(m_storage.GetDatabase());
# 1900 [ - + ]: 293 : if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
# 1901 : 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
# 1902 : 0 : }
# 1903 : 293 : }
# 1904 : :
# 1905 : : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
# 1906 : 1637 : {
# 1907 : 1637 : AssertLockHeld(cs_desc_man);
# 1908 : 1637 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
# 1909 : :
# 1910 : : // Check if provided key already exists
# 1911 [ + + ][ + + ]: 1637 : if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
# 1912 [ - + ]: 1637 : m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
# 1913 : 7 : return true;
# 1914 : 7 : }
# 1915 : :
# 1916 [ + + ]: 1630 : if (m_storage.HasEncryptionKeys()) {
# 1917 [ - + ]: 108 : if (m_storage.IsLocked()) {
# 1918 : 0 : return false;
# 1919 : 0 : }
# 1920 : :
# 1921 : 108 : std::vector<unsigned char> crypted_secret;
# 1922 : 108 : CKeyingMaterial secret(key.begin(), key.end());
# 1923 [ - + ]: 108 : if (!EncryptSecret(m_storage.GetEncryptionKey(), secret, pubkey.GetHash(), crypted_secret)) {
# 1924 : 0 : return false;
# 1925 : 0 : }
# 1926 : :
# 1927 : 108 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
# 1928 : 108 : return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
# 1929 : 1522 : } else {
# 1930 : 1522 : m_map_keys[pubkey.GetID()] = key;
# 1931 : 1522 : return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
# 1932 : 1522 : }
# 1933 : 1630 : }
# 1934 : :
# 1935 : : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(const CExtKey& master_key, OutputType addr_type, bool internal)
# 1936 : 1344 : {
# 1937 : 1344 : LOCK(cs_desc_man);
# 1938 : 1344 : assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
# 1939 : :
# 1940 : : // Ignore when there is already a descriptor
# 1941 [ - + ]: 1344 : if (m_wallet_descriptor.descriptor) {
# 1942 : 0 : return false;
# 1943 : 0 : }
# 1944 : :
# 1945 : 1344 : int64_t creation_time = GetTime();
# 1946 : :
# 1947 : 1344 : std::string xpub = EncodeExtPubKey(master_key.Neuter());
# 1948 : :
# 1949 : : // Build descriptor string
# 1950 : 1344 : std::string desc_prefix;
# 1951 : 1344 : std::string desc_suffix = "/*)";
# 1952 [ - + ]: 1344 : switch (addr_type) {
# 1953 [ + + ]: 336 : case OutputType::LEGACY: {
# 1954 : 336 : desc_prefix = "pkh(" + xpub + "/44'";
# 1955 : 336 : break;
# 1956 : 0 : }
# 1957 [ + + ]: 336 : case OutputType::P2SH_SEGWIT: {
# 1958 : 336 : desc_prefix = "sh(wpkh(" + xpub + "/49'";
# 1959 : 336 : desc_suffix += ")";
# 1960 : 336 : break;
# 1961 : 0 : }
# 1962 [ + + ]: 336 : case OutputType::BECH32: {
# 1963 : 336 : desc_prefix = "wpkh(" + xpub + "/84'";
# 1964 : 336 : break;
# 1965 : 0 : }
# 1966 [ + + ]: 336 : case OutputType::BECH32M: {
# 1967 : 336 : desc_prefix = "tr(" + xpub + "/86'";
# 1968 : 336 : break;
# 1969 : 0 : }
# 1970 : 1344 : } // no default case, so the compiler can warn about missing cases
# 1971 : 1344 : assert(!desc_prefix.empty());
# 1972 : :
# 1973 : : // Mainnet derives at 0', testnet and regtest derive at 1'
# 1974 [ + + ]: 1344 : if (Params().IsTestChain()) {
# 1975 : 1296 : desc_prefix += "/1'";
# 1976 : 1296 : } else {
# 1977 : 48 : desc_prefix += "/0'";
# 1978 : 48 : }
# 1979 : :
# 1980 [ + + ]: 1344 : std::string internal_path = internal ? "/1" : "/0";
# 1981 : 1344 : std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
# 1982 : :
# 1983 : : // Make the descriptor
# 1984 : 1344 : FlatSigningProvider keys;
# 1985 : 1344 : std::string error;
# 1986 : 1344 : std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
# 1987 : 1344 : WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
# 1988 : 1344 : m_wallet_descriptor = w_desc;
# 1989 : :
# 1990 : : // Store the master private key, and descriptor
# 1991 : 1344 : WalletBatch batch(m_storage.GetDatabase());
# 1992 [ - + ]: 1344 : if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
# 1993 : 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
# 1994 : 0 : }
# 1995 [ - + ]: 1344 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
# 1996 : 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
# 1997 : 0 : }
# 1998 : :
# 1999 : : // TopUp
# 2000 : 1344 : TopUp();
# 2001 : :
# 2002 : 1344 : m_storage.UnsetBlankWalletFlag(batch);
# 2003 : 1344 : return true;
# 2004 : 1344 : }
# 2005 : :
# 2006 : : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
# 2007 : 24 : {
# 2008 : 24 : LOCK(cs_desc_man);
# 2009 : 24 : return m_wallet_descriptor.descriptor->IsRange();
# 2010 : 24 : }
# 2011 : :
# 2012 : : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
# 2013 : 10221 : {
# 2014 : : // We can only give out addresses from descriptors that are single type (not combo), ranged,
# 2015 : : // and either have cached keys or can generate more keys (ignoring encryption)
# 2016 : 10221 : LOCK(cs_desc_man);
# 2017 [ + - ]: 10221 : return m_wallet_descriptor.descriptor->IsSingleType() &&
# 2018 [ + - ]: 10221 : m_wallet_descriptor.descriptor->IsRange() &&
# 2019 [ + + ][ + - ]: 10221 : (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
# 2020 : 10221 : }
# 2021 : :
# 2022 : : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
# 2023 : 270783 : {
# 2024 : 270783 : LOCK(cs_desc_man);
# 2025 [ + + ][ + + ]: 270783 : return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
# 2026 : 270783 : }
# 2027 : :
# 2028 : : std::optional<int64_t> DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
# 2029 : 2598 : {
# 2030 : : // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
# 2031 : 2598 : return std::nullopt;
# 2032 : 2598 : }
# 2033 : :
# 2034 : :
# 2035 : : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
# 2036 : 5494 : {
# 2037 : 5494 : LOCK(cs_desc_man);
# 2038 : 5494 : return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
# 2039 : 5494 : }
# 2040 : :
# 2041 : : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
# 2042 : 232 : {
# 2043 : 232 : LOCK(cs_desc_man);
# 2044 : 232 : return m_wallet_descriptor.creation_time;
# 2045 : 232 : }
# 2046 : :
# 2047 : : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
# 2048 : 324324 : {
# 2049 : 324324 : LOCK(cs_desc_man);
# 2050 : :
# 2051 : : // Find the index of the script
# 2052 : 324324 : auto it = m_map_script_pub_keys.find(script);
# 2053 [ + + ]: 324324 : if (it == m_map_script_pub_keys.end()) {
# 2054 : 63942 : return nullptr;
# 2055 : 63942 : }
# 2056 : 260382 : int32_t index = it->second;
# 2057 : :
# 2058 : 260382 : return GetSigningProvider(index, include_private);
# 2059 : 324324 : }
# 2060 : :
# 2061 : : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
# 2062 : 3146 : {
# 2063 : 3146 : LOCK(cs_desc_man);
# 2064 : :
# 2065 : : // Find index of the pubkey
# 2066 : 3146 : auto it = m_map_pubkeys.find(pubkey);
# 2067 [ + + ]: 3146 : if (it == m_map_pubkeys.end()) {
# 2068 : 2972 : return nullptr;
# 2069 : 2972 : }
# 2070 : 174 : int32_t index = it->second;
# 2071 : :
# 2072 : : // Always try to get the signing provider with private keys. This function should only be called during signing anyways
# 2073 : 174 : return GetSigningProvider(index, true);
# 2074 : 3146 : }
# 2075 : :
# 2076 : : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
# 2077 : 260556 : {
# 2078 : 260556 : AssertLockHeld(cs_desc_man);
# 2079 : : // Get the scripts, keys, and key origins for this script
# 2080 : 260556 : std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
# 2081 : 260556 : std::vector<CScript> scripts_temp;
# 2082 [ - + ]: 260556 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
# 2083 : :
# 2084 [ + + ][ + + ]: 260556 : if (HavePrivateKeys() && include_private) {
# 2085 : 7266 : FlatSigningProvider master_provider;
# 2086 : 7266 : master_provider.keys = GetKeys();
# 2087 : 7266 : m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
# 2088 : 7266 : }
# 2089 : :
# 2090 : 260556 : return out_keys;
# 2091 : 260556 : }
# 2092 : :
# 2093 : : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
# 2094 : 260140 : {
# 2095 : 260140 : return GetSigningProvider(script, false);
# 2096 : 260140 : }
# 2097 : :
# 2098 : : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
# 2099 : 3062279 : {
# 2100 : 3062279 : return IsMine(script);
# 2101 : 3062279 : }
# 2102 : :
# 2103 : : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
# 2104 : 14174 : {
# 2105 : 14174 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
# 2106 [ + + ]: 57878 : for (const auto& coin_pair : coins) {
# 2107 : 57878 : std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
# 2108 [ + + ]: 57878 : if (!coin_keys) {
# 2109 : 50874 : continue;
# 2110 : 50874 : }
# 2111 : 7004 : *keys = Merge(*keys, *coin_keys);
# 2112 : 7004 : }
# 2113 : :
# 2114 : 14174 : return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
# 2115 : 14174 : }
# 2116 : :
# 2117 : : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
# 2118 : 5 : {
# 2119 : 5 : std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
# 2120 [ - + ]: 5 : if (!keys) {
# 2121 : 0 : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
# 2122 : 0 : }
# 2123 : :
# 2124 : 5 : CKey key;
# 2125 [ - + ]: 5 : if (!keys->GetKey(ToKeyID(pkhash), key)) {
# 2126 : 0 : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
# 2127 : 0 : }
# 2128 : :
# 2129 [ - + ]: 5 : if (!MessageSign(key, message, str_sig)) {
# 2130 : 0 : return SigningResult::SIGNING_FAILED;
# 2131 : 0 : }
# 2132 : 5 : return SigningResult::OK;
# 2133 : 5 : }
# 2134 : :
# 2135 : : TransactionError DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
# 2136 : 4412 : {
# 2137 [ + - ]: 4412 : if (n_signed) {
# 2138 : 4412 : *n_signed = 0;
# 2139 : 4412 : }
# 2140 [ + + ]: 12545 : for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
# 2141 : 8135 : const CTxIn& txin = psbtx.tx->vin[i];
# 2142 : 8135 : PSBTInput& input = psbtx.inputs.at(i);
# 2143 : :
# 2144 [ + + ]: 8135 : if (PSBTInputSigned(input)) {
# 2145 : 2029 : continue;
# 2146 : 2029 : }
# 2147 : :
# 2148 : : // Get the Sighash type
# 2149 [ + + ][ + + ]: 6106 : if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
# [ - + ]
# 2150 : 0 : return TransactionError::SIGHASH_MISMATCH;
# 2151 : 0 : }
# 2152 : :
# 2153 : : // Get the scriptPubKey to know which SigningProvider to use
# 2154 : 6106 : CScript script;
# 2155 [ + + ]: 6106 : if (!input.witness_utxo.IsNull()) {
# 2156 : 4064 : script = input.witness_utxo.scriptPubKey;
# 2157 [ + + ]: 4064 : } else if (input.non_witness_utxo) {
# 2158 [ + + ]: 1827 : if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
# 2159 : 2 : return TransactionError::MISSING_INPUTS;
# 2160 : 2 : }
# 2161 : 1825 : script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
# 2162 : 1825 : } else {
# 2163 : : // There's no UTXO so we can just skip this now
# 2164 : 215 : continue;
# 2165 : 215 : }
# 2166 : 5889 : SignatureData sigdata;
# 2167 : 5889 : input.FillSignatureData(sigdata);
# 2168 : :
# 2169 : 5889 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
# 2170 : 5889 : std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, sign);
# 2171 [ + + ]: 5889 : if (script_keys) {
# 2172 : 525 : *keys = Merge(*keys, *script_keys);
# 2173 : 5364 : } else {
# 2174 : : // Maybe there are pubkeys listed that we can sign for
# 2175 : 5364 : script_keys = std::make_unique<FlatSigningProvider>();
# 2176 [ + + ]: 5364 : for (const auto& pk_pair : input.hd_keypaths) {
# 2177 : 3146 : const CPubKey& pubkey = pk_pair.first;
# 2178 : 3146 : std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
# 2179 [ + + ]: 3146 : if (pk_keys) {
# 2180 : 174 : *keys = Merge(*keys, *pk_keys);
# 2181 : 174 : }
# 2182 : 3146 : }
# 2183 : 5364 : }
# 2184 : :
# 2185 : 5889 : SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
# 2186 : :
# 2187 : 5889 : bool signed_one = PSBTInputSigned(input);
# 2188 [ + - ][ + + ]: 5889 : if (n_signed && (signed_one || !sign)) {
# [ + + ]
# 2189 : : // If sign is false, we assume that we _could_ sign if we get here. This
# 2190 : : // will never have false negatives; it is hard to tell under what i
# 2191 : : // circumstances it could have false positives.
# 2192 : 4429 : (*n_signed)++;
# 2193 : 4429 : }
# 2194 : 5889 : }
# 2195 : :
# 2196 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
# 2197 [ + + ]: 12442 : for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
# 2198 : 8032 : std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
# 2199 [ + + ]: 8032 : if (!keys) {
# 2200 : 7704 : continue;
# 2201 : 7704 : }
# 2202 : 328 : UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs), psbtx, i);
# 2203 : 328 : }
# 2204 : :
# 2205 : 4410 : return TransactionError::OK;
# 2206 : 4412 : }
# 2207 : :
# 2208 : : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
# 2209 : 412 : {
# 2210 : 412 : std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
# 2211 [ + - ]: 412 : if (provider) {
# 2212 : 412 : KeyOriginInfo orig;
# 2213 : 412 : CKeyID key_id = GetKeyForDestination(*provider, dest);
# 2214 [ + + ]: 412 : if (provider->GetKeyOrigin(key_id, orig)) {
# 2215 : 328 : LOCK(cs_desc_man);
# 2216 : 328 : std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
# 2217 : 328 : meta->key_origin = orig;
# 2218 : 328 : meta->has_key_origin = true;
# 2219 : 328 : meta->nCreateTime = m_wallet_descriptor.creation_time;
# 2220 : 328 : return meta;
# 2221 : 328 : }
# 2222 : 412 : }
# 2223 : 84 : return nullptr;
# 2224 : 412 : }
# 2225 : :
# 2226 : : uint256 DescriptorScriptPubKeyMan::GetID() const
# 2227 : 105415 : {
# 2228 : 105415 : LOCK(cs_desc_man);
# 2229 : 105415 : std::string desc_str = m_wallet_descriptor.descriptor->ToString();
# 2230 : 105415 : uint256 id;
# 2231 : 105415 : CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
# 2232 : 105415 : return id;
# 2233 : 105415 : }
# 2234 : :
# 2235 : : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
# 2236 : 1077 : {
# 2237 : 1077 : LOCK(cs_desc_man);
# 2238 : 1077 : m_wallet_descriptor.cache = cache;
# 2239 [ + + ]: 52432 : for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
# 2240 : 51355 : FlatSigningProvider out_keys;
# 2241 : 51355 : std::vector<CScript> scripts_temp;
# 2242 [ - + ]: 51355 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
# 2243 : 0 : throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
# 2244 : 0 : }
# 2245 : : // Add all of the scriptPubKeys to the scriptPubKey set
# 2246 [ + + ]: 51553 : for (const CScript& script : scripts_temp) {
# 2247 [ - + ]: 51553 : if (m_map_script_pub_keys.count(script) != 0) {
# 2248 : 0 : throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
# 2249 : 0 : }
# 2250 : 51553 : m_map_script_pub_keys[script] = i;
# 2251 : 51553 : }
# 2252 [ + + ]: 51355 : for (const auto& pk_pair : out_keys.pubkeys) {
# 2253 : 49351 : const CPubKey& pubkey = pk_pair.second;
# 2254 [ - + ]: 49351 : if (m_map_pubkeys.count(pubkey) != 0) {
# 2255 : : // We don't need to give an error here.
# 2256 : : // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
# 2257 : 0 : continue;
# 2258 : 0 : }
# 2259 : 49351 : m_map_pubkeys[pubkey] = i;
# 2260 : 49351 : }
# 2261 : 51355 : m_max_cached_index++;
# 2262 : 51355 : }
# 2263 : 1077 : }
# 2264 : :
# 2265 : : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
# 2266 : 907 : {
# 2267 : 907 : LOCK(cs_desc_man);
# 2268 : 907 : m_map_keys[key_id] = key;
# 2269 : 907 : return true;
# 2270 : 907 : }
# 2271 : :
# 2272 : : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
# 2273 : 151 : {
# 2274 : 151 : LOCK(cs_desc_man);
# 2275 [ - + ]: 151 : if (!m_map_keys.empty()) {
# 2276 : 0 : return false;
# 2277 : 0 : }
# 2278 : :
# 2279 : 151 : m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
# 2280 : 151 : return true;
# 2281 : 151 : }
# 2282 : :
# 2283 : : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
# 2284 : 6965 : {
# 2285 : 6965 : LOCK(cs_desc_man);
# 2286 [ + - ][ + - ]: 6965 : return m_wallet_descriptor.descriptor != nullptr && desc.descriptor != nullptr && m_wallet_descriptor.descriptor->ToString() == desc.descriptor->ToString();
# [ + + ]
# 2287 : 6965 : }
# 2288 : :
# 2289 : : void DescriptorScriptPubKeyMan::WriteDescriptor()
# 2290 : 410 : {
# 2291 : 410 : LOCK(cs_desc_man);
# 2292 : 410 : WalletBatch batch(m_storage.GetDatabase());
# 2293 [ - + ]: 410 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
# 2294 : 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
# 2295 : 0 : }
# 2296 : 410 : }
# 2297 : :
# 2298 : : const WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
# 2299 : 272 : {
# 2300 : 272 : return m_wallet_descriptor;
# 2301 : 272 : }
# 2302 : :
# 2303 : : const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
# 2304 : 163 : {
# 2305 : 163 : LOCK(cs_desc_man);
# 2306 : 163 : std::vector<CScript> script_pub_keys;
# 2307 : 163 : script_pub_keys.reserve(m_map_script_pub_keys.size());
# 2308 : :
# 2309 [ + + ]: 517 : for (auto const& script_pub_key: m_map_script_pub_keys) {
# 2310 : 517 : script_pub_keys.push_back(script_pub_key.first);
# 2311 : 517 : }
# 2312 : 163 : return script_pub_keys;
# 2313 : 163 : }
# 2314 : :
# 2315 : : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
# 2316 : 451 : {
# 2317 : 451 : LOCK(cs_desc_man);
# 2318 : :
# 2319 : 451 : FlatSigningProvider provider;
# 2320 : 451 : provider.keys = GetKeys();
# 2321 : :
# 2322 [ + + ]: 451 : if (priv) {
# 2323 : : // For the private version, always return the master key to avoid
# 2324 : : // exposing child private keys. The risk implications of exposing child
# 2325 : : // private keys together with the parent xpub may be non-obvious for users.
# 2326 : 3 : return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
# 2327 : 3 : }
# 2328 : :
# 2329 : 448 : return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
# 2330 : 451 : }
# 2331 : :
# 2332 : : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
# 2333 : 525 : {
# 2334 : 525 : LOCK(cs_desc_man);
# 2335 [ - + ][ - + ]: 525 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
# 2336 : 0 : return;
# 2337 : 0 : }
# 2338 : :
# 2339 : : // Skip if we have the last hardened xpub cache
# 2340 [ + + ]: 525 : if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
# 2341 : 481 : return;
# 2342 : 481 : }
# 2343 : :
# 2344 : : // Expand the descriptor
# 2345 : 44 : FlatSigningProvider provider;
# 2346 : 44 : provider.keys = GetKeys();
# 2347 : 44 : FlatSigningProvider out_keys;
# 2348 : 44 : std::vector<CScript> scripts_temp;
# 2349 : 44 : DescriptorCache temp_cache;
# 2350 [ - + ]: 44 : if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
# 2351 : 0 : throw std::runtime_error("Unable to expand descriptor");
# 2352 : 0 : }
# 2353 : :
# 2354 : : // Cache the last hardened xpubs
# 2355 : 44 : DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
# 2356 [ - + ]: 44 : if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
# 2357 : 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
# 2358 : 0 : }
# 2359 : 44 : }
# 2360 : :
# 2361 : : void DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
# 2362 : 15 : {
# 2363 : 15 : LOCK(cs_desc_man);
# 2364 : 15 : std::string error;
# 2365 [ - + ]: 15 : if (!CanUpdateToWalletDescriptor(descriptor, error)) {
# 2366 : 0 : throw std::runtime_error(std::string(__func__) + ": " + error);
# 2367 : 0 : }
# 2368 : :
# 2369 : 15 : m_map_pubkeys.clear();
# 2370 : 15 : m_map_script_pub_keys.clear();
# 2371 : 15 : m_max_cached_index = -1;
# 2372 : 15 : m_wallet_descriptor = descriptor;
# 2373 : 15 : }
# 2374 : :
# 2375 : : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
# 2376 : 33 : {
# 2377 : 33 : LOCK(cs_desc_man);
# 2378 [ - + ]: 33 : if (!HasWalletDescriptor(descriptor)) {
# 2379 : 0 : error = "can only update matching descriptor";
# 2380 : 0 : return false;
# 2381 : 0 : }
# 2382 : :
# 2383 [ + + ]: 33 : if (descriptor.range_start > m_wallet_descriptor.range_start ||
# 2384 [ + + ]: 33 : descriptor.range_end < m_wallet_descriptor.range_end) {
# 2385 : : // Use inclusive range for error
# 2386 : 3 : error = strprintf("new range must include current range = [%d,%d]",
# 2387 : 3 : m_wallet_descriptor.range_start,
# 2388 : 3 : m_wallet_descriptor.range_end - 1);
# 2389 : 3 : return false;
# 2390 : 3 : }
# 2391 : :
# 2392 : 30 : return true;
# 2393 : 33 : }
# 2394 : : } // namespace wallet
|