Branch data Line data Source code
1 : : // Copyright (c) 2019-2022 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 <hash.h>
6 : : #include <key_io.h>
7 : : #include <logging.h>
8 : : #include <node/types.h>
9 : : #include <outputtype.h>
10 : : #include <script/descriptor.h>
11 : : #include <script/script.h>
12 : : #include <script/sign.h>
13 : : #include <script/solver.h>
14 : : #include <util/bip32.h>
15 : : #include <util/check.h>
16 : : #include <util/strencodings.h>
17 : : #include <util/string.h>
18 : : #include <util/time.h>
19 : : #include <util/translation.h>
20 : : #include <wallet/scriptpubkeyman.h>
21 : :
22 : : #include <optional>
23 : :
24 : : using common::PSBTError;
25 : : using util::ToString;
26 : :
27 : : namespace wallet {
28 : : //! 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.
29 : : const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
30 : :
31 : 2 : util::Result<CTxDestination> LegacyScriptPubKeyMan::GetNewDestination(const OutputType type)
32 : : {
33 [ - + ]: 2 : if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
34 : 0 : return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
35 : : }
36 [ - + ]: 2 : assert(type != OutputType::BECH32M);
37 : :
38 : : // Fill-up keypool if needed
39 : 2 : TopUp();
40 : :
41 : 2 : LOCK(cs_KeyStore);
42 : :
43 : : // Generate a new key that is added to wallet
44 [ + - ]: 2 : CPubKey new_key;
45 [ + - + + ]: 2 : if (!GetKeyFromPool(new_key, type)) {
46 [ + - ]: 3 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
47 : : }
48 [ + - ]: 1 : LearnRelatedScripts(new_key, type);
49 [ + - ]: 2 : return GetDestinationForKey(new_key, type);
50 : 2 : }
51 : :
52 : : typedef std::vector<unsigned char> valtype;
53 : :
54 : : namespace {
55 : :
56 : : /**
57 : : * This is an enum that tracks the execution context of a script, similar to
58 : : * SigVersion in script/interpreter. It is separate however because we want to
59 : : * distinguish between top-level scriptPubKey execution and P2SH redeemScript
60 : : * execution (a distinction that has no impact on consensus rules).
61 : : */
62 : : enum class IsMineSigVersion
63 : : {
64 : : TOP = 0, //!< scriptPubKey execution
65 : : P2SH = 1, //!< P2SH redeemScript
66 : : WITNESS_V0 = 2, //!< P2WSH witness script execution
67 : : };
68 : :
69 : : /**
70 : : * This is an internal representation of isminetype + invalidity.
71 : : * Its order is significant, as we return the max of all explored
72 : : * possibilities.
73 : : */
74 : : enum class IsMineResult
75 : : {
76 : : NO = 0, //!< Not ours
77 : : WATCH_ONLY = 1, //!< Included in watch-only balance
78 : : SPENDABLE = 2, //!< Included in all balances
79 : : INVALID = 3, //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
80 : : };
81 : :
82 : 1481 : bool PermitsUncompressed(IsMineSigVersion sigversion)
83 : : {
84 : 1481 : return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
85 : : }
86 : :
87 : 60 : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
88 : : {
89 [ + + ]: 148 : for (const valtype& pubkey : pubkeys) {
90 : 125 : CKeyID keyID = CPubKey(pubkey).GetID();
91 [ + + ]: 125 : if (!keystore.HaveKey(keyID)) return false;
92 : : }
93 : : return true;
94 : : }
95 : :
96 : : //! Recursively solve script and return spendable/watchonly/invalid status.
97 : : //!
98 : : //! @param keystore legacy key and script store
99 : : //! @param scriptPubKey script to solve
100 : : //! @param sigversion script type (top-level / redeemscript / witnessscript)
101 : : //! @param recurse_scripthash whether to recurse into nested p2sh and p2wsh
102 : : //! scripts or simply treat any script that has been
103 : : //! stored in the keystore as spendable
104 : : // NOLINTNEXTLINE(misc-no-recursion)
105 : 4208 : IsMineResult IsMineInner(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
106 : : {
107 : 4208 : IsMineResult ret = IsMineResult::NO;
108 : :
109 : 4208 : std::vector<valtype> vSolutions;
110 [ + - ]: 4208 : TxoutType whichType = Solver(scriptPubKey, vSolutions);
111 : :
112 [ + + + + : 4208 : CKeyID keyID;
+ + + ]
113 [ + + + + : 4208 : switch (whichType) {
+ + + ]
114 : : case TxoutType::NONSTANDARD:
115 : : case TxoutType::NULL_DATA:
116 : : case TxoutType::WITNESS_UNKNOWN:
117 : : case TxoutType::WITNESS_V1_TAPROOT:
118 : : case TxoutType::ANCHOR:
119 : : break;
120 : 335 : case TxoutType::PUBKEY:
121 [ + - ]: 335 : keyID = CPubKey(vSolutions[0]).GetID();
122 [ - + - - ]: 335 : if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
123 : : return IsMineResult::INVALID;
124 : : }
125 [ + - + + ]: 335 : if (keystore.HaveKey(keyID)) {
126 [ - + ]: 299 : ret = std::max(ret, IsMineResult::SPENDABLE);
127 : : }
128 : : break;
129 : 756 : case TxoutType::WITNESS_V0_KEYHASH:
130 : 756 : {
131 [ + + ]: 756 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
132 : : // P2WPKH inside P2WSH is invalid.
133 : : return IsMineResult::INVALID;
134 : : }
135 [ + + + - : 1078 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
+ - + - +
+ + + ]
136 : : // We do not support bare witness outputs unless the P2SH version of it would be
137 : : // acceptable as well. This protects against matching before segwit activates.
138 : : // This also applies to the P2WSH case.
139 : : break;
140 : : }
141 [ + - + - : 752 : ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
+ + ]
142 : 728 : break;
143 : : }
144 : 1083 : case TxoutType::PUBKEYHASH:
145 [ + + ]: 1083 : keyID = CKeyID(uint160(vSolutions[0]));
146 [ + + ]: 1083 : if (!PermitsUncompressed(sigversion)) {
147 [ + - ]: 748 : CPubKey pubkey;
148 [ + - + - : 748 : if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
+ + ]
149 : : return IsMineResult::INVALID;
150 : : }
151 : : }
152 [ + - + + ]: 1075 : if (keystore.HaveKey(keyID)) {
153 [ - + ]: 1004 : ret = std::max(ret, IsMineResult::SPENDABLE);
154 : : }
155 : : break;
156 : 1238 : case TxoutType::SCRIPTHASH:
157 : 1238 : {
158 [ + + ]: 1238 : if (sigversion != IsMineSigVersion::TOP) {
159 : : // P2SH inside P2WSH or P2SH is invalid.
160 : : return IsMineResult::INVALID;
161 : : }
162 [ + - ]: 1221 : CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
163 : 1221 : CScript subscript;
164 [ + - + + ]: 1221 : if (keystore.GetCScript(scriptID, subscript)) {
165 [ + + + - : 586 : ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
+ + ]
166 : : }
167 : 1221 : break;
168 : 1221 : }
169 : 683 : case TxoutType::WITNESS_V0_SCRIPTHASH:
170 : 683 : {
171 [ + + ]: 683 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
172 : : // P2WSH inside P2WSH is invalid.
173 : : return IsMineResult::INVALID;
174 : : }
175 [ + + + - : 1310 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
+ - + - +
+ + + ]
176 : : break;
177 : : }
178 [ + - ]: 94 : CScriptID scriptID{RIPEMD160(vSolutions[0])};
179 : 94 : CScript subscript;
180 [ + - + + ]: 94 : if (keystore.GetCScript(scriptID, subscript)) {
181 [ + + + - : 113 : ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
+ + ]
182 : : }
183 : 94 : break;
184 : 94 : }
185 : :
186 : 81 : case TxoutType::MULTISIG:
187 : 81 : {
188 : : // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
189 [ + + ]: 81 : if (sigversion == IsMineSigVersion::TOP) {
190 : : break;
191 : : }
192 : :
193 : : // Only consider transactions "mine" if we own ALL the
194 : : // keys involved. Multi-signature transactions that are
195 : : // partially owned (somebody else has a key that can spend
196 : : // them) enable spend-out-from-under-you attacks, especially
197 : : // in shared-wallet situations.
198 [ + - ]: 63 : std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
199 [ + + ]: 63 : if (!PermitsUncompressed(sigversion)) {
200 [ + + ]: 134 : for (size_t i = 0; i < keys.size(); i++) {
201 [ + + ]: 96 : if (keys[i].size() != 33) {
202 : 3 : return IsMineResult::INVALID;
203 : : }
204 : : }
205 : : }
206 [ + - + + ]: 60 : if (HaveKeys(keys, keystore)) {
207 [ - + ]: 23 : ret = std::max(ret, IsMineResult::SPENDABLE);
208 : : }
209 : 60 : break;
210 : 63 : }
211 : : } // no default case, so the compiler can warn about missing cases
212 : :
213 [ + + + - : 4169 : if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
+ + ]
214 [ - + ]: 148 : ret = std::max(ret, IsMineResult::WATCH_ONLY);
215 : : }
216 : 4169 : return ret;
217 : 4208 : }
218 : :
219 : : } // namespace
220 : :
221 : 2453 : isminetype LegacyDataSPKM::IsMine(const CScript& script) const
222 : : {
223 [ + + - + ]: 2453 : switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
224 : : case IsMineResult::INVALID:
225 : : case IsMineResult::NO:
226 : : return ISMINE_NO;
227 : 147 : case IsMineResult::WATCH_ONLY:
228 : 147 : return ISMINE_WATCH_ONLY;
229 : 1323 : case IsMineResult::SPENDABLE:
230 : 1323 : return ISMINE_SPENDABLE;
231 : : }
232 : 0 : assert(false);
233 : : }
234 : :
235 : 4 : bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
236 : : {
237 : 4 : {
238 : 4 : LOCK(cs_KeyStore);
239 [ - + ]: 4 : assert(mapKeys.empty());
240 : :
241 [ + - ]: 4 : bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
242 : 4 : bool keyFail = false;
243 [ + - ]: 4 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
244 [ + - + - ]: 4 : WalletBatch batch(m_storage.GetDatabase());
245 [ + + ]: 2006 : for (; mi != mapCryptedKeys.end(); ++mi)
246 : : {
247 [ + - ]: 2005 : const CPubKey &vchPubKey = (*mi).second.first;
248 : 2005 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
249 : 2005 : CKey key;
250 [ + - + - ]: 2005 : if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
251 : : {
252 : : keyFail = true;
253 : : break;
254 : : }
255 : 2005 : keyPass = true;
256 [ + + ]: 2005 : if (fDecryptionThoroughlyChecked)
257 : : break;
258 : : else {
259 : : // Rewrite these encrypted keys with checksums
260 [ + - + - : 2002 : batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
+ - ]
261 : : }
262 : 2005 : }
263 [ - + ]: 4 : if (keyPass && keyFail)
264 : : {
265 [ # # ]: 0 : LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
266 [ # # ]: 0 : throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
267 : : }
268 [ - + ]: 4 : if (keyFail || !keyPass)
269 : 0 : return false;
270 : 4 : fDecryptionThoroughlyChecked = true;
271 [ - - + - ]: 4 : }
272 : 4 : return true;
273 : : }
274 : :
275 : 1 : bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
276 : : {
277 : 1 : LOCK(cs_KeyStore);
278 : 1 : encrypted_batch = batch;
279 [ - + ]: 1 : if (!mapCryptedKeys.empty()) {
280 : 0 : encrypted_batch = nullptr;
281 : 0 : return false;
282 : : }
283 : :
284 : 1 : KeyMap keys_to_encrypt;
285 : 1 : keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
286 [ + + ]: 1002 : for (const KeyMap::value_type& mKey : keys_to_encrypt)
287 : : {
288 : 1001 : const CKey &key = mKey.second;
289 [ + - ]: 1001 : CPubKey vchPubKey = key.GetPubKey();
290 [ + - + - : 3003 : CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
291 : 1001 : std::vector<unsigned char> vchCryptedSecret;
292 [ + - + - : 1001 : if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
- + ]
293 : 0 : encrypted_batch = nullptr;
294 : 0 : return false;
295 : : }
296 [ + - - + ]: 1001 : if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
297 : 0 : encrypted_batch = nullptr;
298 : 0 : return false;
299 : : }
300 : 1001 : }
301 : 1 : encrypted_batch = nullptr;
302 : 1 : return true;
303 : 2 : }
304 : :
305 : 0 : util::Result<CTxDestination> LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
306 : : {
307 [ # # ]: 0 : if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
308 : 0 : return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
309 : : }
310 [ # # ]: 0 : assert(type != OutputType::BECH32M);
311 : :
312 : 0 : LOCK(cs_KeyStore);
313 [ # # # # ]: 0 : if (!CanGetAddresses(internal)) {
314 [ # # ]: 0 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
315 : : }
316 : :
317 : : // Fill-up keypool if needed
318 [ # # ]: 0 : TopUp();
319 : :
320 [ # # # # ]: 0 : if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
321 [ # # ]: 0 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
322 : : }
323 [ # # ]: 0 : return GetDestinationForKey(keypool.vchPubKey, type);
324 : 0 : }
325 : :
326 : 0 : bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
327 : : {
328 : 0 : LOCK(cs_KeyStore);
329 : :
330 [ # # ]: 0 : auto it = m_inactive_hd_chains.find(seed_id);
331 [ # # ]: 0 : if (it == m_inactive_hd_chains.end()) {
332 : : return false;
333 : : }
334 : :
335 [ # # ]: 0 : CHDChain& chain = it->second;
336 : :
337 [ # # ]: 0 : if (internal) {
338 [ # # ]: 0 : chain.m_next_internal_index = std::max(chain.m_next_internal_index, index + 1);
339 : : } else {
340 [ # # ]: 0 : chain.m_next_external_index = std::max(chain.m_next_external_index, index + 1);
341 : : }
342 : :
343 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
344 [ # # ]: 0 : TopUpChain(batch, chain, 0);
345 : :
346 : 0 : return true;
347 : 0 : }
348 : :
349 : 4 : std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
350 : : {
351 : 4 : LOCK(cs_KeyStore);
352 : 4 : std::vector<WalletDestination> result;
353 : : // extract addresses and check if they match with an unused keypool key
354 [ + - - + ]: 4 : for (const auto& keyid : GetAffectedKeys(script, *this)) {
355 [ # # ]: 0 : std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
356 [ # # ]: 0 : if (mi != m_pool_key_to_index.end()) {
357 [ # # ]: 0 : WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
358 [ # # # # ]: 0 : for (const auto& keypool : MarkReserveKeysAsUsed(mi->second)) {
359 : : // derive all possible destinations as any of them could have been used
360 [ # # ]: 0 : for (const auto& type : LEGACY_OUTPUT_TYPES) {
361 [ # # ]: 0 : const auto& dest = GetDestinationForKey(keypool.vchPubKey, type);
362 [ # # ]: 0 : result.push_back({dest, keypool.fInternal});
363 : 0 : }
364 : 0 : }
365 : :
366 [ # # # # ]: 0 : if (!TopUp()) {
367 [ # # ]: 0 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
368 : : }
369 : : }
370 : :
371 : : // 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.
372 : : // If so, TopUp the inactive hd chain
373 : 0 : auto it = mapKeyMetadata.find(keyid);
374 [ # # ]: 0 : if (it != mapKeyMetadata.end()){
375 [ # # ]: 0 : CKeyMetadata meta = it->second;
376 [ # # # # ]: 0 : if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
377 : 0 : std::vector<uint32_t> path;
378 [ # # ]: 0 : if (meta.has_key_origin) {
379 [ # # ]: 0 : path = meta.key_origin.path;
380 [ # # # # ]: 0 : } else if (!ParseHDKeypath(meta.hdKeypath, path)) {
381 [ # # ]: 0 : WalletLogPrintf("%s: Adding inactive seed keys failed, invalid hdKeypath: %s\n",
382 : : __func__,
383 : : meta.hdKeypath);
384 : : }
385 [ # # ]: 0 : if (path.size() != 3) {
386 [ # # ]: 0 : WalletLogPrintf("%s: Adding inactive seed keys failed, invalid path size: %d, has_key_origin: %s\n",
387 : : __func__,
388 [ # # ]: 0 : path.size(),
389 : : meta.has_key_origin);
390 : : } else {
391 : 0 : bool internal = (path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
392 : 0 : int64_t index = path[2] & ~BIP32_HARDENED_KEY_LIMIT;
393 : :
394 [ # # # # ]: 0 : if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
395 [ # # ]: 0 : WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
396 : : }
397 : : }
398 : 0 : }
399 : 0 : }
400 : 0 : }
401 : :
402 [ + - ]: 4 : return result;
403 [ - - ]: 4 : }
404 : :
405 : 1 : void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
406 : : {
407 : 1 : LOCK(cs_KeyStore);
408 [ + - + - : 1 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
+ - - + ]
409 [ # # ]: 0 : return;
410 : : }
411 : :
412 [ + - + - ]: 1 : std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
413 [ + + ]: 1002 : for (auto& meta_pair : mapKeyMetadata) {
414 : 1001 : CKeyMetadata& meta = meta_pair.second;
415 [ + - + + : 1001 : 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
- + ]
416 : 0 : CKey key;
417 [ # # ]: 0 : GetKey(meta.hd_seed_id, key);
418 [ # # ]: 0 : CExtKey masterKey;
419 [ # # # # ]: 0 : masterKey.SetSeed(key);
420 : : // Add to map
421 [ # # # # ]: 0 : CKeyID master_id = masterKey.key.GetPubKey().GetID();
422 : 0 : std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
423 [ # # # # ]: 0 : if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
424 [ # # ]: 0 : throw std::runtime_error("Invalid stored hdKeypath");
425 : : }
426 : 0 : meta.has_key_origin = true;
427 [ # # ]: 0 : if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
428 : 0 : meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
429 : : }
430 : :
431 : : // Write meta to wallet
432 [ # # ]: 0 : CPubKey pubkey;
433 [ # # # # ]: 0 : if (GetPubKey(meta_pair.first, pubkey)) {
434 [ # # ]: 0 : batch->WriteKeyMetadata(meta, pubkey, true);
435 : : }
436 : 0 : }
437 : : }
438 [ + - ]: 2 : }
439 : :
440 : 3 : bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
441 : : {
442 [ + - + - : 3 : if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
- + ]
443 : 0 : return false;
444 : : }
445 : :
446 : 3 : SetHDSeed(GenerateNewSeed());
447 [ - + ]: 3 : if (!NewKeyPool()) {
448 : 0 : return false;
449 : : }
450 : : return true;
451 : : }
452 : :
453 : 2021 : bool LegacyScriptPubKeyMan::IsHDEnabled() const
454 : : {
455 : 2021 : return !m_hd_chain.seed_id.IsNull();
456 : : }
457 : :
458 : 2 : bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
459 : : {
460 : 2 : LOCK(cs_KeyStore);
461 : : // Check if the keypool has keys
462 : 2 : bool keypool_has_keys;
463 [ - + - - : 2 : if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
- - ]
464 : 0 : keypool_has_keys = setInternalKeyPool.size() > 0;
465 : : } else {
466 [ + - ]: 2 : keypool_has_keys = KeypoolCountExternalKeys() > 0;
467 : : }
468 : : // If the keypool doesn't have keys, check if we can generate them
469 [ + + ]: 2 : if (!keypool_has_keys) {
470 [ + - ]: 1 : return CanGenerateKeys();
471 : : }
472 : : return keypool_has_keys;
473 : 2 : }
474 : :
475 : 0 : bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
476 : : {
477 : 0 : LOCK(cs_KeyStore);
478 : :
479 [ # # # # ]: 0 : if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
480 : : // Nothing to do here if private keys are not enabled
481 : : return true;
482 : : }
483 : :
484 : 0 : bool hd_upgrade = false;
485 : 0 : bool split_upgrade = false;
486 [ # # # # : 0 : if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
# # # # ]
487 [ # # ]: 0 : WalletLogPrintf("Upgrading wallet to HD\n");
488 [ # # ]: 0 : m_storage.SetMinVersion(FEATURE_HD);
489 : :
490 : : // generate a new master key
491 [ # # ]: 0 : CPubKey masterPubKey = GenerateNewSeed();
492 [ # # ]: 0 : SetHDSeed(masterPubKey);
493 : : hd_upgrade = true;
494 : : }
495 : : // Upgrade to HD chain split if necessary
496 [ # # # # : 0 : if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
# # # # ]
497 [ # # ]: 0 : WalletLogPrintf("Upgrading wallet to use HD chain split\n");
498 [ # # ]: 0 : m_storage.SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
499 : 0 : split_upgrade = FEATURE_HD_SPLIT > prev_version;
500 : : // Upgrade the HDChain
501 [ # # ]: 0 : if (m_hd_chain.nVersion < CHDChain::VERSION_HD_CHAIN_SPLIT) {
502 : 0 : m_hd_chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
503 [ # # # # : 0 : if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(m_hd_chain)) {
# # # # ]
504 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing chain failed");
505 : : }
506 : : }
507 : : }
508 : : // Mark all keys currently in the keypool as pre-split
509 [ # # ]: 0 : if (split_upgrade) {
510 [ # # ]: 0 : MarkPreSplitKeys();
511 : : }
512 : : // Regenerate the keypool if upgraded to HD
513 [ # # ]: 0 : if (hd_upgrade) {
514 [ # # # # ]: 0 : if (!NewKeyPool()) {
515 [ # # ]: 0 : error = _("Unable to generate keys");
516 : 0 : return false;
517 : : }
518 : : }
519 : : return true;
520 : 0 : }
521 : :
522 : 0 : bool LegacyScriptPubKeyMan::HavePrivateKeys() const
523 : : {
524 : 0 : LOCK(cs_KeyStore);
525 [ # # # # : 0 : return !mapKeys.empty() || !mapCryptedKeys.empty();
# # ]
526 : 0 : }
527 : :
528 : 0 : bool LegacyScriptPubKeyMan::HaveCryptedKeys() const
529 : : {
530 : 0 : LOCK(cs_KeyStore);
531 [ # # ]: 0 : return !mapCryptedKeys.empty();
532 : 0 : }
533 : :
534 : 0 : void LegacyScriptPubKeyMan::RewriteDB()
535 : : {
536 : 0 : LOCK(cs_KeyStore);
537 : 0 : setInternalKeyPool.clear();
538 : 0 : setExternalKeyPool.clear();
539 [ # # ]: 0 : m_pool_key_to_index.clear();
540 : : // Note: can't top-up keypool here, because wallet is locked.
541 : : // User will be prompted to unlock wallet the next operation
542 : : // that requires a new key.
543 : 0 : }
544 : :
545 : 0 : static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
546 [ # # ]: 0 : if (setKeyPool.empty()) {
547 : 0 : return GetTime();
548 : : }
549 : :
550 : 0 : CKeyPool keypool;
551 : 0 : int64_t nIndex = *(setKeyPool.begin());
552 [ # # ]: 0 : if (!batch.ReadPool(nIndex, keypool)) {
553 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
554 : : }
555 [ # # ]: 0 : assert(keypool.vchPubKey.IsValid());
556 : 0 : return keypool.nTime;
557 : : }
558 : :
559 : 0 : std::optional<int64_t> LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
560 : : {
561 : 0 : LOCK(cs_KeyStore);
562 : :
563 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
564 : :
565 : : // load oldest key from keypool, get time and return
566 [ # # ]: 0 : int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
567 [ # # # # : 0 : if (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
# # # # ]
568 [ # # # # ]: 0 : oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
569 [ # # ]: 0 : if (!set_pre_split_keypool.empty()) {
570 [ # # # # ]: 0 : oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
571 : : }
572 : : }
573 : :
574 : 0 : return oldestKey;
575 [ # # ]: 0 : }
576 : :
577 : 2 : size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
578 : : {
579 : 2 : LOCK(cs_KeyStore);
580 [ + - ]: 2 : return setExternalKeyPool.size() + set_pre_split_keypool.size();
581 : 2 : }
582 : :
583 : 0 : unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
584 : : {
585 : 0 : LOCK(cs_KeyStore);
586 [ # # ]: 0 : return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
587 : 0 : }
588 : :
589 : 32 : int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
590 : : {
591 : 32 : LOCK(cs_KeyStore);
592 [ + - ]: 32 : return nTimeFirstKey;
593 : 32 : }
594 : :
595 : 81 : std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
596 : : {
597 : 81 : return std::make_unique<LegacySigningProvider>(*this);
598 : : }
599 : :
600 : 411 : bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
601 : : {
602 : 411 : IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
603 [ + + ]: 411 : if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
604 : : // If ismine, it means we recognize keys or script ids in the script, or
605 : : // are watching the script itself, and we can at least provide metadata
606 : : // or solving information, even if not able to sign fully.
607 : : return true;
608 : : } else {
609 : : // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
610 : 381 : ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
611 [ + + ]: 381 : if (!sigdata.signatures.empty()) {
612 : : // If we could make signatures, make sure we have a private key to actually make a signature
613 : 1 : bool has_privkeys = false;
614 [ + + ]: 2 : for (const auto& key_sig_pair : sigdata.signatures) {
615 : 1 : has_privkeys |= HaveKey(key_sig_pair.first);
616 : : }
617 : : return has_privkeys;
618 : : }
619 : : return false;
620 : : }
621 : : }
622 : :
623 : 0 : bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
624 : : {
625 : 0 : return ::SignTransaction(tx, this, coins, sighash, input_errors);
626 : : }
627 : :
628 : 0 : SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
629 : : {
630 : 0 : CKey key;
631 [ # # # # : 0 : if (!GetKey(ToKeyID(pkhash), key)) {
# # ]
632 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
633 : : }
634 : :
635 [ # # # # ]: 0 : if (MessageSign(key, message, str_sig)) {
636 : 0 : return SigningResult::OK;
637 : : }
638 : : return SigningResult::SIGNING_FAILED;
639 : 0 : }
640 : :
641 : 0 : std::optional<PSBTError> LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
642 : : {
643 [ # # ]: 0 : if (n_signed) {
644 : 0 : *n_signed = 0;
645 : : }
646 [ # # ]: 0 : for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
647 : 0 : const CTxIn& txin = psbtx.tx->vin[i];
648 : 0 : PSBTInput& input = psbtx.inputs.at(i);
649 : :
650 [ # # ]: 0 : if (PSBTInputSigned(input)) {
651 : 0 : continue;
652 : : }
653 : :
654 : : // Get the Sighash type
655 [ # # # # : 0 : if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
# # ]
656 : 0 : return PSBTError::SIGHASH_MISMATCH;
657 : : }
658 : :
659 : : // Check non_witness_utxo has specified prevout
660 [ # # ]: 0 : if (input.non_witness_utxo) {
661 [ # # ]: 0 : if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
662 : 0 : return PSBTError::MISSING_INPUTS;
663 : : }
664 [ # # ]: 0 : } else if (input.witness_utxo.IsNull()) {
665 : : // There's no UTXO so we can just skip this now
666 : 0 : continue;
667 : : }
668 [ # # ]: 0 : SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
669 : :
670 : 0 : bool signed_one = PSBTInputSigned(input);
671 [ # # # # ]: 0 : if (n_signed && (signed_one || !sign)) {
672 : : // If sign is false, we assume that we _could_ sign if we get here. This
673 : : // will never have false negatives; it is hard to tell under what i
674 : : // circumstances it could have false positives.
675 : 0 : (*n_signed)++;
676 : : }
677 : : }
678 : :
679 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
680 [ # # ]: 0 : for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
681 [ # # ]: 0 : UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
682 : : }
683 : :
684 : 0 : return {};
685 : : }
686 : :
687 : 0 : std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
688 : : {
689 : 0 : LOCK(cs_KeyStore);
690 : :
691 [ # # ]: 0 : CKeyID key_id = GetKeyForDestination(*this, dest);
692 [ # # ]: 0 : if (!key_id.IsNull()) {
693 : 0 : auto it = mapKeyMetadata.find(key_id);
694 [ # # ]: 0 : if (it != mapKeyMetadata.end()) {
695 [ # # ]: 0 : return std::make_unique<CKeyMetadata>(it->second);
696 : : }
697 : : }
698 : :
699 [ # # ]: 0 : CScript scriptPubKey = GetScriptForDestination(dest);
700 [ # # ]: 0 : auto it = m_script_metadata.find(CScriptID(scriptPubKey));
701 [ # # ]: 0 : if (it != m_script_metadata.end()) {
702 [ # # ]: 0 : return std::make_unique<CKeyMetadata>(it->second);
703 : : }
704 : :
705 : 0 : return nullptr;
706 : 0 : }
707 : :
708 : 32 : uint256 LegacyScriptPubKeyMan::GetID() const
709 : : {
710 : 32 : return uint256::ONE;
711 : : }
712 : :
713 : : /**
714 : : * Update wallet first key creation time. This should be called whenever keys
715 : : * are added to the wallet, with the oldest key creation time.
716 : : */
717 : 10017 : void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
718 : : {
719 : 10017 : AssertLockHeld(cs_KeyStore);
720 [ + + ]: 10017 : if (nCreateTime <= 1) {
721 : : // Cannot determine birthday information, so set the wallet birthday to
722 : : // the beginning of time.
723 : 2 : nTimeFirstKey = 1;
724 [ + + + + ]: 10015 : } else if (nTimeFirstKey == UNKNOWN_TIME || nCreateTime < nTimeFirstKey) {
725 : 19 : nTimeFirstKey = nCreateTime;
726 : : }
727 : :
728 : 10017 : NotifyFirstKeyTimeChanged(this, nTimeFirstKey);
729 : 10017 : }
730 : :
731 : 120 : bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
732 : : {
733 : 120 : return AddKeyPubKeyInner(key, pubkey);
734 : : }
735 : :
736 : 29 : bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
737 : : {
738 : 29 : LOCK(cs_KeyStore);
739 [ + - + - ]: 29 : WalletBatch batch(m_storage.GetDatabase());
740 [ + - ]: 29 : return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
741 [ + - ]: 58 : }
742 : :
743 : 2034 : bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
744 : : {
745 : 2034 : AssertLockHeld(cs_KeyStore);
746 : :
747 : : // Make sure we aren't adding private keys to private key disabled wallets
748 [ - + ]: 2034 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
749 : :
750 : : // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
751 : : // which is overridden below. To avoid flushes, the database handle is
752 : : // tunneled through to it.
753 : 2034 : bool needsDB = !encrypted_batch;
754 [ + - ]: 2034 : if (needsDB) {
755 : 2034 : encrypted_batch = &batch;
756 : : }
757 [ - + ]: 2034 : if (!AddKeyPubKeyInner(secret, pubkey)) {
758 [ # # ]: 0 : if (needsDB) encrypted_batch = nullptr;
759 : 0 : return false;
760 : : }
761 [ + - ]: 2034 : if (needsDB) encrypted_batch = nullptr;
762 : :
763 : : // check if we need to remove from watch-only
764 : 2034 : CScript script;
765 [ + - + - ]: 4068 : script = GetScriptForDestination(PKHash(pubkey));
766 [ + - - + ]: 2034 : if (HaveWatchOnly(script)) {
767 [ # # ]: 0 : RemoveWatchOnly(script);
768 : : }
769 [ + - ]: 4068 : script = GetScriptForRawPubKey(pubkey);
770 [ + - - + ]: 2034 : if (HaveWatchOnly(script)) {
771 [ # # ]: 0 : RemoveWatchOnly(script);
772 : : }
773 : :
774 [ + - ]: 2034 : m_storage.UnsetBlankWalletFlag(batch);
775 [ + - + + ]: 2034 : if (!m_storage.HasEncryptionKeys()) {
776 [ + - ]: 1033 : return batch.WriteKey(pubkey,
777 [ + - ]: 2066 : secret.GetPrivKey(),
778 [ + - + - ]: 1033 : mapKeyMetadata[pubkey.GetID()]);
779 : : }
780 : : return true;
781 : 2034 : }
782 : :
783 : 83 : bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
784 : : {
785 : : /* A sanity check was added in pull #3843 to avoid adding redeemScripts
786 : : * that never can be redeemed. However, old wallets may still contain
787 : : * these. Do not add them to the wallet and warn. */
788 [ + + - + ]: 83 : if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
789 : : {
790 [ # # ]: 0 : std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
791 [ # # # # ]: 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);
792 : 0 : return true;
793 : 0 : }
794 : :
795 : 83 : return FillableSigningProvider::AddCScript(redeemScript);
796 : : }
797 : :
798 : 8156 : void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
799 : : {
800 : 8156 : LOCK(cs_KeyStore);
801 [ + - + - ]: 8156 : mapKeyMetadata[keyID] = meta;
802 : 8156 : }
803 : :
804 : 8008 : void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
805 : : {
806 : 8008 : LOCK(cs_KeyStore);
807 [ + - ]: 8008 : LegacyDataSPKM::LoadKeyMetadata(keyID, meta);
808 [ + - ]: 8008 : UpdateTimeFirstKey(meta.nCreateTime);
809 : 8008 : }
810 : :
811 : 44 : void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
812 : : {
813 : 44 : LOCK(cs_KeyStore);
814 [ + - + - ]: 44 : m_script_metadata[script_id] = meta;
815 : 44 : }
816 : :
817 : 0 : void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
818 : : {
819 : 0 : LOCK(cs_KeyStore);
820 [ # # ]: 0 : LegacyDataSPKM::LoadScriptMetadata(script_id, meta);
821 [ # # ]: 0 : UpdateTimeFirstKey(meta.nCreateTime);
822 : 0 : }
823 : :
824 : 120 : bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
825 : : {
826 : 120 : LOCK(cs_KeyStore);
827 [ + - + - ]: 120 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
828 : 120 : }
829 : :
830 : 2034 : bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
831 : : {
832 : 2034 : LOCK(cs_KeyStore);
833 [ + - + + ]: 2034 : if (!m_storage.HasEncryptionKeys()) {
834 [ + - ]: 1033 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
835 : : }
836 : :
837 [ + - + - ]: 1001 : if (m_storage.IsLocked()) {
838 : : return false;
839 : : }
840 : :
841 : 1001 : std::vector<unsigned char> vchCryptedSecret;
842 [ + - + - : 3003 : CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
843 [ + - + - : 1001 : if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
+ - ]
844 : 1001 : return EncryptSecret(encryption_key, vchSecret, pubkey.GetHash(), vchCryptedSecret);
845 : : })) {
846 : : return false;
847 : : }
848 : :
849 [ + - - + ]: 1001 : if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
850 : 0 : return false;
851 : : }
852 : : return true;
853 : 3035 : }
854 : :
855 : 8030 : bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
856 : : {
857 : : // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
858 [ + + ]: 8030 : if (!checksum_valid) {
859 : 1 : fDecryptionThoroughlyChecked = false;
860 : : }
861 : :
862 : 8030 : return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
863 : : }
864 : :
865 : 10032 : bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
866 : : {
867 : 10032 : LOCK(cs_KeyStore);
868 [ - + ]: 10032 : assert(mapKeys.empty());
869 : :
870 [ + - + - : 20064 : mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
+ - ]
871 [ + - ]: 10032 : ImplicitlyLearnRelatedKeyScripts(vchPubKey);
872 [ + - ]: 10032 : return true;
873 : 10032 : }
874 : :
875 : 2002 : bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
876 : : const std::vector<unsigned char> &vchCryptedSecret)
877 : : {
878 [ + - ]: 2002 : if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
879 : : return false;
880 : 2002 : {
881 : 2002 : LOCK(cs_KeyStore);
882 [ + - ]: 2002 : if (encrypted_batch)
883 [ + - ]: 2002 : return encrypted_batch->WriteCryptedKey(vchPubKey,
884 : : vchCryptedSecret,
885 [ + - + - ]: 2002 : mapKeyMetadata[vchPubKey.GetID()]);
886 : : else
887 [ # # # # : 0 : return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
# # ]
888 : : vchCryptedSecret,
889 [ # # # # ]: 0 : mapKeyMetadata[vchPubKey.GetID()]);
890 : 2002 : }
891 : : }
892 : :
893 : 5637 : bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
894 : : {
895 : 5637 : LOCK(cs_KeyStore);
896 [ + - ]: 5637 : return setWatchOnly.count(dest) > 0;
897 : 5637 : }
898 : :
899 : 6 : bool LegacyDataSPKM::HaveWatchOnly() const
900 : : {
901 : 6 : LOCK(cs_KeyStore);
902 [ + - ]: 6 : return (!setWatchOnly.empty());
903 : 6 : }
904 : :
905 : 56 : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
906 : : {
907 : 56 : std::vector<std::vector<unsigned char>> solutions;
908 [ + - + + : 75 : return Solver(dest, solutions) == TxoutType::PUBKEY &&
+ + ]
909 [ + - ]: 75 : (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
910 : 56 : }
911 : :
912 : 5 : bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
913 : : {
914 : 5 : {
915 : 5 : LOCK(cs_KeyStore);
916 : 5 : setWatchOnly.erase(dest);
917 [ + - ]: 5 : CPubKey pubKey;
918 [ + - + + ]: 5 : if (ExtractPubKey(dest, pubKey)) {
919 [ + - ]: 2 : mapWatchKeys.erase(pubKey.GetID());
920 : : }
921 : : // Related CScripts are not removed; having superfluous scripts around is
922 : : // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
923 : 0 : }
924 : :
925 [ + - ]: 5 : if (!HaveWatchOnly())
926 : 5 : NotifyWatchonlyChanged(false);
927 [ + - - + ]: 10 : if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
928 : 0 : return false;
929 : :
930 : : return true;
931 : : }
932 : :
933 : 49 : bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
934 : : {
935 : 49 : return AddWatchOnlyInMem(dest);
936 : : }
937 : :
938 : 51 : bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
939 : : {
940 : 51 : LOCK(cs_KeyStore);
941 [ + - ]: 51 : setWatchOnly.insert(dest);
942 [ + - ]: 51 : CPubKey pubKey;
943 [ + - + + ]: 51 : if (ExtractPubKey(dest, pubKey)) {
944 [ + - + - ]: 13 : mapWatchKeys[pubKey.GetID()] = pubKey;
945 [ + - ]: 13 : ImplicitlyLearnRelatedKeyScripts(pubKey);
946 : : }
947 [ + - ]: 51 : return true;
948 : 51 : }
949 : :
950 : 2 : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
951 : : {
952 [ + - ]: 2 : if (!AddWatchOnlyInMem(dest))
953 : : return false;
954 : 2 : const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
955 : 2 : UpdateTimeFirstKey(meta.nCreateTime);
956 : 2 : NotifyWatchonlyChanged(true);
957 [ + - ]: 2 : if (batch.WriteWatchOnly(dest, meta)) {
958 : 2 : m_storage.UnsetBlankWalletFlag(batch);
959 : 2 : return true;
960 : : }
961 : : return false;
962 : : }
963 : :
964 : 2 : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
965 : : {
966 : 2 : m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
967 : 2 : return AddWatchOnlyWithDB(batch, dest);
968 : : }
969 : :
970 : 0 : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest)
971 : : {
972 : 0 : WalletBatch batch(m_storage.GetDatabase());
973 [ # # ]: 0 : return AddWatchOnlyWithDB(batch, dest);
974 : 0 : }
975 : :
976 : 0 : bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
977 : : {
978 : 0 : m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
979 : 0 : return AddWatchOnly(dest);
980 : : }
981 : :
982 : 30 : void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
983 : : {
984 : 30 : LOCK(cs_KeyStore);
985 [ + - ]: 30 : m_hd_chain = chain;
986 : 30 : }
987 : :
988 : 3 : void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
989 : : {
990 : 3 : LOCK(cs_KeyStore);
991 : : // Store the new chain
992 [ + - + - : 6 : if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
+ - - + ]
993 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing chain failed");
994 : : }
995 : : // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
996 [ + + ]: 3 : if (!m_hd_chain.seed_id.IsNull()) {
997 [ + - ]: 1 : AddInactiveHDChain(m_hd_chain);
998 : : }
999 : :
1000 [ + - ]: 3 : m_hd_chain = chain;
1001 : 3 : }
1002 : :
1003 : 10 : void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
1004 : : {
1005 : 10 : LOCK(cs_KeyStore);
1006 [ - + ]: 10 : assert(!chain.seed_id.IsNull());
1007 [ + - + - ]: 10 : m_inactive_hd_chains[chain.seed_id] = chain;
1008 : 10 : }
1009 : :
1010 : 3541 : bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
1011 : : {
1012 : 3541 : LOCK(cs_KeyStore);
1013 [ + - + + ]: 3541 : if (!m_storage.HasEncryptionKeys()) {
1014 [ + - ]: 2487 : return FillableSigningProvider::HaveKey(address);
1015 : : }
1016 : 1054 : return mapCryptedKeys.count(address) > 0;
1017 : 3541 : }
1018 : :
1019 : 2949 : bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
1020 : : {
1021 : 2949 : LOCK(cs_KeyStore);
1022 [ + - + + ]: 2949 : if (!m_storage.HasEncryptionKeys()) {
1023 [ + - ]: 1942 : return FillableSigningProvider::GetKey(address, keyOut);
1024 : : }
1025 : :
1026 : 1007 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1027 [ + - ]: 1007 : if (mi != mapCryptedKeys.end())
1028 : : {
1029 [ + - ]: 1007 : const CPubKey &vchPubKey = (*mi).second.first;
1030 : 1007 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
1031 [ + - + - ]: 1007 : return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1032 : 1007 : return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
1033 : : });
1034 : : }
1035 : : return false;
1036 : 2949 : }
1037 : :
1038 : 127 : bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
1039 : : {
1040 : 127 : CKeyMetadata meta;
1041 : 127 : {
1042 [ + - ]: 127 : LOCK(cs_KeyStore);
1043 : 127 : auto it = mapKeyMetadata.find(keyID);
1044 [ + + ]: 127 : if (it == mapKeyMetadata.end()) {
1045 [ + - ]: 48 : return false;
1046 : : }
1047 [ + - ]: 79 : meta = it->second;
1048 : 48 : }
1049 [ + + ]: 79 : if (meta.has_key_origin) {
1050 : 42 : std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
1051 [ + - ]: 42 : info.path = meta.key_origin.path;
1052 : : } else { // Single pubkeys get the master fingerprint of themselves
1053 : 37 : std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
1054 : : }
1055 : : return true;
1056 : 127 : }
1057 : :
1058 : 79 : bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
1059 : : {
1060 : 79 : LOCK(cs_KeyStore);
1061 : 79 : WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
1062 [ + + ]: 79 : if (it != mapWatchKeys.end()) {
1063 : 66 : pubkey_out = it->second;
1064 : 66 : return true;
1065 : : }
1066 : : return false;
1067 : 79 : }
1068 : :
1069 : 788 : bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
1070 : : {
1071 : 788 : LOCK(cs_KeyStore);
1072 [ + - + + ]: 788 : if (!m_storage.HasEncryptionKeys()) {
1073 [ + - + + ]: 758 : if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
1074 [ + - ]: 72 : return GetWatchPubKey(address, vchPubKeyOut);
1075 : : }
1076 : : return true;
1077 : : }
1078 : :
1079 : 30 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1080 [ + - ]: 30 : if (mi != mapCryptedKeys.end())
1081 : : {
1082 : 30 : vchPubKeyOut = (*mi).second.first;
1083 : 30 : return true;
1084 : : }
1085 : : // Check for watch-only pubkeys
1086 [ # # ]: 0 : return GetWatchPubKey(address, vchPubKeyOut);
1087 : 788 : }
1088 : :
1089 : 2004 : CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
1090 : : {
1091 [ - + ]: 2004 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1092 [ - + ]: 2004 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
1093 : 2004 : AssertLockHeld(cs_KeyStore);
1094 : 2004 : bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
1095 : :
1096 : 2004 : CKey secret;
1097 : :
1098 : : // Create new metadata
1099 [ + - ]: 2004 : int64_t nCreationTime = GetTime();
1100 : 2004 : CKeyMetadata metadata(nCreationTime);
1101 : :
1102 : : // use HD key derivation if HD was enabled during wallet creation and a seed is present
1103 [ + - + - ]: 2004 : if (IsHDEnabled()) {
1104 [ + - - + : 2004 : DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
+ - ]
1105 : : } else {
1106 [ # # ]: 0 : secret.MakeNewKey(fCompressed);
1107 : : }
1108 : :
1109 : : // Compressed public keys were introduced in version 0.6.0
1110 [ - + ]: 2004 : if (fCompressed) {
1111 [ # # ]: 0 : m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
1112 : : }
1113 : :
1114 [ + - ]: 2004 : CPubKey pubkey = secret.GetPubKey();
1115 [ + - - + ]: 2004 : assert(secret.VerifyPubKey(pubkey));
1116 : :
1117 [ + - + - : 2004 : mapKeyMetadata[pubkey.GetID()] = metadata;
+ - ]
1118 [ + - ]: 2004 : UpdateTimeFirstKey(nCreationTime);
1119 : :
1120 [ + - - + ]: 2004 : if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1121 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1122 : : }
1123 : 2004 : return pubkey;
1124 : 2004 : }
1125 : :
1126 : : //! Try to derive an extended key, throw if it fails.
1127 : 6012 : static void DeriveExtKey(CExtKey& key_in, unsigned int index, CExtKey& key_out) {
1128 [ - + ]: 6012 : if (!key_in.Derive(key_out, index)) {
1129 [ # # ]: 0 : throw std::runtime_error("Could not derive extended key");
1130 : : }
1131 : 6012 : }
1132 : :
1133 : 2004 : void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
1134 : : {
1135 : : // for now we use a fixed keypath scheme of m/0'/0'/k
1136 : 2004 : CKey seed; //seed (256bit)
1137 [ + - ]: 2004 : CExtKey masterKey; //hd master key
1138 : 2004 : CExtKey accountKey; //key at m/0'
1139 : 2004 : CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
1140 : 2004 : CExtKey childKey; //key at m/0'/0'/<n>'
1141 : :
1142 : : // try to get the seed
1143 [ + - - + ]: 2004 : if (!GetKey(hd_chain.seed_id, seed))
1144 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": seed not found");
1145 : :
1146 [ + - + - ]: 4008 : masterKey.SetSeed(seed);
1147 : :
1148 : : // derive m/0'
1149 : : // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
1150 [ + - ]: 2004 : DeriveExtKey(masterKey, BIP32_HARDENED_KEY_LIMIT, accountKey);
1151 : :
1152 : : // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1153 [ - + - - : 2004 : assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
- - ]
1154 [ + - + - ]: 4008 : DeriveExtKey(accountKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0), chainChildKey);
1155 : :
1156 : : // derive child key at next index, skip keys already known to the wallet
1157 : 2004 : do {
1158 : : // always derive hardened keys
1159 : : // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
1160 : : // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1161 [ - + ]: 2004 : if (internal) {
1162 [ # # ]: 0 : DeriveExtKey(chainChildKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1163 [ # # # # ]: 0 : metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1164 [ # # ]: 0 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1165 [ # # ]: 0 : metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1166 [ # # ]: 0 : metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1167 : 0 : hd_chain.nInternalChainCounter++;
1168 : : }
1169 : : else {
1170 [ + - ]: 2004 : DeriveExtKey(chainChildKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1171 [ + - + - ]: 4008 : metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1172 [ + - ]: 2004 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1173 [ + - ]: 2004 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1174 [ + - ]: 2004 : metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1175 : 2004 : hd_chain.nExternalChainCounter++;
1176 : : }
1177 [ + - + - : 2004 : } while (HaveKey(childKey.key.GetPubKey().GetID()));
+ - - + ]
1178 [ + - ]: 2004 : secret = childKey.key;
1179 : 2004 : metadata.hd_seed_id = hd_chain.seed_id;
1180 [ + - + - ]: 2004 : CKeyID master_id = masterKey.key.GetPubKey().GetID();
1181 : 2004 : std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
1182 : 2004 : metadata.has_key_origin = true;
1183 : : // update the chain model in the database
1184 [ + - + - : 2004 : if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
+ - ]
1185 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
1186 : 2004 : }
1187 : :
1188 : 4047 : void LegacyDataSPKM::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
1189 : : {
1190 : 4047 : LOCK(cs_KeyStore);
1191 [ - + ]: 4047 : if (keypool.m_pre_split) {
1192 [ # # ]: 0 : set_pre_split_keypool.insert(nIndex);
1193 [ + + ]: 4047 : } else if (keypool.fInternal) {
1194 [ + - ]: 26 : setInternalKeyPool.insert(nIndex);
1195 : : } else {
1196 [ + - ]: 4021 : setExternalKeyPool.insert(nIndex);
1197 : : }
1198 [ + + ]: 4047 : m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1199 [ + - + - ]: 4047 : m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1200 : :
1201 : : // If no metadata exists yet, create a default with the pool key's
1202 : : // creation time. Note that this may be overwritten by actually
1203 : : // stored metadata for that key later, which is fine.
1204 [ + - ]: 4047 : CKeyID keyid = keypool.vchPubKey.GetID();
1205 [ - + ]: 4047 : if (mapKeyMetadata.count(keyid) == 0)
1206 [ # # ]: 0 : mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1207 : 4047 : }
1208 : :
1209 : 10 : bool LegacyScriptPubKeyMan::CanGenerateKeys() const
1210 : : {
1211 : : // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
1212 : 10 : LOCK(cs_KeyStore);
1213 [ + - + + : 12 : return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
+ - + + +
- ]
1214 : 10 : }
1215 : :
1216 : 3 : CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
1217 : : {
1218 [ - + ]: 3 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1219 : 3 : CKey key = GenerateRandomKey();
1220 [ + - ]: 3 : return DeriveNewSeed(key);
1221 : 3 : }
1222 : :
1223 : 3 : CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
1224 : : {
1225 : 3 : int64_t nCreationTime = GetTime();
1226 : 3 : CKeyMetadata metadata(nCreationTime);
1227 : :
1228 : : // calculate the seed
1229 [ + - ]: 3 : CPubKey seed = key.GetPubKey();
1230 [ + - - + ]: 3 : assert(key.VerifyPubKey(seed));
1231 : :
1232 : : // set the hd keypath to "s" -> Seed, refers the seed to itself
1233 [ + - ]: 3 : metadata.hdKeypath = "s";
1234 : 3 : metadata.has_key_origin = false;
1235 [ + - ]: 3 : metadata.hd_seed_id = seed.GetID();
1236 : :
1237 : 3 : {
1238 [ + - ]: 3 : LOCK(cs_KeyStore);
1239 : :
1240 : : // mem store the metadata
1241 [ + - + - : 3 : mapKeyMetadata[seed.GetID()] = metadata;
+ - ]
1242 : :
1243 : : // write the key&metadata to the database
1244 [ + - - + ]: 3 : if (!AddKeyPubKey(key, seed))
1245 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1246 : 0 : }
1247 : :
1248 : 3 : return seed;
1249 : 3 : }
1250 : :
1251 : 3 : void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
1252 : : {
1253 : 3 : LOCK(cs_KeyStore);
1254 : : // store the keyid (hash160) together with
1255 : : // the child index counter in the database
1256 : : // as a hdchain object
1257 : 3 : CHDChain newHdChain;
1258 [ + - + - ]: 3 : newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1259 [ + - ]: 3 : newHdChain.seed_id = seed.GetID();
1260 [ + - ]: 3 : AddHDChain(newHdChain);
1261 [ + - ]: 3 : NotifyCanGetAddressesChanged();
1262 [ + - + - ]: 3 : WalletBatch batch(m_storage.GetDatabase());
1263 [ + - ]: 3 : m_storage.UnsetBlankWalletFlag(batch);
1264 [ + - ]: 6 : }
1265 : :
1266 : : /**
1267 : : * Mark old keypool keys as used,
1268 : : * and generate all new keys
1269 : : */
1270 : 3 : bool LegacyScriptPubKeyMan::NewKeyPool()
1271 : : {
1272 [ + - ]: 3 : if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
1273 : : return false;
1274 : : }
1275 : 3 : {
1276 : 3 : LOCK(cs_KeyStore);
1277 [ + - + - ]: 3 : WalletBatch batch(m_storage.GetDatabase());
1278 : :
1279 [ - + ]: 3 : for (const int64_t nIndex : setInternalKeyPool) {
1280 [ # # ]: 0 : batch.ErasePool(nIndex);
1281 : : }
1282 : 3 : setInternalKeyPool.clear();
1283 : :
1284 [ + + ]: 1002 : for (const int64_t nIndex : setExternalKeyPool) {
1285 [ + - ]: 999 : batch.ErasePool(nIndex);
1286 : : }
1287 : 3 : setExternalKeyPool.clear();
1288 : :
1289 [ - + ]: 3 : for (const int64_t nIndex : set_pre_split_keypool) {
1290 [ # # ]: 0 : batch.ErasePool(nIndex);
1291 : : }
1292 : 3 : set_pre_split_keypool.clear();
1293 : :
1294 : 3 : m_pool_key_to_index.clear();
1295 : :
1296 [ + - - + ]: 3 : if (!TopUp()) {
1297 : 0 : return false;
1298 : : }
1299 [ + - ]: 3 : WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1300 [ - - + - ]: 3 : }
1301 : 3 : return true;
1302 : : }
1303 : :
1304 : 6 : bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
1305 : : {
1306 [ + + ]: 6 : if (!CanGenerateKeys()) {
1307 : : return false;
1308 : : }
1309 : :
1310 : 4 : WalletBatch batch(m_storage.GetDatabase());
1311 [ + - + - ]: 4 : if (!batch.TxnBegin()) return false;
1312 [ + - + - ]: 4 : if (!TopUpChain(batch, m_hd_chain, kpSize)) {
1313 : : return false;
1314 : : }
1315 [ + - + + ]: 5 : for (auto& [chain_id, chain] : m_inactive_hd_chains) {
1316 [ + - + - ]: 1 : if (!TopUpChain(batch, chain, kpSize)) {
1317 : : return false;
1318 : : }
1319 : : }
1320 [ + - - + : 4 : if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
- - - - -
- ]
1321 [ + - ]: 4 : NotifyCanGetAddressesChanged();
1322 : : // Note: Unlike with DescriptorSPKM, LegacySPKM does not need to call
1323 : : // m_storage.TopUpCallback() as we do not know what new scripts the LegacySPKM is
1324 : : // watching for. CWallet's scriptPubKey cache is not used for LegacySPKMs.
1325 : : return true;
1326 : 4 : }
1327 : :
1328 : 5 : bool LegacyScriptPubKeyMan::TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int kpSize)
1329 : : {
1330 : 5 : LOCK(cs_KeyStore);
1331 : :
1332 [ + - + - ]: 5 : if (m_storage.IsLocked()) return false;
1333 : :
1334 : : // Top up key pool
1335 : 5 : unsigned int nTargetSize;
1336 [ + - ]: 5 : if (kpSize > 0) {
1337 : : nTargetSize = kpSize;
1338 : : } else {
1339 : 5 : nTargetSize = m_keypool_size;
1340 : : }
1341 [ + - ]: 5 : int64_t target = std::max((int64_t) nTargetSize, int64_t{1});
1342 : :
1343 : : // count amount of available keys (internal, external)
1344 : : // make sure the keypool of external and internal keys fits the user selected target (-keypool)
1345 : 5 : int64_t missingExternal;
1346 : 5 : int64_t missingInternal;
1347 [ + + ]: 5 : if (chain == m_hd_chain) {
1348 [ + - ]: 4 : missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
1349 [ + - ]: 8 : missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
1350 : : } else {
1351 [ + - ]: 1 : missingExternal = std::max(target - (chain.nExternalChainCounter - chain.m_next_external_index), int64_t{0});
1352 [ + - ]: 2 : missingInternal = std::max(target - (chain.nInternalChainCounter - chain.m_next_internal_index), int64_t{0});
1353 : : }
1354 : :
1355 [ + - + - : 5 : if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
+ - + - ]
1356 : : // don't create extra internal keys
1357 : 5 : missingInternal = 0;
1358 : : }
1359 : 5 : bool internal = false;
1360 [ + + ]: 2009 : for (int64_t i = missingInternal + missingExternal; i--;) {
1361 [ - + ]: 2004 : if (i < missingInternal) {
1362 : 0 : internal = true;
1363 : : }
1364 : :
1365 [ + - ]: 2004 : CPubKey pubkey(GenerateNewKey(batch, chain, internal));
1366 [ + - ]: 2004 : if (chain == m_hd_chain) {
1367 [ + - ]: 2004 : AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1368 : : }
1369 : : }
1370 [ + + ]: 5 : if (missingInternal + missingExternal > 0) {
1371 [ + - ]: 3 : if (chain == m_hd_chain) {
1372 [ + - ]: 3 : 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());
1373 : : } else {
1374 [ # # # # ]: 0 : WalletLogPrintf("inactive seed with id %s added %d external keys, %d internal keys\n", HexStr(chain.seed_id), missingExternal, missingInternal);
1375 : : }
1376 : : }
1377 : : return true;
1378 : 5 : }
1379 : :
1380 : 2004 : void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
1381 : : {
1382 : 2004 : LOCK(cs_KeyStore);
1383 [ - + ]: 2004 : assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
1384 : 2004 : int64_t index = ++m_max_keypool_index;
1385 [ + - + - : 2004 : if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
- + ]
1386 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
1387 : : }
1388 [ - + ]: 2004 : if (internal) {
1389 [ # # ]: 0 : setInternalKeyPool.insert(index);
1390 : : } else {
1391 [ + - ]: 2004 : setExternalKeyPool.insert(index);
1392 : : }
1393 [ + - + - : 2004 : m_pool_key_to_index[pubkey.GetID()] = index;
+ - ]
1394 : 2004 : }
1395 : :
1396 : 1 : void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
1397 : : {
1398 [ - + ]: 1 : assert(type != OutputType::BECH32M);
1399 : : // Remove from key pool
1400 : 1 : WalletBatch batch(m_storage.GetDatabase());
1401 [ + - ]: 1 : batch.ErasePool(nIndex);
1402 [ + - ]: 1 : CPubKey pubkey;
1403 [ + - + - ]: 1 : bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1404 [ - + ]: 1 : assert(have_pk);
1405 [ + - ]: 1 : LearnRelatedScripts(pubkey, type);
1406 : 1 : m_index_to_reserved_key.erase(nIndex);
1407 [ + - ]: 1 : WalletLogPrintf("keypool keep %d\n", nIndex);
1408 : 1 : }
1409 : :
1410 : 0 : void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
1411 : : {
1412 : : // Return to key pool
1413 : 0 : {
1414 : 0 : LOCK(cs_KeyStore);
1415 [ # # ]: 0 : if (fInternal) {
1416 [ # # ]: 0 : setInternalKeyPool.insert(nIndex);
1417 [ # # ]: 0 : } else if (!set_pre_split_keypool.empty()) {
1418 [ # # ]: 0 : set_pre_split_keypool.insert(nIndex);
1419 : : } else {
1420 [ # # ]: 0 : setExternalKeyPool.insert(nIndex);
1421 : : }
1422 [ # # ]: 0 : CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
1423 [ # # ]: 0 : m_pool_key_to_index[pubkey_id] = nIndex;
1424 : 0 : m_index_to_reserved_key.erase(nIndex);
1425 [ # # ]: 0 : NotifyCanGetAddressesChanged();
1426 : 0 : }
1427 : 0 : WalletLogPrintf("keypool return %d\n", nIndex);
1428 : 0 : }
1429 : :
1430 : 2 : bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type)
1431 : : {
1432 [ - + ]: 2 : assert(type != OutputType::BECH32M);
1433 [ + + ]: 2 : if (!CanGetAddresses(/*internal=*/ false)) {
1434 : : return false;
1435 : : }
1436 : :
1437 : 1 : CKeyPool keypool;
1438 : 1 : {
1439 : 1 : LOCK(cs_KeyStore);
1440 : 1 : int64_t nIndex;
1441 [ + - - + : 1 : if (!ReserveKeyFromKeyPool(nIndex, keypool, /*fRequestedInternal=*/ false) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
- - - - ]
1442 [ # # # # ]: 0 : if (m_storage.IsLocked()) return false;
1443 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
1444 [ # # ]: 0 : result = GenerateNewKey(batch, m_hd_chain, /*internal=*/ false);
1445 : 0 : return true;
1446 : 0 : }
1447 [ + - ]: 1 : KeepDestination(nIndex, type);
1448 [ + - ]: 1 : result = keypool.vchPubKey;
1449 : 0 : }
1450 : 1 : return true;
1451 : : }
1452 : :
1453 : 1 : bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
1454 : : {
1455 : 1 : nIndex = -1;
1456 : 1 : keypool.vchPubKey = CPubKey();
1457 : 1 : {
1458 : 1 : LOCK(cs_KeyStore);
1459 : :
1460 : 1 : bool fReturningInternal = fRequestedInternal;
1461 [ + - + - : 1 : fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
+ - + - +
- - + ]
1462 [ + - ]: 1 : bool use_split_keypool = set_pre_split_keypool.empty();
1463 [ + - - + ]: 1 : std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1464 : :
1465 : : // Get the oldest key
1466 [ - + ]: 1 : if (setKeyPool.empty()) {
1467 [ # # ]: 0 : return false;
1468 : : }
1469 : :
1470 [ + - + - ]: 1 : WalletBatch batch(m_storage.GetDatabase());
1471 : :
1472 : 1 : auto it = setKeyPool.begin();
1473 : 1 : nIndex = *it;
1474 : 1 : setKeyPool.erase(it);
1475 [ + - - + ]: 1 : if (!batch.ReadPool(nIndex, keypool)) {
1476 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": read failed");
1477 : : }
1478 [ + - ]: 1 : CPubKey pk;
1479 [ + - + - : 1 : if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
- + ]
1480 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
1481 : : }
1482 : : // If the key was pre-split keypool, we don't care about what type it is
1483 [ + - - + ]: 1 : if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1484 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
1485 : : }
1486 [ - + ]: 1 : if (!keypool.vchPubKey.IsValid()) {
1487 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
1488 : : }
1489 : :
1490 [ - + ]: 1 : assert(m_index_to_reserved_key.count(nIndex) == 0);
1491 [ + - + - ]: 1 : m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1492 [ + - ]: 1 : m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1493 [ + - ]: 1 : WalletLogPrintf("keypool reserve %d\n", nIndex);
1494 [ + - ]: 1 : }
1495 : 1 : NotifyCanGetAddressesChanged();
1496 : 1 : return true;
1497 : : }
1498 : :
1499 : 2 : void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
1500 : : {
1501 [ - + ]: 2 : assert(type != OutputType::BECH32M);
1502 [ + - - + ]: 2 : if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
1503 [ # # ]: 0 : CTxDestination witdest = WitnessV0KeyHash(key.GetID());
1504 [ # # ]: 0 : CScript witprog = GetScriptForDestination(witdest);
1505 : : // Make sure the resulting program is solvable.
1506 [ # # ]: 0 : const auto desc = InferDescriptor(witprog, *this);
1507 [ # # # # : 0 : assert(desc && desc->IsSolvable());
# # ]
1508 [ # # ]: 0 : AddCScript(witprog);
1509 : 0 : }
1510 : 2 : }
1511 : :
1512 : 0 : void LegacyScriptPubKeyMan::LearnAllRelatedScripts(const CPubKey& key)
1513 : : {
1514 : : // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
1515 : 0 : LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
1516 : 0 : }
1517 : :
1518 : 0 : std::vector<CKeyPool> LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
1519 : : {
1520 : 0 : AssertLockHeld(cs_KeyStore);
1521 : 0 : bool internal = setInternalKeyPool.count(keypool_id);
1522 [ # # # # : 0 : if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
# # ]
1523 [ # # ]: 0 : std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
1524 [ # # ]: 0 : auto it = setKeyPool->begin();
1525 : :
1526 : 0 : std::vector<CKeyPool> result;
1527 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
1528 : 0 : while (it != std::end(*setKeyPool)) {
1529 [ # # ]: 0 : const int64_t& index = *(it);
1530 [ # # ]: 0 : if (index > keypool_id) break; // set*KeyPool is ordered
1531 : :
1532 [ # # ]: 0 : CKeyPool keypool;
1533 [ # # # # ]: 0 : if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
1534 [ # # ]: 0 : m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1535 : : }
1536 [ # # ]: 0 : LearnAllRelatedScripts(keypool.vchPubKey);
1537 [ # # ]: 0 : batch.ErasePool(index);
1538 [ # # ]: 0 : WalletLogPrintf("keypool index %d removed\n", index);
1539 : 0 : it = setKeyPool->erase(it);
1540 [ # # # # ]: 0 : result.push_back(std::move(keypool));
1541 : : }
1542 : :
1543 : 0 : return result;
1544 : 0 : }
1545 : :
1546 : 4 : std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
1547 : : {
1548 : 4 : std::vector<CScript> dummy;
1549 : 4 : FlatSigningProvider out;
1550 [ + - + - ]: 4 : InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1551 : 4 : std::vector<CKeyID> ret;
1552 [ + - ]: 4 : ret.reserve(out.pubkeys.size());
1553 [ - + ]: 4 : for (const auto& entry : out.pubkeys) {
1554 [ # # ]: 0 : ret.push_back(entry.first);
1555 : : }
1556 : 4 : return ret;
1557 : 4 : }
1558 : :
1559 : 0 : void LegacyScriptPubKeyMan::MarkPreSplitKeys()
1560 : : {
1561 : 0 : WalletBatch batch(m_storage.GetDatabase());
1562 [ # # ]: 0 : for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
1563 [ # # ]: 0 : int64_t index = *it;
1564 [ # # ]: 0 : CKeyPool keypool;
1565 [ # # # # ]: 0 : if (!batch.ReadPool(index, keypool)) {
1566 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
1567 : : }
1568 : 0 : keypool.m_pre_split = true;
1569 [ # # # # ]: 0 : if (!batch.WritePool(index, keypool)) {
1570 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
1571 : : }
1572 [ # # ]: 0 : set_pre_split_keypool.insert(index);
1573 : 0 : it = setExternalKeyPool.erase(it);
1574 : : }
1575 : 0 : }
1576 : :
1577 : 23 : bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
1578 : : {
1579 : 23 : WalletBatch batch(m_storage.GetDatabase());
1580 [ + - ]: 23 : return AddCScriptWithDB(batch, redeemScript);
1581 : 23 : }
1582 : :
1583 : 23 : bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
1584 : : {
1585 [ + - ]: 23 : if (!FillableSigningProvider::AddCScript(redeemScript))
1586 : : return false;
1587 [ + - ]: 23 : if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1588 : 23 : m_storage.UnsetBlankWalletFlag(batch);
1589 : 23 : return true;
1590 : : }
1591 : : return false;
1592 : : }
1593 : :
1594 : 0 : bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info)
1595 : : {
1596 : 0 : LOCK(cs_KeyStore);
1597 [ # # # # ]: 0 : std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1598 [ # # # # : 0 : mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
# # ]
1599 [ # # # # ]: 0 : mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1600 [ # # # # : 0 : mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path, /*apostrophe=*/true);
# # ]
1601 [ # # # # : 0 : return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
# # # # ]
1602 : 0 : }
1603 : :
1604 : 3 : bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1605 : : {
1606 : 3 : WalletBatch batch(m_storage.GetDatabase());
1607 [ + + ]: 4 : for (const auto& entry : scripts) {
1608 [ + - ]: 1 : CScriptID id(entry);
1609 [ + - + - ]: 1 : if (HaveCScript(id)) {
1610 [ + - + - : 2 : WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
+ - ]
1611 : 1 : continue;
1612 : : }
1613 [ # # # # ]: 0 : if (!AddCScriptWithDB(batch, entry)) {
1614 : : return false;
1615 : : }
1616 : :
1617 [ # # ]: 0 : if (timestamp > 0) {
1618 [ # # # # ]: 0 : m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1619 : : }
1620 : : }
1621 [ + + ]: 3 : if (timestamp > 0) {
1622 [ + - ]: 2 : UpdateTimeFirstKey(timestamp);
1623 : : }
1624 : :
1625 : : return true;
1626 : 3 : }
1627 : :
1628 : 3 : bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1629 : : {
1630 : 3 : WalletBatch batch(m_storage.GetDatabase());
1631 [ + + ]: 4 : for (const auto& entry : privkey_map) {
1632 : 1 : const CKey& key = entry.second;
1633 [ + - ]: 1 : CPubKey pubkey = key.GetPubKey();
1634 : 1 : const CKeyID& id = entry.first;
1635 [ + - - + ]: 1 : assert(key.VerifyPubKey(pubkey));
1636 : : // Skip if we already have the key
1637 [ + - - + ]: 1 : if (HaveKey(id)) {
1638 [ # # # # ]: 0 : WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
1639 : 0 : continue;
1640 : : }
1641 [ + - ]: 1 : mapKeyMetadata[id].nCreateTime = timestamp;
1642 : : // If the private key is not present in the wallet, insert it.
1643 [ + - + - ]: 1 : if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1644 : : return false;
1645 : : }
1646 [ + - ]: 1 : UpdateTimeFirstKey(timestamp);
1647 : : }
1648 : : return true;
1649 : 3 : }
1650 : :
1651 : 2 : bool LegacyScriptPubKeyMan::ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const int64_t timestamp)
1652 : : {
1653 : 2 : WalletBatch batch(m_storage.GetDatabase());
1654 [ - + ]: 2 : for (const auto& entry : key_origins) {
1655 [ # # ]: 0 : AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1656 : : }
1657 [ - + ]: 2 : for (const auto& [id, internal] : ordered_pubkeys) {
1658 : 0 : auto entry = pubkey_map.find(id);
1659 [ # # ]: 0 : if (entry == pubkey_map.end()) {
1660 : 0 : continue;
1661 : : }
1662 [ # # ]: 0 : const CPubKey& pubkey = entry->second;
1663 [ # # ]: 0 : CPubKey temp;
1664 [ # # # # ]: 0 : if (GetPubKey(id, temp)) {
1665 : : // Already have pubkey, skipping
1666 [ # # # # ]: 0 : WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1667 : 0 : continue;
1668 : : }
1669 [ # # # # : 0 : if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
# # ]
1670 : : return false;
1671 : : }
1672 [ # # ]: 0 : mapKeyMetadata[id].nCreateTime = timestamp;
1673 : :
1674 : : // Add to keypool only works with pubkeys
1675 [ # # ]: 0 : if (add_keypool) {
1676 [ # # ]: 0 : AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1677 [ # # ]: 0 : NotifyCanGetAddressesChanged();
1678 : : }
1679 : : }
1680 : : return true;
1681 : 2 : }
1682 : :
1683 : 2 : bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
1684 : : {
1685 : 2 : WalletBatch batch(m_storage.GetDatabase());
1686 [ + + ]: 4 : for (const CScript& script : script_pub_keys) {
1687 [ - + - - : 2 : if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
- - ]
1688 [ + - + - ]: 2 : if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1689 : : return false;
1690 : : }
1691 : : }
1692 : : }
1693 : : return true;
1694 : 2 : }
1695 : :
1696 : 1 : std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
1697 : : {
1698 : 1 : LOCK(cs_KeyStore);
1699 [ + - + - ]: 1 : if (!m_storage.HasEncryptionKeys()) {
1700 [ + - ]: 1 : return FillableSigningProvider::GetKeys();
1701 : : }
1702 : 0 : std::set<CKeyID> set_address;
1703 [ # # ]: 0 : for (const auto& mi : mapCryptedKeys) {
1704 [ # # ]: 0 : set_address.insert(mi.first);
1705 : : }
1706 : 0 : return set_address;
1707 : 1 : }
1708 : :
1709 : 93 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
1710 : : {
1711 : 93 : LOCK(cs_KeyStore);
1712 [ + - ]: 93 : std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
1713 : :
1714 : : // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
1715 : 384 : const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
1716 [ + - ]: 291 : candidate_spks.insert(GetScriptForRawPubKey(pub));
1717 [ + - ]: 582 : candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
1718 : :
1719 [ + - ]: 291 : CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
1720 [ + - ]: 291 : candidate_spks.insert(wpkh);
1721 [ + - + - ]: 582 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
1722 : 291 : };
1723 [ + - + + ]: 372 : for (const auto& [_, key] : mapKeys) {
1724 [ + - + - ]: 279 : add_pubkey(key.GetPubKey());
1725 : : }
1726 [ + - + + ]: 105 : for (const auto& [_, ckeypair] : mapCryptedKeys) {
1727 [ + - ]: 12 : add_pubkey(ckeypair.first);
1728 : : }
1729 : :
1730 : : // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
1731 : : // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
1732 : : // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
1733 : : // Callers of this function will need to remove such scripts.
1734 : 559 : const auto& add_script = [&candidate_spks](const CScript& script) -> void {
1735 : 466 : candidate_spks.insert(script);
1736 [ + - ]: 932 : candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
1737 : :
1738 [ + - ]: 466 : CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
1739 [ + - ]: 466 : candidate_spks.insert(wsh);
1740 [ + - + - ]: 932 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
1741 : 466 : };
1742 [ + - + + ]: 471 : for (const auto& [_, script] : mapScripts) {
1743 [ + - ]: 378 : add_script(script);
1744 : : }
1745 : :
1746 : : // Although setWatchOnly should only contain output scripts, we will also include each script's
1747 : : // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
1748 [ + + ]: 181 : for (const auto& script : setWatchOnly) {
1749 [ + - ]: 88 : add_script(script);
1750 : : }
1751 : :
1752 [ + - ]: 93 : return candidate_spks;
1753 : 93 : }
1754 : :
1755 : 65 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
1756 : : {
1757 : : // Run IsMine() on each candidate output script. Any script that is not ISMINE_NO is an output
1758 : : // script to return.
1759 : : // This both filters out things that are not watched by the wallet, and things that are invalid.
1760 : 65 : std::unordered_set<CScript, SaltedSipHasher> spks;
1761 [ + - + + ]: 1320 : for (const CScript& script : GetCandidateScriptPubKeys()) {
1762 [ + - + + ]: 1255 : if (IsMine(script) != ISMINE_NO) {
1763 [ + - ]: 707 : spks.insert(script);
1764 : : }
1765 : 0 : }
1766 : :
1767 : 65 : return spks;
1768 : 0 : }
1769 : :
1770 : 27 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
1771 : : {
1772 : 27 : LOCK(cs_KeyStore);
1773 [ + - ]: 27 : std::unordered_set<CScript, SaltedSipHasher> spks;
1774 [ + + ]: 70 : for (const CScript& script : setWatchOnly) {
1775 [ + - + + : 43 : if (IsMine(script) == ISMINE_NO) spks.insert(script);
+ - ]
1776 : : }
1777 [ + - ]: 27 : return spks;
1778 : 27 : }
1779 : :
1780 : 28 : std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
1781 : : {
1782 : 28 : LOCK(cs_KeyStore);
1783 [ + - - + ]: 28 : if (m_storage.IsLocked()) {
1784 : 0 : return std::nullopt;
1785 : : }
1786 : :
1787 : 28 : MigrationData out;
1788 : :
1789 [ + - ]: 28 : std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
1790 : :
1791 : : // Get all key ids
1792 : 28 : std::set<CKeyID> keyids;
1793 [ + + ]: 148 : for (const auto& key_pair : mapKeys) {
1794 [ + - ]: 120 : keyids.insert(key_pair.first);
1795 : : }
1796 [ + + ]: 34 : for (const auto& key_pair : mapCryptedKeys) {
1797 [ + - ]: 6 : keyids.insert(key_pair.first);
1798 : : }
1799 : :
1800 : : // Get key metadata and figure out which keys don't have a seed
1801 : : // Note that we do not ignore the seeds themselves because they are considered IsMine!
1802 [ + + ]: 154 : for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
1803 : 126 : const CKeyID& keyid = *keyid_it;
1804 : 126 : const auto& it = mapKeyMetadata.find(keyid);
1805 [ + - ]: 126 : if (it != mapKeyMetadata.end()) {
1806 [ + + ]: 126 : const CKeyMetadata& meta = it->second;
1807 [ + + + + ]: 126 : if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
1808 : 26 : keyid_it++;
1809 : 26 : continue;
1810 : : }
1811 [ + + + + : 100 : if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.count(meta.hd_seed_id) > 0)) {
+ - + - ]
1812 : 96 : keyid_it = keyids.erase(keyid_it);
1813 : 96 : continue;
1814 : : }
1815 : : }
1816 : 4 : keyid_it++;
1817 : : }
1818 : :
1819 [ + - + - ]: 28 : WalletBatch batch(m_storage.GetDatabase());
1820 [ + - - + ]: 28 : if (!batch.TxnBegin()) {
1821 [ # # ]: 0 : LogPrintf("Error generating descriptors for migration, cannot initialize db transaction\n");
1822 : 0 : return std::nullopt;
1823 : : }
1824 : :
1825 : : // keyids is now all non-HD keys. Each key will have its own combo descriptor
1826 [ + + ]: 58 : for (const CKeyID& keyid : keyids) {
1827 : 30 : CKey key;
1828 [ + - - + ]: 30 : if (!GetKey(keyid, key)) {
1829 : 0 : assert(false);
1830 : : }
1831 : :
1832 : : // Get birthdate from key meta
1833 : 30 : uint64_t creation_time = 0;
1834 : 30 : const auto& it = mapKeyMetadata.find(keyid);
1835 [ + - ]: 30 : if (it != mapKeyMetadata.end()) {
1836 : 30 : creation_time = it->second.nCreateTime;
1837 : : }
1838 : :
1839 : : // Get the key origin
1840 : : // Maybe this doesn't matter because floating keys here shouldn't have origins
1841 [ + - ]: 30 : KeyOriginInfo info;
1842 [ + - ]: 30 : bool has_info = GetKeyOrigin(keyid, info);
1843 [ + - + - : 150 : std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
+ - + - +
- + - - -
+ - + - +
- - - - -
- - - - ]
1844 : :
1845 : : // Construct the combo descriptor
1846 [ + - + - : 60 : std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
+ - + - ]
1847 : 30 : FlatSigningProvider keys;
1848 [ + - ]: 30 : std::string error;
1849 [ + - ]: 30 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
1850 [ + - ]: 30 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
1851 [ + - + - : 30 : WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
+ - ]
1852 : :
1853 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1854 [ + - ]: 30 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1855 [ + - + - : 90 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
+ - ]
1856 [ + - ]: 30 : desc_spk_man->TopUpWithDB(batch);
1857 [ + - ]: 30 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
1858 : :
1859 : : // Remove the scriptPubKeys from our current set
1860 [ + + ]: 148 : for (const CScript& spk : desc_spks) {
1861 [ + - ]: 118 : size_t erased = spks.erase(spk);
1862 [ - + ]: 118 : assert(erased == 1);
1863 [ + - - + ]: 118 : assert(IsMine(spk) == ISMINE_SPENDABLE);
1864 : : }
1865 : :
1866 [ + - ]: 30 : out.desc_spkms.push_back(std::move(desc_spk_man));
1867 : 30 : }
1868 : :
1869 : : // Handle HD keys by using the CHDChains
1870 : 28 : std::vector<CHDChain> chains;
1871 [ + - ]: 28 : chains.push_back(m_hd_chain);
1872 [ + + ]: 30 : for (const auto& chain_pair : m_inactive_hd_chains) {
1873 [ + - ]: 2 : chains.push_back(chain_pair.second);
1874 : : }
1875 [ + + ]: 58 : for (const CHDChain& chain : chains) {
1876 [ + + ]: 90 : for (int i = 0; i < 2; ++i) {
1877 : : // Skip if doing internal chain and split chain is not supported
1878 [ + + + + : 60 : if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
+ - - + ]
1879 : 10 : continue;
1880 : : }
1881 : : // Get the master xprv
1882 : 50 : CKey seed_key;
1883 [ + - - + ]: 50 : if (!GetKey(chain.seed_id, seed_key)) {
1884 : 0 : assert(false);
1885 : : }
1886 [ + - ]: 50 : CExtKey master_key;
1887 [ + - + - ]: 100 : master_key.SetSeed(seed_key);
1888 : :
1889 : : // Make the combo descriptor
1890 [ + - + - ]: 50 : std::string xpub = EncodeExtPubKey(master_key.Neuter());
1891 [ + - + - : 150 : std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
+ - ]
1892 : 50 : FlatSigningProvider keys;
1893 [ + - ]: 50 : std::string error;
1894 [ + - ]: 50 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
1895 [ + - ]: 50 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
1896 [ + + ]: 50 : uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
1897 [ + - + - : 50 : WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
+ - ]
1898 : :
1899 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1900 [ + - ]: 50 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1901 [ + - + - : 150 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
+ - ]
1902 [ + - ]: 50 : desc_spk_man->TopUpWithDB(batch);
1903 [ + - ]: 50 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
1904 : :
1905 : : // Remove the scriptPubKeys from our current set
1906 [ + + ]: 434 : for (const CScript& spk : desc_spks) {
1907 [ + - ]: 384 : size_t erased = spks.erase(spk);
1908 [ - + ]: 384 : assert(erased == 1);
1909 [ + - - + ]: 384 : assert(IsMine(spk) == ISMINE_SPENDABLE);
1910 : : }
1911 : :
1912 [ + - ]: 50 : out.desc_spkms.push_back(std::move(desc_spk_man));
1913 : 50 : }
1914 : : }
1915 : : // Add the current master seed to the migration data
1916 [ + + ]: 28 : if (!m_hd_chain.seed_id.IsNull()) {
1917 : 23 : CKey seed_key;
1918 [ + - - + ]: 23 : if (!GetKey(m_hd_chain.seed_id, seed_key)) {
1919 : 0 : assert(false);
1920 : : }
1921 [ + - + - ]: 46 : out.master_key.SetSeed(seed_key);
1922 : 23 : }
1923 : :
1924 : : // Handle the rest of the scriptPubKeys which must be imports and may not have all info
1925 [ + + ]: 84 : for (auto it = spks.begin(); it != spks.end();) {
1926 [ + - ]: 56 : const CScript& spk = *it;
1927 : :
1928 : : // Get birthdate from script meta
1929 : 56 : uint64_t creation_time = 0;
1930 [ + - ]: 56 : const auto& mit = m_script_metadata.find(CScriptID(spk));
1931 [ + + ]: 56 : if (mit != m_script_metadata.end()) {
1932 : 39 : creation_time = mit->second.nCreateTime;
1933 : : }
1934 : :
1935 : : // InferDescriptor as that will get us all the solving info if it is there
1936 [ + - + - ]: 112 : std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
1937 : :
1938 : : // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
1939 : : // Re-parse the descriptors to detect that, and skip any that do not parse.
1940 : 56 : {
1941 [ + - ]: 56 : std::string desc_str = desc->ToString();
1942 : 56 : FlatSigningProvider parsed_keys;
1943 [ + - ]: 56 : std::string parse_error;
1944 [ + - ]: 56 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
1945 [ - + ]: 56 : if (parsed_descs.empty()) {
1946 : : // Remove this scriptPubKey from the set
1947 : 0 : it = spks.erase(it);
1948 : 0 : continue;
1949 : : }
1950 : 56 : }
1951 : :
1952 : : // Get the private keys for this descriptor
1953 : 56 : std::vector<CScript> scripts;
1954 : 56 : FlatSigningProvider keys;
1955 [ + - - + ]: 56 : if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
1956 : 0 : assert(false);
1957 : : }
1958 : 56 : std::set<CKeyID> privkeyids;
1959 [ + + ]: 108 : for (const auto& key_orig_pair : keys.origins) {
1960 [ + - ]: 52 : privkeyids.insert(key_orig_pair.first);
1961 : : }
1962 : :
1963 : 56 : std::vector<CScript> desc_spks;
1964 : :
1965 : : // Make the descriptor string with private keys
1966 [ + - ]: 56 : std::string desc_str;
1967 [ + - ]: 56 : bool watchonly = !desc->ToPrivateString(*this, desc_str);
1968 [ + + + - : 56 : if (watchonly && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
+ + ]
1969 [ + - + - ]: 35 : out.watch_descs.emplace_back(desc->ToString(), creation_time);
1970 : :
1971 : : // Get the scriptPubKeys without writing this to the wallet
1972 : 35 : FlatSigningProvider provider;
1973 [ + - ]: 35 : desc->Expand(0, provider, desc_spks, provider);
1974 : 35 : } else {
1975 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1976 [ + - + - ]: 21 : WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1977 [ + - ]: 21 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1978 [ + + ]: 48 : for (const auto& keyid : privkeyids) {
1979 : 27 : CKey key;
1980 [ + - + + ]: 27 : if (!GetKey(keyid, key)) {
1981 : 9 : continue;
1982 : : }
1983 [ + - + - : 54 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
+ - ]
1984 : 27 : }
1985 [ + - ]: 21 : desc_spk_man->TopUpWithDB(batch);
1986 [ + - ]: 21 : auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
1987 [ + - ]: 21 : desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
1988 : :
1989 [ + - ]: 21 : out.desc_spkms.push_back(std::move(desc_spk_man));
1990 : 21 : }
1991 : :
1992 : : // Remove the scriptPubKeys from our current set
1993 [ + + ]: 112 : for (const CScript& desc_spk : desc_spks) {
1994 [ + - ]: 56 : auto del_it = spks.find(desc_spk);
1995 [ - + ]: 56 : assert(del_it != spks.end());
1996 [ + - - + ]: 56 : assert(IsMine(desc_spk) != ISMINE_NO);
1997 : 56 : it = spks.erase(del_it);
1998 : : }
1999 : 56 : }
2000 : :
2001 : : // Make sure that we have accounted for all scriptPubKeys
2002 [ - + ]: 28 : if (!Assume(spks.empty())) {
2003 [ # # # # ]: 0 : LogPrintf("%s\n", STR_INTERNAL_BUG("Error: Some output scripts were not migrated.\n"));
2004 : 0 : return std::nullopt;
2005 : : }
2006 : :
2007 : : // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
2008 : : // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
2009 : : // be put into the separate "solvables" wallet.
2010 : : // These can be detected by going through the entire candidate output scripts, finding the ISMINE_NO scripts,
2011 : : // and checking CanProvide() which will dummy sign.
2012 [ + - + + ]: 998 : for (const CScript& script : GetCandidateScriptPubKeys()) {
2013 : : // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
2014 [ + - + + : 970 : if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
+ - + + ]
2015 : 416 : continue;
2016 : : }
2017 [ + - + + ]: 554 : if (IsMine(script) != ISMINE_NO) {
2018 : 153 : continue;
2019 : : }
2020 : 401 : SignatureData dummy_sigdata;
2021 [ + - + + ]: 401 : if (!CanProvide(script, dummy_sigdata)) {
2022 : 376 : continue;
2023 : : }
2024 : :
2025 : : // Get birthdate from script meta
2026 : 25 : uint64_t creation_time = 0;
2027 [ + - ]: 25 : const auto& it = m_script_metadata.find(CScriptID(script));
2028 [ + + ]: 25 : if (it != m_script_metadata.end()) {
2029 : 4 : creation_time = it->second.nCreateTime;
2030 : : }
2031 : :
2032 : : // InferDescriptor as that will get us all the solving info if it is there
2033 [ + - + - ]: 25 : std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
2034 [ + - + + ]: 25 : if (!desc->IsSolvable()) {
2035 : : // The wallet was able to provide some information, but not enough to make a descriptor that actually
2036 : : // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
2037 : 10 : continue;
2038 : : }
2039 : :
2040 : : // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
2041 : : // Re-parse the descriptors to detect that, and skip any that do not parse.
2042 : 15 : {
2043 [ + - ]: 15 : std::string desc_str = desc->ToString();
2044 : 15 : FlatSigningProvider parsed_keys;
2045 [ + - ]: 15 : std::string parse_error;
2046 [ + - ]: 15 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
2047 [ - + ]: 15 : if (parsed_descs.empty()) {
2048 : 0 : continue;
2049 : : }
2050 : 15 : }
2051 : :
2052 [ + - + - ]: 15 : out.solvable_descs.emplace_back(desc->ToString(), creation_time);
2053 : 401 : }
2054 : :
2055 : : // Finalize transaction
2056 [ + - - + ]: 28 : if (!batch.TxnCommit()) {
2057 [ # # ]: 0 : LogPrintf("Error generating descriptors for migration, cannot commit db transaction\n");
2058 : 0 : return std::nullopt;
2059 : : }
2060 : :
2061 : 28 : return out;
2062 : 84 : }
2063 : :
2064 : 3 : bool LegacyDataSPKM::DeleteRecords()
2065 : : {
2066 [ + - + - ]: 3 : return RunWithinTxn(m_storage.GetDatabase(), /*process_desc=*/"delete legacy records", [&](WalletBatch& batch){
2067 : 3 : return DeleteRecordsWithDB(batch);
2068 : 3 : });
2069 : : }
2070 : :
2071 : 30 : bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
2072 : : {
2073 : 30 : LOCK(cs_KeyStore);
2074 [ + - + - ]: 30 : return batch.EraseRecords(DBKeys::LEGACY_TYPES);
2075 : 30 : }
2076 : :
2077 : 18178 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
2078 : : {
2079 : : // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
2080 [ - + ]: 18178 : if (!CanGetAddresses()) {
2081 : 0 : return util::Error{_("No addresses available")};
2082 : : }
2083 : 18178 : {
2084 : 18178 : LOCK(cs_desc_man);
2085 [ + - - + ]: 18178 : assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
2086 [ + - ]: 18178 : std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
2087 [ - + ]: 18178 : assert(desc_addr_type);
2088 [ - + ]: 18178 : if (type != *desc_addr_type) {
2089 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
2090 : : }
2091 : :
2092 [ + - ]: 18178 : TopUp();
2093 : :
2094 : : // Get the scriptPubKey from the descriptor
2095 : 18178 : FlatSigningProvider out_keys;
2096 : 18178 : std::vector<CScript> scripts_temp;
2097 [ - + - - : 18178 : if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
- - ]
2098 : : // We can't generate anymore keys
2099 [ # # ]: 0 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
2100 : : }
2101 [ + - + + ]: 18178 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2102 : : // We can't generate anymore keys
2103 [ + - ]: 24 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
2104 : : }
2105 : :
2106 : 18170 : CTxDestination dest;
2107 [ + - - + ]: 18170 : if (!ExtractDestination(scripts_temp[0], dest)) {
2108 [ # # ]: 0 : return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
2109 : : }
2110 : 18170 : m_wallet_descriptor.next_index++;
2111 [ + - + - : 18170 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
2112 : 18170 : return dest;
2113 [ + - ]: 36356 : }
2114 : : }
2115 : :
2116 : 761181 : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
2117 : : {
2118 : 761181 : LOCK(cs_desc_man);
2119 [ + + ]: 761181 : if (m_map_script_pub_keys.count(script) > 0) {
2120 : 761126 : return ISMINE_SPENDABLE;
2121 : : }
2122 : : return ISMINE_NO;
2123 : 761181 : }
2124 : :
2125 : 874 : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
2126 : : {
2127 : 874 : LOCK(cs_desc_man);
2128 [ + - ]: 874 : if (!m_map_keys.empty()) {
2129 : : return false;
2130 : : }
2131 : :
2132 : 874 : bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
2133 : 874 : bool keyFail = false;
2134 [ + + ]: 1089 : for (const auto& mi : m_map_crypted_keys) {
2135 : 736 : const CPubKey &pubkey = mi.second.first;
2136 : 736 : const std::vector<unsigned char> &crypted_secret = mi.second.second;
2137 : 736 : CKey key;
2138 [ + - + - ]: 736 : if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
2139 : : keyFail = true;
2140 : : break;
2141 : : }
2142 : 736 : keyPass = true;
2143 [ + + ]: 736 : if (m_decryption_thoroughly_checked)
2144 : : break;
2145 : 736 : }
2146 [ - + ]: 874 : if (keyPass && keyFail) {
2147 [ # # ]: 0 : LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
2148 [ # # ]: 0 : throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
2149 : : }
2150 [ + - ]: 874 : if (keyFail || !keyPass) {
2151 : : return false;
2152 : : }
2153 : 874 : m_decryption_thoroughly_checked = true;
2154 : 874 : return true;
2155 : 874 : }
2156 : :
2157 : 103 : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
2158 : : {
2159 : 103 : LOCK(cs_desc_man);
2160 [ + - ]: 103 : if (!m_map_crypted_keys.empty()) {
2161 : : return false;
2162 : : }
2163 : :
2164 [ + + ]: 206 : for (const KeyMap::value_type& key_in : m_map_keys)
2165 : : {
2166 : 103 : const CKey &key = key_in.second;
2167 [ + - ]: 103 : CPubKey pubkey = key.GetPubKey();
2168 [ + - + - : 309 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
2169 : 103 : std::vector<unsigned char> crypted_secret;
2170 [ + - + - : 103 : if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
- + ]
2171 : 0 : return false;
2172 : : }
2173 [ + - + - : 206 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
+ - ]
2174 [ + - + - ]: 103 : batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2175 : 103 : }
2176 : 103 : m_map_keys.clear();
2177 : 103 : return true;
2178 : 103 : }
2179 : :
2180 : 1906 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
2181 : : {
2182 : 1906 : LOCK(cs_desc_man);
2183 [ + - ]: 1906 : auto op_dest = GetNewDestination(type);
2184 : 1906 : index = m_wallet_descriptor.next_index - 1;
2185 [ + - ]: 1906 : return op_dest;
2186 : 1906 : }
2187 : :
2188 : 83 : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
2189 : : {
2190 : 83 : LOCK(cs_desc_man);
2191 : : // Only return when the index was the most recent
2192 [ + - ]: 83 : if (m_wallet_descriptor.next_index - 1 == index) {
2193 : 83 : m_wallet_descriptor.next_index--;
2194 : : }
2195 [ + - + - : 83 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
2196 [ + - ]: 83 : NotifyCanGetAddressesChanged();
2197 : 83 : }
2198 : :
2199 : 85538 : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
2200 : : {
2201 : 85538 : AssertLockHeld(cs_desc_man);
2202 [ + + + + ]: 85538 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
2203 : 2261 : KeyMap keys;
2204 [ + + ]: 4522 : for (const auto& key_pair : m_map_crypted_keys) {
2205 : 2261 : const CPubKey& pubkey = key_pair.second.first;
2206 : 2261 : const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
2207 : 2261 : CKey key;
2208 [ + - + - ]: 2261 : m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
2209 : 2261 : return DecryptKey(encryption_key, crypted_secret, pubkey, key);
2210 : : });
2211 [ + - + - : 2261 : keys[pubkey.GetID()] = key;
+ - ]
2212 : 2261 : }
2213 : : return keys;
2214 : 0 : }
2215 : 83277 : return m_map_keys;
2216 : : }
2217 : :
2218 : 225 : bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
2219 : : {
2220 : 225 : AssertLockHeld(cs_desc_man);
2221 [ + + + + ]: 225 : return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
2222 : : }
2223 : :
2224 : 72 : std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
2225 : : {
2226 : 72 : AssertLockHeld(cs_desc_man);
2227 [ + + + - ]: 72 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
2228 : 9 : const auto& it = m_map_crypted_keys.find(keyid);
2229 [ - + ]: 9 : if (it == m_map_crypted_keys.end()) {
2230 : 0 : return std::nullopt;
2231 : : }
2232 [ + - ]: 9 : const std::vector<unsigned char>& crypted_secret = it->second.second;
2233 : 9 : CKey key;
2234 [ + - + - : 18 : if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
- + ]
2235 : : return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
2236 : : }))) {
2237 : 0 : return std::nullopt;
2238 : : }
2239 : 9 : return key;
2240 : 9 : }
2241 : 63 : const auto& it = m_map_keys.find(keyid);
2242 [ + + ]: 63 : if (it == m_map_keys.end()) {
2243 : 1 : return std::nullopt;
2244 : : }
2245 : 62 : return it->second;
2246 : : }
2247 : :
2248 : 70160 : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
2249 : : {
2250 : 70160 : WalletBatch batch(m_storage.GetDatabase());
2251 [ + - + + ]: 70160 : if (!batch.TxnBegin()) return false;
2252 [ + - ]: 70159 : bool res = TopUpWithDB(batch, size);
2253 [ + - - + : 70159 : if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
- - - - -
- ]
2254 : : return res;
2255 : 70160 : }
2256 : :
2257 : 73230 : bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
2258 : : {
2259 : 73230 : LOCK(cs_desc_man);
2260 [ + + ]: 73230 : std::set<CScript> new_spks;
2261 : 73230 : unsigned int target_size;
2262 [ + + ]: 73230 : if (size > 0) {
2263 : : target_size = size;
2264 : : } else {
2265 : 73157 : target_size = m_keypool_size;
2266 : : }
2267 : :
2268 : : // Calculate the new range_end
2269 [ + + ]: 73230 : int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
2270 : :
2271 : : // If the descriptor is not ranged, we actually just want to fill the first cache item
2272 [ + - + + ]: 73230 : if (!m_wallet_descriptor.descriptor->IsRange()) {
2273 : 13316 : new_range_end = 1;
2274 : 13316 : m_wallet_descriptor.range_end = 1;
2275 : 13316 : m_wallet_descriptor.range_start = 0;
2276 : : }
2277 : :
2278 : 73230 : FlatSigningProvider provider;
2279 [ + - ]: 146460 : provider.keys = GetKeys();
2280 : :
2281 [ + - ]: 73230 : uint256 id = GetID();
2282 [ + + ]: 511026 : for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
2283 : 437903 : FlatSigningProvider out_keys;
2284 : 437903 : std::vector<CScript> scripts_temp;
2285 : 437903 : DescriptorCache temp_cache;
2286 : : // Maybe we have a cached xpub and we can expand from the cache first
2287 [ + - + + ]: 437903 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2288 [ + - + + ]: 14374 : if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
2289 : : }
2290 : : // Add all of the scriptPubKeys to the scriptPubKey set
2291 [ + - ]: 437796 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
2292 [ + + ]: 876523 : for (const CScript& script : scripts_temp) {
2293 [ + - ]: 438727 : m_map_script_pub_keys[script] = i;
2294 : : }
2295 [ + + ]: 859830 : for (const auto& pk_pair : out_keys.pubkeys) {
2296 : 422034 : const CPubKey& pubkey = pk_pair.second;
2297 [ + + ]: 422034 : if (m_map_pubkeys.count(pubkey) != 0) {
2298 : : // We don't need to give an error here.
2299 : : // 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
2300 : 5588 : continue;
2301 : : }
2302 [ + - ]: 416446 : m_map_pubkeys[pubkey] = i;
2303 : : }
2304 : : // Merge and write the cache
2305 [ + - ]: 437796 : DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2306 [ + - - + ]: 437796 : if (!batch.WriteDescriptorCacheItems(id, new_items)) {
2307 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2308 : : }
2309 : 437796 : m_max_cached_index++;
2310 : 437903 : }
2311 : 73123 : m_wallet_descriptor.range_end = new_range_end;
2312 [ + - + - ]: 73123 : batch.WriteDescriptor(GetID(), m_wallet_descriptor);
2313 : :
2314 : : // By this point, the cache size should be the size of the entire range
2315 [ - + ]: 73123 : assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
2316 : :
2317 [ + - ]: 73123 : m_storage.TopUpCallback(new_spks, this);
2318 [ + - ]: 73123 : NotifyCanGetAddressesChanged();
2319 : : return true;
2320 [ + - ]: 146460 : }
2321 : :
2322 : 46607 : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
2323 : : {
2324 : 46607 : LOCK(cs_desc_man);
2325 : 46607 : std::vector<WalletDestination> result;
2326 [ + - + - ]: 46607 : if (IsMine(script)) {
2327 [ + - ]: 46607 : int32_t index = m_map_script_pub_keys[script];
2328 [ + + ]: 46607 : if (index >= m_wallet_descriptor.next_index) {
2329 [ + - ]: 512 : WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
2330 [ + - ]: 512 : auto out_keys = std::make_unique<FlatSigningProvider>();
2331 : 512 : std::vector<CScript> scripts_temp;
2332 [ + + ]: 28917 : while (index >= m_wallet_descriptor.next_index) {
2333 [ + - - + ]: 28405 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2334 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
2335 : : }
2336 : 28405 : CTxDestination dest;
2337 [ + - ]: 28405 : ExtractDestination(scripts_temp[0], dest);
2338 : 28405 : result.push_back({dest, std::nullopt});
2339 : 28405 : m_wallet_descriptor.next_index++;
2340 : 28405 : }
2341 [ + - ]: 1024 : }
2342 [ + - + + ]: 46607 : if (!TopUp()) {
2343 [ + - ]: 1 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
2344 : : }
2345 : : }
2346 : :
2347 [ + - ]: 46607 : return result;
2348 [ + - + - ]: 103417 : }
2349 : :
2350 : 505 : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
2351 : : {
2352 : 505 : LOCK(cs_desc_man);
2353 [ + - + - ]: 505 : WalletBatch batch(m_storage.GetDatabase());
2354 [ + - - + ]: 505 : if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
2355 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
2356 : : }
2357 [ + - ]: 1010 : }
2358 : :
2359 : 3565 : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
2360 : : {
2361 : 3565 : AssertLockHeld(cs_desc_man);
2362 [ - + ]: 3565 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
2363 : :
2364 : : // Check if provided key already exists
2365 [ + + - + ]: 7123 : if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
2366 [ - + ]: 3558 : m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
2367 : 7 : return true;
2368 : : }
2369 : :
2370 [ + + ]: 3558 : if (m_storage.HasEncryptionKeys()) {
2371 [ + - ]: 162 : if (m_storage.IsLocked()) {
2372 : : return false;
2373 : : }
2374 : :
2375 : 162 : std::vector<unsigned char> crypted_secret;
2376 [ + - + - : 486 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
2377 [ + - + - : 162 : if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
+ - ]
2378 : 162 : return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
2379 : : })) {
2380 : : return false;
2381 : : }
2382 : :
2383 [ + - + - : 324 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
+ - ]
2384 [ + - + - ]: 162 : return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2385 : 162 : } else {
2386 : 3396 : m_map_keys[pubkey.GetID()] = key;
2387 [ + - + - ]: 3396 : return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
2388 : : }
2389 : : }
2390 : :
2391 : 2962 : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
2392 : : {
2393 : 2962 : LOCK(cs_desc_man);
2394 [ + - - + ]: 2962 : assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
2395 : :
2396 : : // Ignore when there is already a descriptor
2397 [ + - ]: 2962 : if (m_wallet_descriptor.descriptor) {
2398 : : return false;
2399 : : }
2400 : :
2401 [ + - + - ]: 2962 : m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
2402 : :
2403 : : // Store the master private key, and descriptor
2404 [ + - + - : 2962 : if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
- + ]
2405 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
2406 : : }
2407 [ + - + - : 2962 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
- + ]
2408 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2409 : : }
2410 : :
2411 : : // TopUp
2412 [ + - ]: 2962 : TopUpWithDB(batch);
2413 : :
2414 [ + - ]: 2962 : m_storage.UnsetBlankWalletFlag(batch);
2415 : : return true;
2416 : 2962 : }
2417 : :
2418 : 77 : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
2419 : : {
2420 : 77 : LOCK(cs_desc_man);
2421 [ + - + - ]: 77 : return m_wallet_descriptor.descriptor->IsRange();
2422 : 77 : }
2423 : :
2424 : 28521 : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
2425 : : {
2426 : : // We can only give out addresses from descriptors that are single type (not combo), ranged,
2427 : : // and either have cached keys or can generate more keys (ignoring encryption)
2428 : 28521 : LOCK(cs_desc_man);
2429 [ + - + - ]: 57042 : return m_wallet_descriptor.descriptor->IsSingleType() &&
2430 [ + - + - : 57042 : m_wallet_descriptor.descriptor->IsRange() &&
+ + ]
2431 [ + - - + : 57042 : (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
+ - ]
2432 : 28521 : }
2433 : :
2434 : 323073 : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
2435 : : {
2436 : 323073 : LOCK(cs_desc_man);
2437 [ + + + + : 351984 : return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
+ - ]
2438 : 323073 : }
2439 : :
2440 : 0 : bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
2441 : : {
2442 : 0 : LOCK(cs_desc_man);
2443 [ # # ]: 0 : return !m_map_crypted_keys.empty();
2444 : 0 : }
2445 : :
2446 : 4535 : std::optional<int64_t> DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
2447 : : {
2448 : : // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
2449 : 4535 : return std::nullopt;
2450 : : }
2451 : :
2452 : :
2453 : 9437 : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
2454 : : {
2455 : 9437 : LOCK(cs_desc_man);
2456 [ + - ]: 9437 : return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2457 : 9437 : }
2458 : :
2459 : 10766 : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
2460 : : {
2461 : 10766 : LOCK(cs_desc_man);
2462 [ + - ]: 10766 : return m_wallet_descriptor.creation_time;
2463 : 10766 : }
2464 : :
2465 : 395356 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
2466 : : {
2467 : 395356 : LOCK(cs_desc_man);
2468 : :
2469 : : // Find the index of the script
2470 : 395356 : auto it = m_map_script_pub_keys.find(script);
2471 [ + + ]: 395356 : if (it == m_map_script_pub_keys.end()) {
2472 : 101275 : return nullptr;
2473 : : }
2474 [ + - ]: 294081 : int32_t index = it->second;
2475 : :
2476 [ + - ]: 294081 : return GetSigningProvider(index, include_private);
2477 : 395356 : }
2478 : :
2479 : 17344 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
2480 : : {
2481 : 17344 : LOCK(cs_desc_man);
2482 : :
2483 : : // Find index of the pubkey
2484 : 17344 : auto it = m_map_pubkeys.find(pubkey);
2485 [ + + ]: 17344 : if (it == m_map_pubkeys.end()) {
2486 : 16879 : return nullptr;
2487 : : }
2488 [ + - ]: 465 : int32_t index = it->second;
2489 : :
2490 : : // Always try to get the signing provider with private keys. This function should only be called during signing anyways
2491 [ + - ]: 465 : std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
2492 [ + - + - : 465 : if (!out->HaveKey(pubkey.GetID())) {
+ + ]
2493 : 168 : return nullptr;
2494 : : }
2495 : 297 : return out;
2496 : 17809 : }
2497 : :
2498 : 294546 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
2499 : : {
2500 : 294546 : AssertLockHeld(cs_desc_man);
2501 : :
2502 : 294546 : std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
2503 : :
2504 : : // Fetch SigningProvider from cache to avoid re-deriving
2505 : 294546 : auto it = m_map_signing_providers.find(index);
2506 [ + + ]: 294546 : if (it != m_map_signing_providers.end()) {
2507 [ + - + - ]: 278560 : out_keys->Merge(FlatSigningProvider{it->second});
2508 : : } else {
2509 : : // Get the scripts, keys, and key origins for this script
2510 : 15986 : std::vector<CScript> scripts_temp;
2511 [ + - - + ]: 15986 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
2512 : :
2513 : : // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
2514 [ + - + - ]: 15986 : m_map_signing_providers[index] = *out_keys;
2515 : 15986 : }
2516 : :
2517 [ + - + + : 294546 : if (HavePrivateKeys() && include_private) {
+ + ]
2518 : 10934 : FlatSigningProvider master_provider;
2519 [ + - ]: 21868 : master_provider.keys = GetKeys();
2520 [ + - ]: 10934 : m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2521 : 10934 : }
2522 : :
2523 : 294546 : return out_keys;
2524 : 294546 : }
2525 : :
2526 : 345502 : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
2527 : : {
2528 [ - + ]: 345502 : return GetSigningProvider(script, false);
2529 : : }
2530 : :
2531 : 363549 : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
2532 : : {
2533 : 363549 : return IsMine(script);
2534 : : }
2535 : :
2536 : 15883 : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2537 : : {
2538 : 15883 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2539 [ + + ]: 47586 : for (const auto& coin_pair : coins) {
2540 [ + - ]: 31703 : std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
2541 [ + + ]: 31703 : if (!coin_keys) {
2542 : 22551 : continue;
2543 : : }
2544 [ + - ]: 9152 : keys->Merge(std::move(*coin_keys));
2545 : 31703 : }
2546 : :
2547 [ + - + - ]: 15883 : return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2548 : 15883 : }
2549 : :
2550 : 9 : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2551 : : {
2552 [ + - + - ]: 18 : std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
2553 [ + - ]: 9 : if (!keys) {
2554 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2555 : : }
2556 : :
2557 : 9 : CKey key;
2558 [ + - + - : 9 : if (!keys->GetKey(ToKeyID(pkhash), key)) {
+ - ]
2559 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2560 : : }
2561 : :
2562 [ + - - + ]: 9 : if (!MessageSign(key, message, str_sig)) {
2563 : 0 : return SigningResult::SIGNING_FAILED;
2564 : : }
2565 : : return SigningResult::OK;
2566 : 18 : }
2567 : :
2568 : 5700 : std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
2569 : : {
2570 [ + - ]: 5700 : if (n_signed) {
2571 : 5700 : *n_signed = 0;
2572 : : }
2573 [ + + ]: 29876 : for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2574 : 24177 : const CTxIn& txin = psbtx.tx->vin[i];
2575 : 24177 : PSBTInput& input = psbtx.inputs.at(i);
2576 : :
2577 [ + + ]: 24177 : if (PSBTInputSigned(input)) {
2578 : 6482 : continue;
2579 : : }
2580 : :
2581 : : // Get the Sighash type
2582 [ + + + + : 17695 : if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
- + ]
2583 : 0 : return PSBTError::SIGHASH_MISMATCH;
2584 : : }
2585 : :
2586 : : // Get the scriptPubKey to know which SigningProvider to use
2587 : 17695 : CScript script;
2588 [ + + ]: 17695 : if (!input.witness_utxo.IsNull()) {
2589 : 12648 : script = input.witness_utxo.scriptPubKey;
2590 [ + + ]: 5047 : } else if (input.non_witness_utxo) {
2591 [ + + ]: 4850 : if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
2592 : 1 : return PSBTError::MISSING_INPUTS;
2593 : : }
2594 : 4849 : script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
2595 : : } else {
2596 : : // There's no UTXO so we can just skip this now
2597 : 197 : continue;
2598 : : }
2599 : :
2600 [ + - ]: 17497 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2601 [ + - ]: 17497 : std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
2602 [ + + ]: 17497 : if (script_keys) {
2603 [ + - ]: 2777 : keys->Merge(std::move(*script_keys));
2604 : : } else {
2605 : : // Maybe there are pubkeys listed that we can sign for
2606 : 14720 : std::vector<CPubKey> pubkeys;
2607 [ + - ]: 14720 : pubkeys.reserve(input.hd_keypaths.size() + 2);
2608 : :
2609 : : // ECDSA Pubkeys
2610 [ + - + + ]: 25408 : for (const auto& [pk, _] : input.hd_keypaths) {
2611 [ + - ]: 10688 : pubkeys.push_back(pk);
2612 : : }
2613 : :
2614 : : // Taproot output pubkey
2615 : 14720 : std::vector<std::vector<unsigned char>> sols;
2616 [ + - + + ]: 14720 : if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
2617 [ + - ]: 1040 : sols[0].insert(sols[0].begin(), 0x02);
2618 [ + - ]: 1040 : pubkeys.emplace_back(sols[0]);
2619 [ + - ]: 1040 : sols[0][0] = 0x03;
2620 [ + - ]: 1040 : pubkeys.emplace_back(sols[0]);
2621 : : }
2622 : :
2623 : : // Taproot pubkeys
2624 [ + + ]: 17007 : for (const auto& pk_pair : input.m_tap_bip32_paths) {
2625 : 2287 : const XOnlyPubKey& pubkey = pk_pair.first;
2626 [ + + ]: 6861 : for (unsigned char prefix : {0x02, 0x03}) {
2627 : 4574 : unsigned char b[33] = {prefix};
2628 : 4574 : std::copy(pubkey.begin(), pubkey.end(), b + 1);
2629 : 4574 : CPubKey fullpubkey;
2630 : 4574 : fullpubkey.Set(b, b + 33);
2631 [ + - ]: 4574 : pubkeys.push_back(fullpubkey);
2632 : : }
2633 : : }
2634 : :
2635 [ + + ]: 32062 : for (const auto& pubkey : pubkeys) {
2636 [ + - ]: 17342 : std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
2637 [ + + ]: 17342 : if (pk_keys) {
2638 [ + - ]: 296 : keys->Merge(std::move(*pk_keys));
2639 : : }
2640 : 17342 : }
2641 : 14720 : }
2642 : :
2643 [ + - ]: 17497 : SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
2644 : :
2645 [ + - ]: 17497 : bool signed_one = PSBTInputSigned(input);
2646 [ + - + + ]: 17497 : if (n_signed && (signed_one || !sign)) {
2647 : : // If sign is false, we assume that we _could_ sign if we get here. This
2648 : : // will never have false negatives; it is hard to tell under what i
2649 : : // circumstances it could have false positives.
2650 : 12875 : (*n_signed)++;
2651 : : }
2652 [ + - ]: 35192 : }
2653 : :
2654 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
2655 [ + + ]: 70531 : for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
2656 : 65660 : std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2657 [ + + ]: 64832 : if (!keys) {
2658 : 64004 : continue;
2659 : : }
2660 [ + - ]: 828 : UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
2661 : 64832 : }
2662 : :
2663 : 5699 : return {};
2664 : : }
2665 : :
2666 : 645 : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
2667 : : {
2668 [ + - ]: 645 : std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
2669 [ + - ]: 645 : if (provider) {
2670 [ + - ]: 645 : KeyOriginInfo orig;
2671 [ + - ]: 645 : CKeyID key_id = GetKeyForDestination(*provider, dest);
2672 [ + - + + ]: 645 : if (provider->GetKeyOrigin(key_id, orig)) {
2673 [ + - ]: 558 : LOCK(cs_desc_man);
2674 [ + - ]: 558 : std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
2675 [ + - ]: 558 : meta->key_origin = orig;
2676 [ + - ]: 558 : meta->has_key_origin = true;
2677 : 558 : meta->nCreateTime = m_wallet_descriptor.creation_time;
2678 [ + - ]: 558 : return meta;
2679 : 558 : }
2680 : 645 : }
2681 : 87 : return nullptr;
2682 : 645 : }
2683 : :
2684 : 178985 : uint256 DescriptorScriptPubKeyMan::GetID() const
2685 : : {
2686 : 178985 : LOCK(cs_desc_man);
2687 [ + - ]: 178985 : return m_wallet_descriptor.id;
2688 : 178985 : }
2689 : :
2690 : 2332 : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
2691 : : {
2692 : 2332 : LOCK(cs_desc_man);
2693 [ + - ]: 2332 : std::set<CScript> new_spks;
2694 [ + - ]: 2332 : m_wallet_descriptor.cache = cache;
2695 [ + + ]: 59192 : for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2696 : 56860 : FlatSigningProvider out_keys;
2697 : 56860 : std::vector<CScript> scripts_temp;
2698 [ + - - + ]: 56860 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2699 [ # # ]: 0 : throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
2700 : : }
2701 : : // Add all of the scriptPubKeys to the scriptPubKey set
2702 [ + - ]: 56860 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
2703 [ + + ]: 114471 : for (const CScript& script : scripts_temp) {
2704 [ - + ]: 57611 : if (m_map_script_pub_keys.count(script) != 0) {
2705 [ # # # # : 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]));
# # ]
2706 : : }
2707 [ + - ]: 57611 : m_map_script_pub_keys[script] = i;
2708 : : }
2709 [ + + ]: 111663 : for (const auto& pk_pair : out_keys.pubkeys) {
2710 : 54803 : const CPubKey& pubkey = pk_pair.second;
2711 [ - + ]: 54803 : if (m_map_pubkeys.count(pubkey) != 0) {
2712 : : // We don't need to give an error here.
2713 : : // 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
2714 : 0 : continue;
2715 : : }
2716 [ + - ]: 54803 : m_map_pubkeys[pubkey] = i;
2717 : : }
2718 : 56860 : m_max_cached_index++;
2719 : 56860 : }
2720 : : // Make sure the wallet knows about our new spks
2721 [ + - ]: 2332 : m_storage.TopUpCallback(new_spks, this);
2722 [ + - ]: 4664 : }
2723 : :
2724 : 2016 : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
2725 : : {
2726 : 2016 : LOCK(cs_desc_man);
2727 [ + - + - ]: 2016 : m_map_keys[key_id] = key;
2728 [ + - ]: 2016 : return true;
2729 : 2016 : }
2730 : :
2731 : 231 : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
2732 : : {
2733 : 231 : LOCK(cs_desc_man);
2734 [ + - ]: 231 : if (!m_map_keys.empty()) {
2735 : : return false;
2736 : : }
2737 : :
2738 [ + - + - ]: 462 : m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2739 : 231 : return true;
2740 : 231 : }
2741 : :
2742 : 6421 : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
2743 : : {
2744 : 6421 : LOCK(cs_desc_man);
2745 [ + - + - : 12724 : return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
+ + + - ]
2746 : 6421 : }
2747 : :
2748 : 719 : void DescriptorScriptPubKeyMan::WriteDescriptor()
2749 : : {
2750 : 719 : LOCK(cs_desc_man);
2751 [ + - + - ]: 719 : WalletBatch batch(m_storage.GetDatabase());
2752 [ + - + - : 719 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
- + ]
2753 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2754 : : }
2755 [ + - ]: 1438 : }
2756 : :
2757 : 54940 : WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
2758 : : {
2759 : 54940 : return m_wallet_descriptor;
2760 : : }
2761 : :
2762 : 452 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
2763 : : {
2764 : 452 : return GetScriptPubKeys(0);
2765 : : }
2766 : :
2767 : 577 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
2768 : : {
2769 : 577 : LOCK(cs_desc_man);
2770 [ + - ]: 577 : std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
2771 [ + - ]: 577 : script_pub_keys.reserve(m_map_script_pub_keys.size());
2772 : :
2773 [ + + + + ]: 37222 : for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
2774 [ + + + - ]: 36645 : if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
2775 : : }
2776 [ + - ]: 577 : return script_pub_keys;
2777 : 577 : }
2778 : :
2779 : 4968 : int32_t DescriptorScriptPubKeyMan::GetEndRange() const
2780 : : {
2781 : 4968 : return m_max_cached_index + 1;
2782 : : }
2783 : :
2784 : 1168 : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
2785 : : {
2786 : 1168 : LOCK(cs_desc_man);
2787 : :
2788 : 1168 : FlatSigningProvider provider;
2789 [ + - ]: 2336 : provider.keys = GetKeys();
2790 : :
2791 [ + + ]: 1168 : if (priv) {
2792 : : // For the private version, always return the master key to avoid
2793 : : // exposing child private keys. The risk implications of exposing child
2794 : : // private keys together with the parent xpub may be non-obvious for users.
2795 [ + - ]: 48 : return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
2796 : : }
2797 : :
2798 [ + - ]: 1120 : return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
2799 [ + - ]: 2336 : }
2800 : :
2801 : 1277 : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
2802 : : {
2803 : 1277 : LOCK(cs_desc_man);
2804 [ + - + - : 1277 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
+ - - + ]
2805 : 0 : return;
2806 : : }
2807 : :
2808 : : // Skip if we have the last hardened xpub cache
2809 [ + - + + ]: 1277 : if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
2810 : : return;
2811 : : }
2812 : :
2813 : : // Expand the descriptor
2814 : 206 : FlatSigningProvider provider;
2815 [ + - ]: 412 : provider.keys = GetKeys();
2816 : 206 : FlatSigningProvider out_keys;
2817 : 206 : std::vector<CScript> scripts_temp;
2818 : 206 : DescriptorCache temp_cache;
2819 [ + - - + ]: 206 : if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
2820 [ # # ]: 0 : throw std::runtime_error("Unable to expand descriptor");
2821 : : }
2822 : :
2823 : : // Cache the last hardened xpubs
2824 [ + - ]: 206 : DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2825 [ + - + - : 412 : if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
+ - + - -
+ ]
2826 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2827 : : }
2828 [ + - ]: 1483 : }
2829 : :
2830 : 28 : void DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
2831 : : {
2832 : 28 : LOCK(cs_desc_man);
2833 [ + - ]: 28 : std::string error;
2834 [ + - - + ]: 28 : if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2835 [ # # # # : 0 : throw std::runtime_error(std::string(__func__) + ": " + error);
# # ]
2836 : : }
2837 : :
2838 : 28 : m_map_pubkeys.clear();
2839 : 28 : m_map_script_pub_keys.clear();
2840 : 28 : m_max_cached_index = -1;
2841 [ + - ]: 28 : m_wallet_descriptor = descriptor;
2842 : :
2843 [ + - ]: 28 : NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
2844 [ + - ]: 56 : }
2845 : :
2846 : 59 : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
2847 : : {
2848 : 59 : LOCK(cs_desc_man);
2849 [ + - - + ]: 59 : if (!HasWalletDescriptor(descriptor)) {
2850 [ - - + - ]: 59 : error = "can only update matching descriptor";
2851 : : return false;
2852 : : }
2853 : :
2854 [ + + ]: 59 : if (descriptor.range_start > m_wallet_descriptor.range_start ||
2855 [ + + ]: 57 : descriptor.range_end < m_wallet_descriptor.range_end) {
2856 : : // Use inclusive range for error
2857 : 6 : error = strprintf("new range must include current range = [%d,%d]",
2858 : 3 : m_wallet_descriptor.range_start,
2859 [ + - ]: 3 : m_wallet_descriptor.range_end - 1);
2860 : 3 : return false;
2861 : : }
2862 : :
2863 : : return true;
2864 : 59 : }
2865 : : } // namespace wallet
|