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 : 0 : util::Result<CTxDestination> LegacyScriptPubKeyMan::GetNewDestination(const OutputType type)
32 : : {
33 [ # # ]: 0 : 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 [ # # ]: 0 : assert(type != OutputType::BECH32M);
37 : :
38 : : // Fill-up keypool if needed
39 : 0 : TopUp();
40 : :
41 : 0 : LOCK(cs_KeyStore);
42 : :
43 : : // Generate a new key that is added to wallet
44 [ # # ]: 0 : CPubKey new_key;
45 [ # # # # ]: 0 : if (!GetKeyFromPool(new_key, type)) {
46 [ # # ]: 0 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
47 : : }
48 [ # # ]: 0 : LearnRelatedScripts(new_key, type);
49 [ # # ]: 0 : return GetDestinationForKey(new_key, type);
50 : 0 : }
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 : 0 : bool PermitsUncompressed(IsMineSigVersion sigversion)
83 : : {
84 : 0 : return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
85 : : }
86 : :
87 : 0 : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
88 : : {
89 [ # # ]: 0 : for (const valtype& pubkey : pubkeys) {
90 : 0 : CKeyID keyID = CPubKey(pubkey).GetID();
91 [ # # ]: 0 : 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 : 0 : IsMineResult IsMineInner(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
106 : : {
107 : 0 : IsMineResult ret = IsMineResult::NO;
108 : :
109 : 0 : std::vector<valtype> vSolutions;
110 [ # # ]: 0 : TxoutType whichType = Solver(scriptPubKey, vSolutions);
111 : :
112 [ # # # # : 0 : CKeyID keyID;
# # # ]
113 [ # # # # : 0 : 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 : 0 : case TxoutType::PUBKEY:
121 [ # # ]: 0 : keyID = CPubKey(vSolutions[0]).GetID();
122 [ # # # # ]: 0 : if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
123 : : return IsMineResult::INVALID;
124 : : }
125 [ # # # # ]: 0 : if (keystore.HaveKey(keyID)) {
126 [ # # ]: 0 : ret = std::max(ret, IsMineResult::SPENDABLE);
127 : : }
128 : : break;
129 : 0 : case TxoutType::WITNESS_V0_KEYHASH:
130 : 0 : {
131 [ # # ]: 0 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
132 : : // P2WPKH inside P2WSH is invalid.
133 : : return IsMineResult::INVALID;
134 : : }
135 [ # # # # : 0 : 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 [ # # # # : 0 : ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
# # ]
142 : 0 : break;
143 : : }
144 : 0 : case TxoutType::PUBKEYHASH:
145 [ # # ]: 0 : keyID = CKeyID(uint160(vSolutions[0]));
146 [ # # ]: 0 : if (!PermitsUncompressed(sigversion)) {
147 [ # # ]: 0 : CPubKey pubkey;
148 [ # # # # : 0 : if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
# # ]
149 : : return IsMineResult::INVALID;
150 : : }
151 : : }
152 [ # # # # ]: 0 : if (keystore.HaveKey(keyID)) {
153 [ # # ]: 0 : ret = std::max(ret, IsMineResult::SPENDABLE);
154 : : }
155 : : break;
156 : 0 : case TxoutType::SCRIPTHASH:
157 : 0 : {
158 [ # # ]: 0 : if (sigversion != IsMineSigVersion::TOP) {
159 : : // P2SH inside P2WSH or P2SH is invalid.
160 : : return IsMineResult::INVALID;
161 : : }
162 [ # # ]: 0 : CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
163 : 0 : CScript subscript;
164 [ # # # # ]: 0 : if (keystore.GetCScript(scriptID, subscript)) {
165 [ # # # # : 0 : ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
# # ]
166 : : }
167 : 0 : break;
168 : 0 : }
169 : 0 : case TxoutType::WITNESS_V0_SCRIPTHASH:
170 : 0 : {
171 [ # # ]: 0 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
172 : : // P2WSH inside P2WSH is invalid.
173 : : return IsMineResult::INVALID;
174 : : }
175 [ # # # # : 0 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
# # # # #
# # # ]
176 : : break;
177 : : }
178 [ # # ]: 0 : CScriptID scriptID{RIPEMD160(vSolutions[0])};
179 : 0 : CScript subscript;
180 [ # # # # ]: 0 : if (keystore.GetCScript(scriptID, subscript)) {
181 [ # # # # : 0 : ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
# # ]
182 : : }
183 : 0 : break;
184 : 0 : }
185 : :
186 : 0 : case TxoutType::MULTISIG:
187 : 0 : {
188 : : // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
189 [ # # ]: 0 : 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 [ # # ]: 0 : std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
199 [ # # ]: 0 : if (!PermitsUncompressed(sigversion)) {
200 [ # # ]: 0 : for (size_t i = 0; i < keys.size(); i++) {
201 [ # # ]: 0 : if (keys[i].size() != 33) {
202 : 0 : return IsMineResult::INVALID;
203 : : }
204 : : }
205 : : }
206 [ # # # # ]: 0 : if (HaveKeys(keys, keystore)) {
207 [ # # ]: 0 : ret = std::max(ret, IsMineResult::SPENDABLE);
208 : : }
209 : 0 : break;
210 : 0 : }
211 : : } // no default case, so the compiler can warn about missing cases
212 : :
213 [ # # # # : 0 : if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
# # ]
214 [ # # ]: 0 : ret = std::max(ret, IsMineResult::WATCH_ONLY);
215 : : }
216 : 0 : return ret;
217 : 0 : }
218 : :
219 : : } // namespace
220 : :
221 : 0 : isminetype LegacyDataSPKM::IsMine(const CScript& script) const
222 : : {
223 [ # # # # ]: 0 : switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
224 : : case IsMineResult::INVALID:
225 : : case IsMineResult::NO:
226 : : return ISMINE_NO;
227 : 0 : case IsMineResult::WATCH_ONLY:
228 : 0 : return ISMINE_WATCH_ONLY;
229 : 0 : case IsMineResult::SPENDABLE:
230 : 0 : return ISMINE_SPENDABLE;
231 : : }
232 : 0 : assert(false);
233 : : }
234 : :
235 : 0 : bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
236 : : {
237 : 0 : {
238 : 0 : LOCK(cs_KeyStore);
239 [ # # ]: 0 : assert(mapKeys.empty());
240 : :
241 [ # # ]: 0 : bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
242 : 0 : bool keyFail = false;
243 [ # # ]: 0 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
244 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
245 [ # # ]: 0 : for (; mi != mapCryptedKeys.end(); ++mi)
246 : : {
247 [ # # ]: 0 : const CPubKey &vchPubKey = (*mi).second.first;
248 : 0 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
249 : 0 : CKey key;
250 [ # # # # ]: 0 : if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
251 : : {
252 : : keyFail = true;
253 : : break;
254 : : }
255 : 0 : keyPass = true;
256 [ # # ]: 0 : if (fDecryptionThoroughlyChecked)
257 : : break;
258 : : else {
259 : : // Rewrite these encrypted keys with checksums
260 [ # # # # : 0 : batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
# # ]
261 : : }
262 : 0 : }
263 [ # # ]: 0 : 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 [ # # ]: 0 : if (keyFail || !keyPass)
269 : 0 : return false;
270 : 0 : fDecryptionThoroughlyChecked = true;
271 [ # # # # ]: 0 : }
272 : 0 : return true;
273 : : }
274 : :
275 : 0 : bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
276 : : {
277 : 0 : LOCK(cs_KeyStore);
278 : 0 : encrypted_batch = batch;
279 [ # # ]: 0 : if (!mapCryptedKeys.empty()) {
280 : 0 : encrypted_batch = nullptr;
281 : 0 : return false;
282 : : }
283 : :
284 : 0 : KeyMap keys_to_encrypt;
285 : 0 : keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
286 [ # # ]: 0 : for (const KeyMap::value_type& mKey : keys_to_encrypt)
287 : : {
288 : 0 : const CKey &key = mKey.second;
289 [ # # ]: 0 : CPubKey vchPubKey = key.GetPubKey();
290 [ # # # # : 0 : CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
# # ]
291 : 0 : std::vector<unsigned char> vchCryptedSecret;
292 [ # # # # : 0 : if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
# # ]
293 : 0 : encrypted_batch = nullptr;
294 : 0 : return false;
295 : : }
296 [ # # # # ]: 0 : if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
297 : 0 : encrypted_batch = nullptr;
298 : 0 : return false;
299 : : }
300 : 0 : }
301 : 0 : encrypted_batch = nullptr;
302 : 0 : return true;
303 : 0 : }
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 : 0 : std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
350 : : {
351 : 0 : LOCK(cs_KeyStore);
352 : 0 : std::vector<WalletDestination> result;
353 : : // extract addresses and check if they match with an unused keypool key
354 [ # # # # ]: 0 : 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 [ # # ]: 0 : return result;
403 [ # # ]: 0 : }
404 : :
405 : 0 : void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
406 : : {
407 : 0 : LOCK(cs_KeyStore);
408 [ # # # # : 0 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
# # # # ]
409 [ # # ]: 0 : return;
410 : : }
411 : :
412 [ # # # # ]: 0 : std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
413 [ # # ]: 0 : for (auto& meta_pair : mapKeyMetadata) {
414 : 0 : CKeyMetadata& meta = meta_pair.second;
415 [ # # # # : 0 : 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 [ # # ]: 0 : }
439 : :
440 : 0 : bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
441 : : {
442 [ # # # # : 0 : if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
# # ]
443 : 0 : return false;
444 : : }
445 : :
446 : 0 : SetHDSeed(GenerateNewSeed());
447 [ # # ]: 0 : if (!NewKeyPool()) {
448 : 0 : return false;
449 : : }
450 : : return true;
451 : : }
452 : :
453 : 0 : bool LegacyScriptPubKeyMan::IsHDEnabled() const
454 : : {
455 : 0 : return !m_hd_chain.seed_id.IsNull();
456 : : }
457 : :
458 : 0 : bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
459 : : {
460 : 0 : LOCK(cs_KeyStore);
461 : : // Check if the keypool has keys
462 : 0 : bool keypool_has_keys;
463 [ # # # # : 0 : if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
# # ]
464 : 0 : keypool_has_keys = setInternalKeyPool.size() > 0;
465 : : } else {
466 [ # # ]: 0 : keypool_has_keys = KeypoolCountExternalKeys() > 0;
467 : : }
468 : : // If the keypool doesn't have keys, check if we can generate them
469 [ # # ]: 0 : if (!keypool_has_keys) {
470 [ # # ]: 0 : return CanGenerateKeys();
471 : : }
472 : : return keypool_has_keys;
473 : 0 : }
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 : 0 : size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
578 : : {
579 : 0 : LOCK(cs_KeyStore);
580 [ # # ]: 0 : return setExternalKeyPool.size() + set_pre_split_keypool.size();
581 : 0 : }
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 : 0 : int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
590 : : {
591 : 0 : LOCK(cs_KeyStore);
592 [ # # ]: 0 : return nTimeFirstKey;
593 : 0 : }
594 : :
595 : 0 : std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
596 : : {
597 : 0 : return std::make_unique<LegacySigningProvider>(*this);
598 : : }
599 : :
600 : 0 : bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
601 : : {
602 : 0 : IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
603 [ # # ]: 0 : 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 : 0 : ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
611 [ # # ]: 0 : if (!sigdata.signatures.empty()) {
612 : : // If we could make signatures, make sure we have a private key to actually make a signature
613 : 0 : bool has_privkeys = false;
614 [ # # ]: 0 : for (const auto& key_sig_pair : sigdata.signatures) {
615 : 0 : 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 : 0 : uint256 LegacyScriptPubKeyMan::GetID() const
709 : : {
710 : 0 : 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 : 0 : void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
718 : : {
719 : 0 : AssertLockHeld(cs_KeyStore);
720 [ # # ]: 0 : if (nCreateTime <= 1) {
721 : : // Cannot determine birthday information, so set the wallet birthday to
722 : : // the beginning of time.
723 : 0 : nTimeFirstKey = 1;
724 [ # # # # ]: 0 : } else if (nTimeFirstKey == UNKNOWN_TIME || nCreateTime < nTimeFirstKey) {
725 : 0 : nTimeFirstKey = nCreateTime;
726 : : }
727 : :
728 : 0 : NotifyFirstKeyTimeChanged(this, nTimeFirstKey);
729 : 0 : }
730 : :
731 : 0 : bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
732 : : {
733 : 0 : return AddKeyPubKeyInner(key, pubkey);
734 : : }
735 : :
736 : 0 : bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
737 : : {
738 : 0 : LOCK(cs_KeyStore);
739 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
740 [ # # ]: 0 : return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
741 [ # # ]: 0 : }
742 : :
743 : 0 : bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
744 : : {
745 : 0 : AssertLockHeld(cs_KeyStore);
746 : :
747 : : // Make sure we aren't adding private keys to private key disabled wallets
748 [ # # ]: 0 : 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 : 0 : bool needsDB = !encrypted_batch;
754 [ # # ]: 0 : if (needsDB) {
755 : 0 : encrypted_batch = &batch;
756 : : }
757 [ # # ]: 0 : if (!AddKeyPubKeyInner(secret, pubkey)) {
758 [ # # ]: 0 : if (needsDB) encrypted_batch = nullptr;
759 : 0 : return false;
760 : : }
761 [ # # ]: 0 : if (needsDB) encrypted_batch = nullptr;
762 : :
763 : : // check if we need to remove from watch-only
764 : 0 : CScript script;
765 [ # # # # ]: 0 : script = GetScriptForDestination(PKHash(pubkey));
766 [ # # # # ]: 0 : if (HaveWatchOnly(script)) {
767 [ # # ]: 0 : RemoveWatchOnly(script);
768 : : }
769 [ # # ]: 0 : script = GetScriptForRawPubKey(pubkey);
770 [ # # # # ]: 0 : if (HaveWatchOnly(script)) {
771 [ # # ]: 0 : RemoveWatchOnly(script);
772 : : }
773 : :
774 [ # # ]: 0 : m_storage.UnsetBlankWalletFlag(batch);
775 [ # # # # ]: 0 : if (!m_storage.HasEncryptionKeys()) {
776 [ # # ]: 0 : return batch.WriteKey(pubkey,
777 [ # # ]: 0 : secret.GetPrivKey(),
778 [ # # # # ]: 0 : mapKeyMetadata[pubkey.GetID()]);
779 : : }
780 : : return true;
781 : 0 : }
782 : :
783 : 0 : 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 [ # # # # ]: 0 : 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 : 0 : return FillableSigningProvider::AddCScript(redeemScript);
796 : : }
797 : :
798 : 0 : void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
799 : : {
800 : 0 : LOCK(cs_KeyStore);
801 [ # # # # ]: 0 : mapKeyMetadata[keyID] = meta;
802 : 0 : }
803 : :
804 : 0 : void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
805 : : {
806 : 0 : LOCK(cs_KeyStore);
807 [ # # ]: 0 : LegacyDataSPKM::LoadKeyMetadata(keyID, meta);
808 [ # # ]: 0 : UpdateTimeFirstKey(meta.nCreateTime);
809 : 0 : }
810 : :
811 : 0 : void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
812 : : {
813 : 0 : LOCK(cs_KeyStore);
814 [ # # # # ]: 0 : m_script_metadata[script_id] = meta;
815 : 0 : }
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 : 0 : bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
825 : : {
826 : 0 : LOCK(cs_KeyStore);
827 [ # # # # ]: 0 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
828 : 0 : }
829 : :
830 : 0 : bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
831 : : {
832 : 0 : LOCK(cs_KeyStore);
833 [ # # # # ]: 0 : if (!m_storage.HasEncryptionKeys()) {
834 [ # # ]: 0 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
835 : : }
836 : :
837 [ # # # # ]: 0 : if (m_storage.IsLocked()) {
838 : : return false;
839 : : }
840 : :
841 : 0 : std::vector<unsigned char> vchCryptedSecret;
842 [ # # # # : 0 : CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
# # ]
843 [ # # # # : 0 : if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
# # ]
844 : 0 : return EncryptSecret(encryption_key, vchSecret, pubkey.GetHash(), vchCryptedSecret);
845 : : })) {
846 : : return false;
847 : : }
848 : :
849 [ # # # # ]: 0 : if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
850 : 0 : return false;
851 : : }
852 : : return true;
853 : 0 : }
854 : :
855 : 0 : 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 [ # # ]: 0 : if (!checksum_valid) {
859 : 0 : fDecryptionThoroughlyChecked = false;
860 : : }
861 : :
862 : 0 : return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
863 : : }
864 : :
865 : 0 : bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
866 : : {
867 : 0 : LOCK(cs_KeyStore);
868 [ # # ]: 0 : assert(mapKeys.empty());
869 : :
870 [ # # # # : 0 : mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
# # ]
871 [ # # ]: 0 : ImplicitlyLearnRelatedKeyScripts(vchPubKey);
872 [ # # ]: 0 : return true;
873 : 0 : }
874 : :
875 : 0 : bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
876 : : const std::vector<unsigned char> &vchCryptedSecret)
877 : : {
878 [ # # ]: 0 : if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
879 : : return false;
880 : 0 : {
881 : 0 : LOCK(cs_KeyStore);
882 [ # # ]: 0 : if (encrypted_batch)
883 [ # # ]: 0 : return encrypted_batch->WriteCryptedKey(vchPubKey,
884 : : vchCryptedSecret,
885 [ # # # # ]: 0 : mapKeyMetadata[vchPubKey.GetID()]);
886 : : else
887 [ # # # # : 0 : return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
# # ]
888 : : vchCryptedSecret,
889 [ # # # # ]: 0 : mapKeyMetadata[vchPubKey.GetID()]);
890 : 0 : }
891 : : }
892 : :
893 : 0 : bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
894 : : {
895 : 0 : LOCK(cs_KeyStore);
896 [ # # ]: 0 : return setWatchOnly.count(dest) > 0;
897 : 0 : }
898 : :
899 : 0 : bool LegacyDataSPKM::HaveWatchOnly() const
900 : : {
901 : 0 : LOCK(cs_KeyStore);
902 [ # # ]: 0 : return (!setWatchOnly.empty());
903 : 0 : }
904 : :
905 : 0 : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
906 : : {
907 : 0 : std::vector<std::vector<unsigned char>> solutions;
908 [ # # # # : 0 : return Solver(dest, solutions) == TxoutType::PUBKEY &&
# # ]
909 [ # # ]: 0 : (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
910 : 0 : }
911 : :
912 : 0 : bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
913 : : {
914 : 0 : {
915 : 0 : LOCK(cs_KeyStore);
916 : 0 : setWatchOnly.erase(dest);
917 [ # # ]: 0 : CPubKey pubKey;
918 [ # # # # ]: 0 : if (ExtractPubKey(dest, pubKey)) {
919 [ # # ]: 0 : 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 [ # # ]: 0 : if (!HaveWatchOnly())
926 : 0 : NotifyWatchonlyChanged(false);
927 [ # # # # ]: 0 : if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
928 : 0 : return false;
929 : :
930 : : return true;
931 : : }
932 : :
933 : 0 : bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
934 : : {
935 : 0 : return AddWatchOnlyInMem(dest);
936 : : }
937 : :
938 : 0 : bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
939 : : {
940 : 0 : LOCK(cs_KeyStore);
941 [ # # ]: 0 : setWatchOnly.insert(dest);
942 [ # # ]: 0 : CPubKey pubKey;
943 [ # # # # ]: 0 : if (ExtractPubKey(dest, pubKey)) {
944 [ # # # # ]: 0 : mapWatchKeys[pubKey.GetID()] = pubKey;
945 [ # # ]: 0 : ImplicitlyLearnRelatedKeyScripts(pubKey);
946 : : }
947 [ # # ]: 0 : return true;
948 : 0 : }
949 : :
950 : 0 : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
951 : : {
952 [ # # ]: 0 : if (!AddWatchOnlyInMem(dest))
953 : : return false;
954 : 0 : const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
955 : 0 : UpdateTimeFirstKey(meta.nCreateTime);
956 : 0 : NotifyWatchonlyChanged(true);
957 [ # # ]: 0 : if (batch.WriteWatchOnly(dest, meta)) {
958 : 0 : m_storage.UnsetBlankWalletFlag(batch);
959 : 0 : return true;
960 : : }
961 : : return false;
962 : : }
963 : :
964 : 0 : bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
965 : : {
966 : 0 : m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
967 : 0 : 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 : 0 : void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
983 : : {
984 : 0 : LOCK(cs_KeyStore);
985 [ # # ]: 0 : m_hd_chain = chain;
986 : 0 : }
987 : :
988 : 0 : void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
989 : : {
990 : 0 : LOCK(cs_KeyStore);
991 : : // Store the new chain
992 [ # # # # : 0 : 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 [ # # ]: 0 : if (!m_hd_chain.seed_id.IsNull()) {
997 [ # # ]: 0 : AddInactiveHDChain(m_hd_chain);
998 : : }
999 : :
1000 [ # # ]: 0 : m_hd_chain = chain;
1001 : 0 : }
1002 : :
1003 : 0 : void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
1004 : : {
1005 : 0 : LOCK(cs_KeyStore);
1006 [ # # ]: 0 : assert(!chain.seed_id.IsNull());
1007 [ # # # # ]: 0 : m_inactive_hd_chains[chain.seed_id] = chain;
1008 : 0 : }
1009 : :
1010 : 0 : bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
1011 : : {
1012 : 0 : LOCK(cs_KeyStore);
1013 [ # # # # ]: 0 : if (!m_storage.HasEncryptionKeys()) {
1014 [ # # ]: 0 : return FillableSigningProvider::HaveKey(address);
1015 : : }
1016 : 0 : return mapCryptedKeys.count(address) > 0;
1017 : 0 : }
1018 : :
1019 : 0 : bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
1020 : : {
1021 : 0 : LOCK(cs_KeyStore);
1022 [ # # # # ]: 0 : if (!m_storage.HasEncryptionKeys()) {
1023 [ # # ]: 0 : return FillableSigningProvider::GetKey(address, keyOut);
1024 : : }
1025 : :
1026 : 0 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1027 [ # # ]: 0 : if (mi != mapCryptedKeys.end())
1028 : : {
1029 [ # # ]: 0 : const CPubKey &vchPubKey = (*mi).second.first;
1030 : 0 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
1031 [ # # # # ]: 0 : return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1032 : 0 : return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
1033 : : });
1034 : : }
1035 : : return false;
1036 : 0 : }
1037 : :
1038 : 0 : bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
1039 : : {
1040 : 0 : CKeyMetadata meta;
1041 : 0 : {
1042 [ # # ]: 0 : LOCK(cs_KeyStore);
1043 : 0 : auto it = mapKeyMetadata.find(keyID);
1044 [ # # ]: 0 : if (it == mapKeyMetadata.end()) {
1045 [ # # ]: 0 : return false;
1046 : : }
1047 [ # # ]: 0 : meta = it->second;
1048 : 0 : }
1049 [ # # ]: 0 : if (meta.has_key_origin) {
1050 : 0 : std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
1051 [ # # ]: 0 : info.path = meta.key_origin.path;
1052 : : } else { // Single pubkeys get the master fingerprint of themselves
1053 : 0 : std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
1054 : : }
1055 : : return true;
1056 : 0 : }
1057 : :
1058 : 0 : bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
1059 : : {
1060 : 0 : LOCK(cs_KeyStore);
1061 : 0 : WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
1062 [ # # ]: 0 : if (it != mapWatchKeys.end()) {
1063 : 0 : pubkey_out = it->second;
1064 : 0 : return true;
1065 : : }
1066 : : return false;
1067 : 0 : }
1068 : :
1069 : 0 : bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
1070 : : {
1071 : 0 : LOCK(cs_KeyStore);
1072 [ # # # # ]: 0 : if (!m_storage.HasEncryptionKeys()) {
1073 [ # # # # ]: 0 : if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
1074 [ # # ]: 0 : return GetWatchPubKey(address, vchPubKeyOut);
1075 : : }
1076 : : return true;
1077 : : }
1078 : :
1079 : 0 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1080 [ # # ]: 0 : if (mi != mapCryptedKeys.end())
1081 : : {
1082 : 0 : vchPubKeyOut = (*mi).second.first;
1083 : 0 : return true;
1084 : : }
1085 : : // Check for watch-only pubkeys
1086 [ # # ]: 0 : return GetWatchPubKey(address, vchPubKeyOut);
1087 : 0 : }
1088 : :
1089 : 0 : CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
1090 : : {
1091 [ # # ]: 0 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1092 [ # # ]: 0 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
1093 : 0 : AssertLockHeld(cs_KeyStore);
1094 : 0 : bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
1095 : :
1096 : 0 : CKey secret;
1097 : :
1098 : : // Create new metadata
1099 [ # # ]: 0 : int64_t nCreationTime = GetTime();
1100 : 0 : CKeyMetadata metadata(nCreationTime);
1101 : :
1102 : : // use HD key derivation if HD was enabled during wallet creation and a seed is present
1103 [ # # # # ]: 0 : if (IsHDEnabled()) {
1104 [ # # # # : 0 : 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 [ # # ]: 0 : if (fCompressed) {
1111 [ # # ]: 0 : m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
1112 : : }
1113 : :
1114 [ # # ]: 0 : CPubKey pubkey = secret.GetPubKey();
1115 [ # # # # ]: 0 : assert(secret.VerifyPubKey(pubkey));
1116 : :
1117 [ # # # # : 0 : mapKeyMetadata[pubkey.GetID()] = metadata;
# # ]
1118 [ # # ]: 0 : UpdateTimeFirstKey(nCreationTime);
1119 : :
1120 [ # # # # ]: 0 : if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1121 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1122 : : }
1123 : 0 : return pubkey;
1124 : 0 : }
1125 : :
1126 : : //! Try to derive an extended key, throw if it fails.
1127 : 0 : static void DeriveExtKey(CExtKey& key_in, unsigned int index, CExtKey& key_out) {
1128 [ # # ]: 0 : if (!key_in.Derive(key_out, index)) {
1129 [ # # ]: 0 : throw std::runtime_error("Could not derive extended key");
1130 : : }
1131 : 0 : }
1132 : :
1133 : 0 : 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 : 0 : CKey seed; //seed (256bit)
1137 [ # # ]: 0 : CExtKey masterKey; //hd master key
1138 : 0 : CExtKey accountKey; //key at m/0'
1139 : 0 : CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
1140 : 0 : CExtKey childKey; //key at m/0'/0'/<n>'
1141 : :
1142 : : // try to get the seed
1143 [ # # # # ]: 0 : if (!GetKey(hd_chain.seed_id, seed))
1144 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": seed not found");
1145 : :
1146 [ # # # # ]: 0 : masterKey.SetSeed(seed);
1147 : :
1148 : : // derive m/0'
1149 : : // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
1150 [ # # ]: 0 : DeriveExtKey(masterKey, BIP32_HARDENED_KEY_LIMIT, accountKey);
1151 : :
1152 : : // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1153 [ # # # # : 0 : assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
# # ]
1154 [ # # # # ]: 0 : 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 : 0 : 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 [ # # ]: 0 : 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 [ # # ]: 0 : DeriveExtKey(chainChildKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1171 [ # # # # ]: 0 : metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1172 [ # # ]: 0 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1173 [ # # ]: 0 : metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1174 [ # # ]: 0 : metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1175 : 0 : hd_chain.nExternalChainCounter++;
1176 : : }
1177 [ # # # # : 0 : } while (HaveKey(childKey.key.GetPubKey().GetID()));
# # # # ]
1178 [ # # ]: 0 : secret = childKey.key;
1179 : 0 : metadata.hd_seed_id = hd_chain.seed_id;
1180 [ # # # # ]: 0 : CKeyID master_id = masterKey.key.GetPubKey().GetID();
1181 : 0 : std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
1182 : 0 : metadata.has_key_origin = true;
1183 : : // update the chain model in the database
1184 [ # # # # : 0 : 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 : 0 : }
1187 : :
1188 : 0 : void LegacyDataSPKM::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
1189 : : {
1190 : 0 : LOCK(cs_KeyStore);
1191 [ # # ]: 0 : if (keypool.m_pre_split) {
1192 [ # # ]: 0 : set_pre_split_keypool.insert(nIndex);
1193 [ # # ]: 0 : } else if (keypool.fInternal) {
1194 [ # # ]: 0 : setInternalKeyPool.insert(nIndex);
1195 : : } else {
1196 [ # # ]: 0 : setExternalKeyPool.insert(nIndex);
1197 : : }
1198 [ # # ]: 0 : m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1199 [ # # # # ]: 0 : 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 [ # # ]: 0 : CKeyID keyid = keypool.vchPubKey.GetID();
1205 [ # # ]: 0 : if (mapKeyMetadata.count(keyid) == 0)
1206 [ # # ]: 0 : mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1207 : 0 : }
1208 : :
1209 : 0 : 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 : 0 : LOCK(cs_KeyStore);
1213 [ # # # # : 0 : return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
# # # # #
# ]
1214 : 0 : }
1215 : :
1216 : 0 : CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
1217 : : {
1218 [ # # ]: 0 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1219 : 0 : CKey key = GenerateRandomKey();
1220 [ # # ]: 0 : return DeriveNewSeed(key);
1221 : 0 : }
1222 : :
1223 : 0 : CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
1224 : : {
1225 : 0 : int64_t nCreationTime = GetTime();
1226 : 0 : CKeyMetadata metadata(nCreationTime);
1227 : :
1228 : : // calculate the seed
1229 [ # # ]: 0 : CPubKey seed = key.GetPubKey();
1230 [ # # # # ]: 0 : assert(key.VerifyPubKey(seed));
1231 : :
1232 : : // set the hd keypath to "s" -> Seed, refers the seed to itself
1233 [ # # ]: 0 : metadata.hdKeypath = "s";
1234 : 0 : metadata.has_key_origin = false;
1235 [ # # ]: 0 : metadata.hd_seed_id = seed.GetID();
1236 : :
1237 : 0 : {
1238 [ # # ]: 0 : LOCK(cs_KeyStore);
1239 : :
1240 : : // mem store the metadata
1241 [ # # # # : 0 : mapKeyMetadata[seed.GetID()] = metadata;
# # ]
1242 : :
1243 : : // write the key&metadata to the database
1244 [ # # # # ]: 0 : if (!AddKeyPubKey(key, seed))
1245 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1246 : 0 : }
1247 : :
1248 : 0 : return seed;
1249 : 0 : }
1250 : :
1251 : 0 : void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
1252 : : {
1253 : 0 : LOCK(cs_KeyStore);
1254 : : // store the keyid (hash160) together with
1255 : : // the child index counter in the database
1256 : : // as a hdchain object
1257 : 0 : CHDChain newHdChain;
1258 [ # # # # ]: 0 : newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1259 [ # # ]: 0 : newHdChain.seed_id = seed.GetID();
1260 [ # # ]: 0 : AddHDChain(newHdChain);
1261 [ # # ]: 0 : NotifyCanGetAddressesChanged();
1262 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
1263 [ # # ]: 0 : m_storage.UnsetBlankWalletFlag(batch);
1264 [ # # ]: 0 : }
1265 : :
1266 : : /**
1267 : : * Mark old keypool keys as used,
1268 : : * and generate all new keys
1269 : : */
1270 : 0 : bool LegacyScriptPubKeyMan::NewKeyPool()
1271 : : {
1272 [ # # ]: 0 : if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
1273 : : return false;
1274 : : }
1275 : 0 : {
1276 : 0 : LOCK(cs_KeyStore);
1277 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
1278 : :
1279 [ # # ]: 0 : for (const int64_t nIndex : setInternalKeyPool) {
1280 [ # # ]: 0 : batch.ErasePool(nIndex);
1281 : : }
1282 : 0 : setInternalKeyPool.clear();
1283 : :
1284 [ # # ]: 0 : for (const int64_t nIndex : setExternalKeyPool) {
1285 [ # # ]: 0 : batch.ErasePool(nIndex);
1286 : : }
1287 : 0 : setExternalKeyPool.clear();
1288 : :
1289 [ # # ]: 0 : for (const int64_t nIndex : set_pre_split_keypool) {
1290 [ # # ]: 0 : batch.ErasePool(nIndex);
1291 : : }
1292 : 0 : set_pre_split_keypool.clear();
1293 : :
1294 : 0 : m_pool_key_to_index.clear();
1295 : :
1296 [ # # # # ]: 0 : if (!TopUp()) {
1297 : 0 : return false;
1298 : : }
1299 [ # # ]: 0 : WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1300 [ # # # # ]: 0 : }
1301 : 0 : return true;
1302 : : }
1303 : :
1304 : 0 : bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
1305 : : {
1306 [ # # ]: 0 : if (!CanGenerateKeys()) {
1307 : : return false;
1308 : : }
1309 : :
1310 : 0 : WalletBatch batch(m_storage.GetDatabase());
1311 [ # # # # ]: 0 : if (!batch.TxnBegin()) return false;
1312 [ # # # # ]: 0 : if (!TopUpChain(batch, m_hd_chain, kpSize)) {
1313 : : return false;
1314 : : }
1315 [ # # # # ]: 0 : for (auto& [chain_id, chain] : m_inactive_hd_chains) {
1316 [ # # # # ]: 0 : if (!TopUpChain(batch, chain, kpSize)) {
1317 : : return false;
1318 : : }
1319 : : }
1320 [ # # # # : 0 : if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
# # # # #
# ]
1321 [ # # ]: 0 : 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 : 0 : }
1327 : :
1328 : 0 : bool LegacyScriptPubKeyMan::TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int kpSize)
1329 : : {
1330 : 0 : LOCK(cs_KeyStore);
1331 : :
1332 [ # # # # ]: 0 : if (m_storage.IsLocked()) return false;
1333 : :
1334 : : // Top up key pool
1335 : 0 : unsigned int nTargetSize;
1336 [ # # ]: 0 : if (kpSize > 0) {
1337 : : nTargetSize = kpSize;
1338 : : } else {
1339 : 0 : nTargetSize = m_keypool_size;
1340 : : }
1341 [ # # ]: 0 : 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 : 0 : int64_t missingExternal;
1346 : 0 : int64_t missingInternal;
1347 [ # # ]: 0 : if (chain == m_hd_chain) {
1348 [ # # ]: 0 : missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
1349 [ # # ]: 0 : missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
1350 : : } else {
1351 [ # # ]: 0 : missingExternal = std::max(target - (chain.nExternalChainCounter - chain.m_next_external_index), int64_t{0});
1352 [ # # ]: 0 : missingInternal = std::max(target - (chain.nInternalChainCounter - chain.m_next_internal_index), int64_t{0});
1353 : : }
1354 : :
1355 [ # # # # : 0 : if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
# # # # ]
1356 : : // don't create extra internal keys
1357 : 0 : missingInternal = 0;
1358 : : }
1359 : 0 : bool internal = false;
1360 [ # # ]: 0 : for (int64_t i = missingInternal + missingExternal; i--;) {
1361 [ # # ]: 0 : if (i < missingInternal) {
1362 : 0 : internal = true;
1363 : : }
1364 : :
1365 [ # # ]: 0 : CPubKey pubkey(GenerateNewKey(batch, chain, internal));
1366 [ # # ]: 0 : if (chain == m_hd_chain) {
1367 [ # # ]: 0 : AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1368 : : }
1369 : : }
1370 [ # # ]: 0 : if (missingInternal + missingExternal > 0) {
1371 [ # # ]: 0 : if (chain == m_hd_chain) {
1372 [ # # ]: 0 : 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 : 0 : }
1379 : :
1380 : 0 : void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
1381 : : {
1382 : 0 : LOCK(cs_KeyStore);
1383 [ # # ]: 0 : assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
1384 : 0 : int64_t index = ++m_max_keypool_index;
1385 [ # # # # : 0 : if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
# # ]
1386 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
1387 : : }
1388 [ # # ]: 0 : if (internal) {
1389 [ # # ]: 0 : setInternalKeyPool.insert(index);
1390 : : } else {
1391 [ # # ]: 0 : setExternalKeyPool.insert(index);
1392 : : }
1393 [ # # # # : 0 : m_pool_key_to_index[pubkey.GetID()] = index;
# # ]
1394 : 0 : }
1395 : :
1396 : 0 : void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
1397 : : {
1398 [ # # ]: 0 : assert(type != OutputType::BECH32M);
1399 : : // Remove from key pool
1400 : 0 : WalletBatch batch(m_storage.GetDatabase());
1401 [ # # ]: 0 : batch.ErasePool(nIndex);
1402 [ # # ]: 0 : CPubKey pubkey;
1403 [ # # # # ]: 0 : bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1404 [ # # ]: 0 : assert(have_pk);
1405 [ # # ]: 0 : LearnRelatedScripts(pubkey, type);
1406 : 0 : m_index_to_reserved_key.erase(nIndex);
1407 [ # # ]: 0 : WalletLogPrintf("keypool keep %d\n", nIndex);
1408 : 0 : }
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 : 0 : bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type)
1431 : : {
1432 [ # # ]: 0 : assert(type != OutputType::BECH32M);
1433 [ # # ]: 0 : if (!CanGetAddresses(/*internal=*/ false)) {
1434 : : return false;
1435 : : }
1436 : :
1437 : 0 : CKeyPool keypool;
1438 : 0 : {
1439 : 0 : LOCK(cs_KeyStore);
1440 : 0 : int64_t nIndex;
1441 [ # # # # : 0 : 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 [ # # ]: 0 : KeepDestination(nIndex, type);
1448 [ # # ]: 0 : result = keypool.vchPubKey;
1449 : 0 : }
1450 : 0 : return true;
1451 : : }
1452 : :
1453 : 0 : bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
1454 : : {
1455 : 0 : nIndex = -1;
1456 : 0 : keypool.vchPubKey = CPubKey();
1457 : 0 : {
1458 : 0 : LOCK(cs_KeyStore);
1459 : :
1460 : 0 : bool fReturningInternal = fRequestedInternal;
1461 [ # # # # : 0 : fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
# # # # #
# # # ]
1462 [ # # ]: 0 : bool use_split_keypool = set_pre_split_keypool.empty();
1463 [ # # # # ]: 0 : std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1464 : :
1465 : : // Get the oldest key
1466 [ # # ]: 0 : if (setKeyPool.empty()) {
1467 [ # # ]: 0 : return false;
1468 : : }
1469 : :
1470 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
1471 : :
1472 : 0 : auto it = setKeyPool.begin();
1473 : 0 : nIndex = *it;
1474 : 0 : setKeyPool.erase(it);
1475 [ # # # # ]: 0 : if (!batch.ReadPool(nIndex, keypool)) {
1476 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": read failed");
1477 : : }
1478 [ # # ]: 0 : CPubKey pk;
1479 [ # # # # : 0 : 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 [ # # # # ]: 0 : if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1484 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
1485 : : }
1486 [ # # ]: 0 : if (!keypool.vchPubKey.IsValid()) {
1487 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
1488 : : }
1489 : :
1490 [ # # ]: 0 : assert(m_index_to_reserved_key.count(nIndex) == 0);
1491 [ # # # # ]: 0 : m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1492 [ # # ]: 0 : m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1493 [ # # ]: 0 : WalletLogPrintf("keypool reserve %d\n", nIndex);
1494 [ # # ]: 0 : }
1495 : 0 : NotifyCanGetAddressesChanged();
1496 : 0 : return true;
1497 : : }
1498 : :
1499 : 0 : void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
1500 : : {
1501 [ # # ]: 0 : assert(type != OutputType::BECH32M);
1502 [ # # # # ]: 0 : 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 : 0 : }
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 : 0 : std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
1547 : : {
1548 : 0 : std::vector<CScript> dummy;
1549 : 0 : FlatSigningProvider out;
1550 [ # # # # ]: 0 : InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1551 : 0 : std::vector<CKeyID> ret;
1552 [ # # ]: 0 : ret.reserve(out.pubkeys.size());
1553 [ # # ]: 0 : for (const auto& entry : out.pubkeys) {
1554 [ # # ]: 0 : ret.push_back(entry.first);
1555 : : }
1556 : 0 : return ret;
1557 : 0 : }
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 : 0 : bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
1578 : : {
1579 : 0 : WalletBatch batch(m_storage.GetDatabase());
1580 [ # # ]: 0 : return AddCScriptWithDB(batch, redeemScript);
1581 : 0 : }
1582 : :
1583 : 0 : bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
1584 : : {
1585 [ # # ]: 0 : if (!FillableSigningProvider::AddCScript(redeemScript))
1586 : : return false;
1587 [ # # ]: 0 : if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1588 : 0 : m_storage.UnsetBlankWalletFlag(batch);
1589 : 0 : 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 : 0 : bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1605 : : {
1606 : 0 : WalletBatch batch(m_storage.GetDatabase());
1607 [ # # ]: 0 : for (const auto& entry : scripts) {
1608 [ # # ]: 0 : CScriptID id(entry);
1609 [ # # # # ]: 0 : if (HaveCScript(id)) {
1610 [ # # # # : 0 : WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
# # ]
1611 : 0 : 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 [ # # ]: 0 : if (timestamp > 0) {
1622 [ # # ]: 0 : UpdateTimeFirstKey(timestamp);
1623 : : }
1624 : :
1625 : : return true;
1626 : 0 : }
1627 : :
1628 : 0 : bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1629 : : {
1630 : 0 : WalletBatch batch(m_storage.GetDatabase());
1631 [ # # ]: 0 : for (const auto& entry : privkey_map) {
1632 : 0 : const CKey& key = entry.second;
1633 [ # # ]: 0 : CPubKey pubkey = key.GetPubKey();
1634 : 0 : const CKeyID& id = entry.first;
1635 [ # # # # ]: 0 : assert(key.VerifyPubKey(pubkey));
1636 : : // Skip if we already have the key
1637 [ # # # # ]: 0 : if (HaveKey(id)) {
1638 [ # # # # ]: 0 : WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
1639 : 0 : continue;
1640 : : }
1641 [ # # ]: 0 : mapKeyMetadata[id].nCreateTime = timestamp;
1642 : : // If the private key is not present in the wallet, insert it.
1643 [ # # # # ]: 0 : if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1644 : : return false;
1645 : : }
1646 [ # # ]: 0 : UpdateTimeFirstKey(timestamp);
1647 : : }
1648 : : return true;
1649 : 0 : }
1650 : :
1651 : 0 : 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 : 0 : WalletBatch batch(m_storage.GetDatabase());
1654 [ # # ]: 0 : for (const auto& entry : key_origins) {
1655 [ # # ]: 0 : AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1656 : : }
1657 [ # # ]: 0 : 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 : 0 : }
1682 : :
1683 : 0 : bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
1684 : : {
1685 : 0 : WalletBatch batch(m_storage.GetDatabase());
1686 [ # # ]: 0 : for (const CScript& script : script_pub_keys) {
1687 [ # # # # : 0 : if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
# # ]
1688 [ # # # # ]: 0 : if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1689 : : return false;
1690 : : }
1691 : : }
1692 : : }
1693 : : return true;
1694 : 0 : }
1695 : :
1696 : 0 : std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
1697 : : {
1698 : 0 : LOCK(cs_KeyStore);
1699 [ # # # # ]: 0 : if (!m_storage.HasEncryptionKeys()) {
1700 [ # # ]: 0 : 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 : 0 : }
1708 : :
1709 : 0 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
1710 : : {
1711 : 0 : LOCK(cs_KeyStore);
1712 [ # # ]: 0 : 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 : 0 : const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
1716 [ # # ]: 0 : candidate_spks.insert(GetScriptForRawPubKey(pub));
1717 [ # # ]: 0 : candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
1718 : :
1719 [ # # ]: 0 : CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
1720 [ # # ]: 0 : candidate_spks.insert(wpkh);
1721 [ # # # # ]: 0 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
1722 : 0 : };
1723 [ # # # # ]: 0 : for (const auto& [_, key] : mapKeys) {
1724 [ # # # # ]: 0 : add_pubkey(key.GetPubKey());
1725 : : }
1726 [ # # # # ]: 0 : for (const auto& [_, ckeypair] : mapCryptedKeys) {
1727 [ # # ]: 0 : 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 : 0 : const auto& add_script = [&candidate_spks](const CScript& script) -> void {
1735 : 0 : candidate_spks.insert(script);
1736 [ # # ]: 0 : candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
1737 : :
1738 [ # # ]: 0 : CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
1739 [ # # ]: 0 : candidate_spks.insert(wsh);
1740 [ # # # # ]: 0 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
1741 : 0 : };
1742 [ # # # # ]: 0 : for (const auto& [_, script] : mapScripts) {
1743 [ # # ]: 0 : 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 [ # # ]: 0 : for (const auto& script : setWatchOnly) {
1749 [ # # ]: 0 : add_script(script);
1750 : : }
1751 : :
1752 [ # # ]: 0 : return candidate_spks;
1753 : 0 : }
1754 : :
1755 : 0 : 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 : 0 : std::unordered_set<CScript, SaltedSipHasher> spks;
1761 [ # # # # ]: 0 : for (const CScript& script : GetCandidateScriptPubKeys()) {
1762 [ # # # # ]: 0 : if (IsMine(script) != ISMINE_NO) {
1763 [ # # ]: 0 : spks.insert(script);
1764 : : }
1765 : 0 : }
1766 : :
1767 : 0 : return spks;
1768 : 0 : }
1769 : :
1770 : 0 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
1771 : : {
1772 : 0 : LOCK(cs_KeyStore);
1773 [ # # ]: 0 : std::unordered_set<CScript, SaltedSipHasher> spks;
1774 [ # # ]: 0 : for (const CScript& script : setWatchOnly) {
1775 [ # # # # : 0 : if (IsMine(script) == ISMINE_NO) spks.insert(script);
# # ]
1776 : : }
1777 [ # # ]: 0 : return spks;
1778 : 0 : }
1779 : :
1780 : 0 : std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
1781 : : {
1782 : 0 : LOCK(cs_KeyStore);
1783 [ # # # # ]: 0 : if (m_storage.IsLocked()) {
1784 : 0 : return std::nullopt;
1785 : : }
1786 : :
1787 : 0 : MigrationData out;
1788 : :
1789 [ # # ]: 0 : std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
1790 : :
1791 : : // Get all key ids
1792 : 0 : std::set<CKeyID> keyids;
1793 [ # # ]: 0 : for (const auto& key_pair : mapKeys) {
1794 [ # # ]: 0 : keyids.insert(key_pair.first);
1795 : : }
1796 [ # # ]: 0 : for (const auto& key_pair : mapCryptedKeys) {
1797 [ # # ]: 0 : 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 [ # # ]: 0 : for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
1803 : 0 : const CKeyID& keyid = *keyid_it;
1804 : 0 : const auto& it = mapKeyMetadata.find(keyid);
1805 [ # # ]: 0 : if (it != mapKeyMetadata.end()) {
1806 [ # # ]: 0 : const CKeyMetadata& meta = it->second;
1807 [ # # # # ]: 0 : if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
1808 : 0 : keyid_it++;
1809 : 0 : continue;
1810 : : }
1811 [ # # # # : 0 : 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 : 0 : keyid_it = keyids.erase(keyid_it);
1813 : 0 : continue;
1814 : : }
1815 : : }
1816 : 0 : keyid_it++;
1817 : : }
1818 : :
1819 [ # # # # ]: 0 : WalletBatch batch(m_storage.GetDatabase());
1820 [ # # # # ]: 0 : 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 [ # # ]: 0 : for (const CKeyID& keyid : keyids) {
1827 : 0 : CKey key;
1828 [ # # # # ]: 0 : if (!GetKey(keyid, key)) {
1829 : 0 : assert(false);
1830 : : }
1831 : :
1832 : : // Get birthdate from key meta
1833 : 0 : uint64_t creation_time = 0;
1834 : 0 : const auto& it = mapKeyMetadata.find(keyid);
1835 [ # # ]: 0 : if (it != mapKeyMetadata.end()) {
1836 : 0 : 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 [ # # ]: 0 : KeyOriginInfo info;
1842 [ # # ]: 0 : bool has_info = GetKeyOrigin(keyid, info);
1843 [ # # # # : 0 : std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
1844 : :
1845 : : // Construct the combo descriptor
1846 [ # # # # : 0 : std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
# # # # ]
1847 : 0 : FlatSigningProvider keys;
1848 [ # # ]: 0 : std::string error;
1849 [ # # ]: 0 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
1850 [ # # ]: 0 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
1851 [ # # # # : 0 : WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
# # ]
1852 : :
1853 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1854 [ # # ]: 0 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1855 [ # # # # : 0 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
# # ]
1856 [ # # ]: 0 : desc_spk_man->TopUpWithDB(batch);
1857 [ # # ]: 0 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
1858 : :
1859 : : // Remove the scriptPubKeys from our current set
1860 [ # # ]: 0 : for (const CScript& spk : desc_spks) {
1861 [ # # ]: 0 : size_t erased = spks.erase(spk);
1862 [ # # ]: 0 : assert(erased == 1);
1863 [ # # # # ]: 0 : assert(IsMine(spk) == ISMINE_SPENDABLE);
1864 : : }
1865 : :
1866 [ # # ]: 0 : out.desc_spkms.push_back(std::move(desc_spk_man));
1867 : 0 : }
1868 : :
1869 : : // Handle HD keys by using the CHDChains
1870 : 0 : std::vector<CHDChain> chains;
1871 [ # # ]: 0 : chains.push_back(m_hd_chain);
1872 [ # # ]: 0 : for (const auto& chain_pair : m_inactive_hd_chains) {
1873 [ # # ]: 0 : chains.push_back(chain_pair.second);
1874 : : }
1875 [ # # ]: 0 : for (const CHDChain& chain : chains) {
1876 [ # # ]: 0 : for (int i = 0; i < 2; ++i) {
1877 : : // Skip if doing internal chain and split chain is not supported
1878 [ # # # # : 0 : if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
# # # # ]
1879 : 0 : continue;
1880 : : }
1881 : : // Get the master xprv
1882 : 0 : CKey seed_key;
1883 [ # # # # ]: 0 : if (!GetKey(chain.seed_id, seed_key)) {
1884 : 0 : assert(false);
1885 : : }
1886 [ # # ]: 0 : CExtKey master_key;
1887 [ # # # # ]: 0 : master_key.SetSeed(seed_key);
1888 : :
1889 : : // Make the combo descriptor
1890 [ # # # # ]: 0 : std::string xpub = EncodeExtPubKey(master_key.Neuter());
1891 [ # # # # : 0 : std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
# # ]
1892 : 0 : FlatSigningProvider keys;
1893 [ # # ]: 0 : std::string error;
1894 [ # # ]: 0 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
1895 [ # # ]: 0 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
1896 [ # # ]: 0 : uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
1897 [ # # # # : 0 : WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
# # ]
1898 : :
1899 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1900 [ # # ]: 0 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1901 [ # # # # : 0 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
# # ]
1902 [ # # ]: 0 : desc_spk_man->TopUpWithDB(batch);
1903 [ # # ]: 0 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
1904 : :
1905 : : // Remove the scriptPubKeys from our current set
1906 [ # # ]: 0 : for (const CScript& spk : desc_spks) {
1907 [ # # ]: 0 : size_t erased = spks.erase(spk);
1908 [ # # ]: 0 : assert(erased == 1);
1909 [ # # # # ]: 0 : assert(IsMine(spk) == ISMINE_SPENDABLE);
1910 : : }
1911 : :
1912 [ # # ]: 0 : out.desc_spkms.push_back(std::move(desc_spk_man));
1913 : 0 : }
1914 : : }
1915 : : // Add the current master seed to the migration data
1916 [ # # ]: 0 : if (!m_hd_chain.seed_id.IsNull()) {
1917 : 0 : CKey seed_key;
1918 [ # # # # ]: 0 : if (!GetKey(m_hd_chain.seed_id, seed_key)) {
1919 : 0 : assert(false);
1920 : : }
1921 [ # # # # ]: 0 : out.master_key.SetSeed(seed_key);
1922 : 0 : }
1923 : :
1924 : : // Handle the rest of the scriptPubKeys which must be imports and may not have all info
1925 [ # # ]: 0 : for (auto it = spks.begin(); it != spks.end();) {
1926 [ # # ]: 0 : const CScript& spk = *it;
1927 : :
1928 : : // Get birthdate from script meta
1929 : 0 : uint64_t creation_time = 0;
1930 [ # # ]: 0 : const auto& mit = m_script_metadata.find(CScriptID(spk));
1931 [ # # ]: 0 : if (mit != m_script_metadata.end()) {
1932 : 0 : creation_time = mit->second.nCreateTime;
1933 : : }
1934 : :
1935 : : // InferDescriptor as that will get us all the solving info if it is there
1936 [ # # # # ]: 0 : 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 : 0 : {
1941 [ # # ]: 0 : std::string desc_str = desc->ToString();
1942 : 0 : FlatSigningProvider parsed_keys;
1943 [ # # ]: 0 : std::string parse_error;
1944 [ # # ]: 0 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
1945 [ # # ]: 0 : if (parsed_descs.empty()) {
1946 : : // Remove this scriptPubKey from the set
1947 : 0 : it = spks.erase(it);
1948 : 0 : continue;
1949 : : }
1950 : 0 : }
1951 : :
1952 : : // Get the private keys for this descriptor
1953 : 0 : std::vector<CScript> scripts;
1954 : 0 : FlatSigningProvider keys;
1955 [ # # # # ]: 0 : if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
1956 : 0 : assert(false);
1957 : : }
1958 : 0 : std::set<CKeyID> privkeyids;
1959 [ # # ]: 0 : for (const auto& key_orig_pair : keys.origins) {
1960 [ # # ]: 0 : privkeyids.insert(key_orig_pair.first);
1961 : : }
1962 : :
1963 : 0 : std::vector<CScript> desc_spks;
1964 : :
1965 : : // Make the descriptor string with private keys
1966 [ # # ]: 0 : std::string desc_str;
1967 [ # # ]: 0 : bool watchonly = !desc->ToPrivateString(*this, desc_str);
1968 [ # # # # : 0 : if (watchonly && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
# # ]
1969 [ # # # # ]: 0 : out.watch_descs.emplace_back(desc->ToString(), creation_time);
1970 : :
1971 : : // Get the scriptPubKeys without writing this to the wallet
1972 : 0 : FlatSigningProvider provider;
1973 [ # # ]: 0 : desc->Expand(0, provider, desc_spks, provider);
1974 : 0 : } else {
1975 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1976 [ # # # # ]: 0 : WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1977 [ # # ]: 0 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1978 [ # # ]: 0 : for (const auto& keyid : privkeyids) {
1979 : 0 : CKey key;
1980 [ # # # # ]: 0 : if (!GetKey(keyid, key)) {
1981 : 0 : continue;
1982 : : }
1983 [ # # # # : 0 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
# # ]
1984 : 0 : }
1985 [ # # ]: 0 : desc_spk_man->TopUpWithDB(batch);
1986 [ # # ]: 0 : auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
1987 [ # # ]: 0 : desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
1988 : :
1989 [ # # ]: 0 : out.desc_spkms.push_back(std::move(desc_spk_man));
1990 : 0 : }
1991 : :
1992 : : // Remove the scriptPubKeys from our current set
1993 [ # # ]: 0 : for (const CScript& desc_spk : desc_spks) {
1994 [ # # ]: 0 : auto del_it = spks.find(desc_spk);
1995 [ # # ]: 0 : assert(del_it != spks.end());
1996 [ # # # # ]: 0 : assert(IsMine(desc_spk) != ISMINE_NO);
1997 : 0 : it = spks.erase(del_it);
1998 : : }
1999 : 0 : }
2000 : :
2001 : : // Make sure that we have accounted for all scriptPubKeys
2002 [ # # # # ]: 0 : 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 [ # # # # ]: 0 : 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 [ # # # # : 0 : if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
# # # # ]
2015 : 0 : continue;
2016 : : }
2017 [ # # # # ]: 0 : if (IsMine(script) != ISMINE_NO) {
2018 : 0 : continue;
2019 : : }
2020 : 0 : SignatureData dummy_sigdata;
2021 [ # # # # ]: 0 : if (!CanProvide(script, dummy_sigdata)) {
2022 : 0 : continue;
2023 : : }
2024 : :
2025 : : // Get birthdate from script meta
2026 : 0 : uint64_t creation_time = 0;
2027 [ # # ]: 0 : const auto& it = m_script_metadata.find(CScriptID(script));
2028 [ # # ]: 0 : if (it != m_script_metadata.end()) {
2029 : 0 : creation_time = it->second.nCreateTime;
2030 : : }
2031 : :
2032 : : // InferDescriptor as that will get us all the solving info if it is there
2033 [ # # # # ]: 0 : std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
2034 [ # # # # ]: 0 : 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 : 0 : 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 : 0 : {
2043 [ # # ]: 0 : std::string desc_str = desc->ToString();
2044 : 0 : FlatSigningProvider parsed_keys;
2045 [ # # ]: 0 : std::string parse_error;
2046 [ # # ]: 0 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
2047 [ # # ]: 0 : if (parsed_descs.empty()) {
2048 : 0 : continue;
2049 : : }
2050 : 0 : }
2051 : :
2052 [ # # # # ]: 0 : out.solvable_descs.emplace_back(desc->ToString(), creation_time);
2053 : 0 : }
2054 : :
2055 : : // Finalize transaction
2056 [ # # # # ]: 0 : if (!batch.TxnCommit()) {
2057 [ # # ]: 0 : LogPrintf("Error generating descriptors for migration, cannot commit db transaction\n");
2058 : 0 : return std::nullopt;
2059 : : }
2060 : :
2061 : 0 : return out;
2062 : 0 : }
2063 : :
2064 : 0 : bool LegacyDataSPKM::DeleteRecords()
2065 : : {
2066 [ # # # # ]: 0 : return RunWithinTxn(m_storage.GetDatabase(), /*process_desc=*/"delete legacy records", [&](WalletBatch& batch){
2067 : 0 : return DeleteRecordsWithDB(batch);
2068 : 0 : });
2069 : : }
2070 : :
2071 : 0 : bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
2072 : : {
2073 : 0 : LOCK(cs_KeyStore);
2074 [ # # # # ]: 0 : return batch.EraseRecords(DBKeys::LEGACY_TYPES);
2075 : 0 : }
2076 : :
2077 : 217344 : 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 [ + + ]: 217344 : if (!CanGetAddresses()) {
2081 : 6046 : return util::Error{_("No addresses available")};
2082 : : }
2083 : 214321 : {
2084 : 214321 : LOCK(cs_desc_man);
2085 [ + - - + ]: 214321 : assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
2086 [ + - ]: 214321 : std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
2087 [ - + ]: 214321 : assert(desc_addr_type);
2088 [ - + ]: 214321 : 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 [ + - ]: 214321 : TopUp();
2093 : :
2094 : : // Get the scriptPubKey from the descriptor
2095 : 214321 : FlatSigningProvider out_keys;
2096 : 214321 : std::vector<CScript> scripts_temp;
2097 [ - + - - : 214321 : 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 [ + - + + ]: 214321 : 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 [ + - ]: 567 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
2104 : : }
2105 : :
2106 : 214132 : CTxDestination dest;
2107 [ + - - + ]: 214132 : if (!ExtractDestination(scripts_temp[0], dest)) {
2108 [ # # ]: 0 : return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
2109 : : }
2110 : 214132 : m_wallet_descriptor.next_index++;
2111 [ + - + - : 214132 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
2112 : 214132 : return dest;
2113 [ + - ]: 428642 : }
2114 : : }
2115 : :
2116 : 2329761 : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
2117 : : {
2118 : 2329761 : LOCK(cs_desc_man);
2119 [ + + ]: 2329761 : if (m_map_script_pub_keys.count(script) > 0) {
2120 : 2328179 : return ISMINE_SPENDABLE;
2121 : : }
2122 : : return ISMINE_NO;
2123 : 2329761 : }
2124 : :
2125 : 0 : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
2126 : : {
2127 : 0 : LOCK(cs_desc_man);
2128 [ # # ]: 0 : if (!m_map_keys.empty()) {
2129 : : return false;
2130 : : }
2131 : :
2132 : 0 : bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
2133 : 0 : bool keyFail = false;
2134 [ # # ]: 0 : for (const auto& mi : m_map_crypted_keys) {
2135 : 0 : const CPubKey &pubkey = mi.second.first;
2136 : 0 : const std::vector<unsigned char> &crypted_secret = mi.second.second;
2137 : 0 : CKey key;
2138 [ # # # # ]: 0 : if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
2139 : : keyFail = true;
2140 : : break;
2141 : : }
2142 : 0 : keyPass = true;
2143 [ # # ]: 0 : if (m_decryption_thoroughly_checked)
2144 : : break;
2145 : 0 : }
2146 [ # # ]: 0 : 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 [ # # ]: 0 : if (keyFail || !keyPass) {
2151 : : return false;
2152 : : }
2153 : 0 : m_decryption_thoroughly_checked = true;
2154 : 0 : return true;
2155 : 0 : }
2156 : :
2157 : 0 : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
2158 : : {
2159 : 0 : LOCK(cs_desc_man);
2160 [ # # ]: 0 : if (!m_map_crypted_keys.empty()) {
2161 : : return false;
2162 : : }
2163 : :
2164 [ # # ]: 0 : for (const KeyMap::value_type& key_in : m_map_keys)
2165 : : {
2166 : 0 : const CKey &key = key_in.second;
2167 [ # # ]: 0 : CPubKey pubkey = key.GetPubKey();
2168 [ # # # # : 0 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
# # ]
2169 : 0 : std::vector<unsigned char> crypted_secret;
2170 [ # # # # : 0 : if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
# # ]
2171 : 0 : return false;
2172 : : }
2173 [ # # # # : 0 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
# # ]
2174 [ # # # # ]: 0 : batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2175 : 0 : }
2176 : 0 : m_map_keys.clear();
2177 : 0 : return true;
2178 : 0 : }
2179 : :
2180 : 84840 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
2181 : : {
2182 : 84840 : LOCK(cs_desc_man);
2183 [ + - ]: 84840 : auto op_dest = GetNewDestination(type);
2184 : 84840 : index = m_wallet_descriptor.next_index - 1;
2185 [ + - ]: 84840 : return op_dest;
2186 : 84840 : }
2187 : :
2188 : 2520 : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
2189 : : {
2190 : 2520 : LOCK(cs_desc_man);
2191 : : // Only return when the index was the most recent
2192 [ + - ]: 2520 : if (m_wallet_descriptor.next_index - 1 == index) {
2193 : 2520 : m_wallet_descriptor.next_index--;
2194 : : }
2195 [ + - + - : 2520 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
2196 [ + - ]: 2520 : NotifyCanGetAddressesChanged();
2197 : 2520 : }
2198 : :
2199 : 424620 : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
2200 : : {
2201 : 424620 : AssertLockHeld(cs_desc_man);
2202 [ - + - - ]: 424620 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
2203 : 0 : KeyMap keys;
2204 [ # # ]: 0 : for (const auto& key_pair : m_map_crypted_keys) {
2205 : 0 : const CPubKey& pubkey = key_pair.second.first;
2206 : 0 : const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
2207 : 0 : CKey key;
2208 [ # # # # ]: 0 : m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
2209 : 0 : return DecryptKey(encryption_key, crypted_secret, pubkey, key);
2210 : : });
2211 [ # # # # : 0 : keys[pubkey.GetID()] = key;
# # ]
2212 : 0 : }
2213 : : return keys;
2214 : 0 : }
2215 : 424620 : return m_map_keys;
2216 : : }
2217 : :
2218 : 0 : bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
2219 : : {
2220 : 0 : AssertLockHeld(cs_desc_man);
2221 [ # # # # ]: 0 : return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
2222 : : }
2223 : :
2224 : 0 : std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
2225 : : {
2226 : 0 : AssertLockHeld(cs_desc_man);
2227 [ # # # # ]: 0 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
2228 : 0 : const auto& it = m_map_crypted_keys.find(keyid);
2229 [ # # ]: 0 : if (it == m_map_crypted_keys.end()) {
2230 : 0 : return std::nullopt;
2231 : : }
2232 [ # # ]: 0 : const std::vector<unsigned char>& crypted_secret = it->second.second;
2233 : 0 : CKey key;
2234 [ # # # # : 0 : 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 : 0 : return key;
2240 : 0 : }
2241 : 0 : const auto& it = m_map_keys.find(keyid);
2242 [ # # ]: 0 : if (it == m_map_keys.end()) {
2243 : 0 : return std::nullopt;
2244 : : }
2245 : 0 : return it->second;
2246 : : }
2247 : :
2248 : 380192 : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
2249 : : {
2250 : 380192 : WalletBatch batch(m_storage.GetDatabase());
2251 [ + - + - ]: 380192 : if (!batch.TxnBegin()) return false;
2252 [ + - ]: 380192 : bool res = TopUpWithDB(batch, size);
2253 [ + - - + : 380192 : 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 : 380192 : }
2256 : :
2257 : 380192 : bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
2258 : : {
2259 : 380192 : LOCK(cs_desc_man);
2260 [ + - ]: 380192 : std::set<CScript> new_spks;
2261 : 380192 : unsigned int target_size;
2262 [ + - ]: 380192 : if (size > 0) {
2263 : : target_size = size;
2264 : : } else {
2265 : 380192 : target_size = m_keypool_size;
2266 : : }
2267 : :
2268 : : // Calculate the new range_end
2269 [ + - ]: 380192 : 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 [ + - + + ]: 380192 : if (!m_wallet_descriptor.descriptor->IsRange()) {
2273 : 6520 : new_range_end = 1;
2274 : 6520 : m_wallet_descriptor.range_end = 1;
2275 : 6520 : m_wallet_descriptor.range_start = 0;
2276 : : }
2277 : :
2278 : 380192 : FlatSigningProvider provider;
2279 [ + - ]: 760384 : provider.keys = GetKeys();
2280 : :
2281 [ + - ]: 380192 : uint256 id = GetID();
2282 [ + + ]: 641941 : for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
2283 : 263278 : FlatSigningProvider out_keys;
2284 : 263278 : std::vector<CScript> scripts_temp;
2285 : 263278 : DescriptorCache temp_cache;
2286 : : // Maybe we have a cached xpub and we can expand from the cache first
2287 [ + - + + ]: 263278 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2288 [ + - + + ]: 58052 : 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 [ + - ]: 261749 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
2292 [ + + ]: 526784 : for (const CScript& script : scripts_temp) {
2293 [ + - ]: 265035 : m_map_script_pub_keys[script] = i;
2294 : : }
2295 [ + + ]: 523927 : for (const auto& pk_pair : out_keys.pubkeys) {
2296 : 262178 : const CPubKey& pubkey = pk_pair.second;
2297 [ + + ]: 262178 : 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 : 2527 : continue;
2301 : : }
2302 [ + - ]: 259651 : m_map_pubkeys[pubkey] = i;
2303 : : }
2304 : : // Merge and write the cache
2305 [ + - ]: 261749 : DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2306 [ + - - + ]: 261749 : if (!batch.WriteDescriptorCacheItems(id, new_items)) {
2307 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2308 : : }
2309 : 261749 : m_max_cached_index++;
2310 : 263278 : }
2311 : 378663 : m_wallet_descriptor.range_end = new_range_end;
2312 [ + - + - ]: 378663 : batch.WriteDescriptor(GetID(), m_wallet_descriptor);
2313 : :
2314 : : // By this point, the cache size should be the size of the entire range
2315 [ - + ]: 378663 : assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
2316 : :
2317 [ + - ]: 378663 : m_storage.TopUpCallback(new_spks, this);
2318 [ + - ]: 378663 : NotifyCanGetAddressesChanged();
2319 : : return true;
2320 [ + - ]: 760384 : }
2321 : :
2322 : 106755 : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
2323 : : {
2324 : 106755 : LOCK(cs_desc_man);
2325 : 106755 : std::vector<WalletDestination> result;
2326 [ + - + - ]: 106755 : if (IsMine(script)) {
2327 [ + - ]: 106755 : int32_t index = m_map_script_pub_keys[script];
2328 [ + + ]: 106755 : if (index >= m_wallet_descriptor.next_index) {
2329 [ + - ]: 172 : WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
2330 [ + - ]: 172 : auto out_keys = std::make_unique<FlatSigningProvider>();
2331 : 172 : std::vector<CScript> scripts_temp;
2332 [ + + ]: 344 : while (index >= m_wallet_descriptor.next_index) {
2333 [ + - - + ]: 172 : 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 : 172 : CTxDestination dest;
2337 [ + - ]: 172 : ExtractDestination(scripts_temp[0], dest);
2338 : 172 : result.push_back({dest, std::nullopt});
2339 : 172 : m_wallet_descriptor.next_index++;
2340 : 172 : }
2341 [ + - ]: 344 : }
2342 [ + - - + ]: 106755 : if (!TopUp()) {
2343 [ # # ]: 0 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
2344 : : }
2345 : : }
2346 : :
2347 [ + - ]: 106755 : return result;
2348 [ + - + - ]: 107099 : }
2349 : :
2350 : 56119 : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
2351 : : {
2352 : 56119 : LOCK(cs_desc_man);
2353 [ + - + - ]: 56119 : WalletBatch batch(m_storage.GetDatabase());
2354 [ + - - + ]: 56119 : if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
2355 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
2356 : : }
2357 [ + - ]: 112238 : }
2358 : :
2359 : 56119 : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
2360 : : {
2361 : 56119 : AssertLockHeld(cs_desc_man);
2362 [ - + ]: 56119 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
2363 : :
2364 : : // Check if provided key already exists
2365 [ + + - + ]: 112126 : if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
2366 [ - + ]: 56007 : m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
2367 : 112 : return true;
2368 : : }
2369 : :
2370 [ - + ]: 56007 : if (m_storage.HasEncryptionKeys()) {
2371 [ # # ]: 0 : if (m_storage.IsLocked()) {
2372 : : return false;
2373 : : }
2374 : :
2375 : 0 : std::vector<unsigned char> crypted_secret;
2376 [ # # # # : 0 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
# # ]
2377 [ # # # # : 0 : if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
# # ]
2378 : 0 : return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
2379 : : })) {
2380 : : return false;
2381 : : }
2382 : :
2383 [ # # # # : 0 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
# # ]
2384 [ # # # # ]: 0 : return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2385 : 0 : } else {
2386 : 56007 : m_map_keys[pubkey.GetID()] = key;
2387 [ + - + - ]: 56007 : return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
2388 : : }
2389 : : }
2390 : :
2391 : 0 : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
2392 : : {
2393 : 0 : LOCK(cs_desc_man);
2394 [ # # # # ]: 0 : assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
2395 : :
2396 : : // Ignore when there is already a descriptor
2397 [ # # ]: 0 : if (m_wallet_descriptor.descriptor) {
2398 : : return false;
2399 : : }
2400 : :
2401 [ # # # # ]: 0 : m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
2402 : :
2403 : : // Store the master private key, and descriptor
2404 [ # # # # : 0 : 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 [ # # # # : 0 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
# # ]
2408 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2409 : : }
2410 : :
2411 : : // TopUp
2412 [ # # ]: 0 : TopUpWithDB(batch);
2413 : :
2414 [ # # ]: 0 : m_storage.UnsetBlankWalletFlag(batch);
2415 : : return true;
2416 : 0 : }
2417 : :
2418 : 2526 : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
2419 : : {
2420 : 2526 : LOCK(cs_desc_man);
2421 [ + - + - ]: 2526 : return m_wallet_descriptor.descriptor->IsRange();
2422 : 2526 : }
2423 : :
2424 : 217344 : 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 : 217344 : LOCK(cs_desc_man);
2429 [ + - + + ]: 434688 : return m_wallet_descriptor.descriptor->IsSingleType() &&
2430 [ + - + - : 431908 : m_wallet_descriptor.descriptor->IsRange() &&
+ + ]
2431 [ + - + + : 432151 : (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
+ - ]
2432 : 217344 : }
2433 : :
2434 : 1152312 : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
2435 : : {
2436 : 1152312 : LOCK(cs_desc_man);
2437 [ + + - + : 1152312 : return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
+ - ]
2438 : 1152312 : }
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 : 0 : std::optional<int64_t> DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
2447 : : {
2448 : : // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
2449 : 0 : return std::nullopt;
2450 : : }
2451 : :
2452 : :
2453 : 5583 : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
2454 : : {
2455 : 5583 : LOCK(cs_desc_man);
2456 [ + - ]: 5583 : return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2457 : 5583 : }
2458 : :
2459 : 58981 : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
2460 : : {
2461 : 58981 : LOCK(cs_desc_man);
2462 [ + - ]: 58981 : return m_wallet_descriptor.creation_time;
2463 : 58981 : }
2464 : :
2465 : 1108851 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
2466 : : {
2467 : 1108851 : LOCK(cs_desc_man);
2468 : :
2469 : : // Find the index of the script
2470 : 1108851 : auto it = m_map_script_pub_keys.find(script);
2471 [ + + ]: 1108851 : if (it == m_map_script_pub_keys.end()) {
2472 : 171103 : return nullptr;
2473 : : }
2474 [ + - ]: 937748 : int32_t index = it->second;
2475 : :
2476 [ + - ]: 937748 : return GetSigningProvider(index, include_private);
2477 : 1108851 : }
2478 : :
2479 : 977 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
2480 : : {
2481 : 977 : LOCK(cs_desc_man);
2482 : :
2483 : : // Find index of the pubkey
2484 : 977 : auto it = m_map_pubkeys.find(pubkey);
2485 [ + - ]: 977 : if (it == m_map_pubkeys.end()) {
2486 : 977 : return nullptr;
2487 : : }
2488 [ # # ]: 0 : 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 [ # # ]: 0 : std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
2492 [ # # # # : 0 : if (!out->HaveKey(pubkey.GetID())) {
# # ]
2493 : 0 : return nullptr;
2494 : : }
2495 : 0 : return out;
2496 : 977 : }
2497 : :
2498 : 937748 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
2499 : : {
2500 : 937748 : AssertLockHeld(cs_desc_man);
2501 : :
2502 : 937748 : std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
2503 : :
2504 : : // Fetch SigningProvider from cache to avoid re-deriving
2505 : 937748 : auto it = m_map_signing_providers.find(index);
2506 [ + + ]: 937748 : if (it != m_map_signing_providers.end()) {
2507 [ + - + - ]: 808408 : out_keys->Merge(FlatSigningProvider{it->second});
2508 : : } else {
2509 : : // Get the scripts, keys, and key origins for this script
2510 : 129340 : std::vector<CScript> scripts_temp;
2511 [ + - - + ]: 129340 : 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 [ + - + - ]: 129340 : m_map_signing_providers[index] = *out_keys;
2515 : 129340 : }
2516 : :
2517 [ + - + + : 937748 : if (HavePrivateKeys() && include_private) {
+ + ]
2518 : 38845 : FlatSigningProvider master_provider;
2519 [ + - ]: 77690 : master_provider.keys = GetKeys();
2520 [ + - ]: 38845 : m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2521 : 38845 : }
2522 : :
2523 : 937748 : return out_keys;
2524 : 937748 : }
2525 : :
2526 : 878833 : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
2527 : : {
2528 [ - + ]: 878833 : return GetSigningProvider(script, false);
2529 : : }
2530 : :
2531 : 983690 : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
2532 : : {
2533 : 983690 : return IsMine(script);
2534 : : }
2535 : :
2536 : 7403 : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2537 : : {
2538 : 7403 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2539 [ + + ]: 195925 : for (const auto& coin_pair : coins) {
2540 [ + - ]: 188522 : std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
2541 [ + + ]: 188522 : if (!coin_keys) {
2542 : 156652 : continue;
2543 : : }
2544 [ + - ]: 31870 : keys->Merge(std::move(*coin_keys));
2545 : 188522 : }
2546 : :
2547 [ + - + - ]: 7403 : return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2548 : 7403 : }
2549 : :
2550 : 20414 : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2551 : : {
2552 [ + - + - ]: 40828 : std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
2553 [ + + ]: 20414 : if (!keys) {
2554 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2555 : : }
2556 : :
2557 : 7330 : CKey key;
2558 [ + - + - : 7330 : if (!keys->GetKey(ToKeyID(pkhash), key)) {
+ + ]
2559 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2560 : : }
2561 : :
2562 [ + - - + ]: 6975 : if (!MessageSign(key, message, str_sig)) {
2563 : 0 : return SigningResult::SIGNING_FAILED;
2564 : : }
2565 : : return SigningResult::OK;
2566 : 27744 : }
2567 : :
2568 : 2176 : 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 [ - + ]: 2176 : if (n_signed) {
2571 : 0 : *n_signed = 0;
2572 : : }
2573 [ + + ]: 3748 : for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2574 : 1572 : const CTxIn& txin = psbtx.tx->vin[i];
2575 : 1572 : PSBTInput& input = psbtx.inputs.at(i);
2576 : :
2577 [ + + ]: 1572 : if (PSBTInputSigned(input)) {
2578 : 59 : continue;
2579 : : }
2580 : :
2581 : : // Get the Sighash type
2582 [ + + - + : 1513 : 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 : 1513 : CScript script;
2588 [ + + ]: 1513 : if (!input.witness_utxo.IsNull()) {
2589 : 668 : script = input.witness_utxo.scriptPubKey;
2590 [ - + ]: 845 : } else if (input.non_witness_utxo) {
2591 [ # # ]: 0 : if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
2592 : 0 : return PSBTError::MISSING_INPUTS;
2593 : : }
2594 : 0 : 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 : 845 : continue;
2598 : : }
2599 : :
2600 [ + - ]: 668 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2601 [ + - ]: 668 : std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
2602 [ - + ]: 668 : if (script_keys) {
2603 [ # # ]: 0 : keys->Merge(std::move(*script_keys));
2604 : : } else {
2605 : : // Maybe there are pubkeys listed that we can sign for
2606 : 668 : std::vector<CPubKey> pubkeys;
2607 [ + - ]: 668 : pubkeys.reserve(input.hd_keypaths.size() + 2);
2608 : :
2609 : : // ECDSA Pubkeys
2610 [ + - + + ]: 675 : for (const auto& [pk, _] : input.hd_keypaths) {
2611 [ + - ]: 7 : pubkeys.push_back(pk);
2612 : : }
2613 : :
2614 : : // Taproot output pubkey
2615 : 668 : std::vector<std::vector<unsigned char>> sols;
2616 [ + - - + ]: 668 : if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
2617 [ # # ]: 0 : sols[0].insert(sols[0].begin(), 0x02);
2618 [ # # ]: 0 : pubkeys.emplace_back(sols[0]);
2619 [ # # ]: 0 : sols[0][0] = 0x03;
2620 [ # # ]: 0 : pubkeys.emplace_back(sols[0]);
2621 : : }
2622 : :
2623 : : // Taproot pubkeys
2624 [ + + ]: 1153 : for (const auto& pk_pair : input.m_tap_bip32_paths) {
2625 : 485 : const XOnlyPubKey& pubkey = pk_pair.first;
2626 [ + + ]: 1455 : for (unsigned char prefix : {0x02, 0x03}) {
2627 : 970 : unsigned char b[33] = {prefix};
2628 : 970 : std::copy(pubkey.begin(), pubkey.end(), b + 1);
2629 : 970 : CPubKey fullpubkey;
2630 : 970 : fullpubkey.Set(b, b + 33);
2631 [ + - ]: 970 : pubkeys.push_back(fullpubkey);
2632 : : }
2633 : : }
2634 : :
2635 [ + + ]: 1645 : for (const auto& pubkey : pubkeys) {
2636 [ + - ]: 977 : std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
2637 [ - + ]: 977 : if (pk_keys) {
2638 [ # # ]: 0 : keys->Merge(std::move(*pk_keys));
2639 : : }
2640 : 977 : }
2641 : 668 : }
2642 : :
2643 [ + - ]: 668 : SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
2644 : :
2645 [ + - ]: 668 : bool signed_one = PSBTInputSigned(input);
2646 [ - + - - ]: 668 : 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 : 0 : (*n_signed)++;
2651 : : }
2652 [ + - ]: 2181 : }
2653 : :
2654 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
2655 [ + + ]: 2875 : for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
2656 : 699 : std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2657 [ + - ]: 699 : if (!keys) {
2658 : 699 : continue;
2659 : : }
2660 [ # # ]: 0 : UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
2661 : 699 : }
2662 : :
2663 : 2176 : return {};
2664 : : }
2665 : :
2666 : 20414 : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
2667 : : {
2668 [ + - ]: 20414 : std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
2669 [ + - ]: 20414 : if (provider) {
2670 [ + - ]: 20414 : KeyOriginInfo orig;
2671 [ + - ]: 20414 : CKeyID key_id = GetKeyForDestination(*provider, dest);
2672 [ + - + + ]: 20414 : if (provider->GetKeyOrigin(key_id, orig)) {
2673 [ + - ]: 16124 : LOCK(cs_desc_man);
2674 [ + - ]: 16124 : std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
2675 [ + - ]: 16124 : meta->key_origin = orig;
2676 [ + - ]: 16124 : meta->has_key_origin = true;
2677 : 16124 : meta->nCreateTime = m_wallet_descriptor.creation_time;
2678 [ + - ]: 16124 : return meta;
2679 : 16124 : }
2680 : 20414 : }
2681 : 4290 : return nullptr;
2682 : 20414 : }
2683 : :
2684 : 1198879 : uint256 DescriptorScriptPubKeyMan::GetID() const
2685 : : {
2686 : 1198879 : LOCK(cs_desc_man);
2687 [ + - ]: 1198879 : return m_wallet_descriptor.id;
2688 : 1198879 : }
2689 : :
2690 : 0 : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
2691 : : {
2692 : 0 : LOCK(cs_desc_man);
2693 [ # # ]: 0 : std::set<CScript> new_spks;
2694 [ # # ]: 0 : m_wallet_descriptor.cache = cache;
2695 [ # # ]: 0 : for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2696 : 0 : FlatSigningProvider out_keys;
2697 : 0 : std::vector<CScript> scripts_temp;
2698 [ # # # # ]: 0 : 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 [ # # ]: 0 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
2703 [ # # ]: 0 : for (const CScript& script : scripts_temp) {
2704 [ # # ]: 0 : 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 [ # # ]: 0 : m_map_script_pub_keys[script] = i;
2708 : : }
2709 [ # # ]: 0 : for (const auto& pk_pair : out_keys.pubkeys) {
2710 : 0 : const CPubKey& pubkey = pk_pair.second;
2711 [ # # ]: 0 : 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 [ # # ]: 0 : m_map_pubkeys[pubkey] = i;
2717 : : }
2718 : 0 : m_max_cached_index++;
2719 : 0 : }
2720 : : // Make sure the wallet knows about our new spks
2721 [ # # ]: 0 : m_storage.TopUpCallback(new_spks, this);
2722 [ # # ]: 0 : }
2723 : :
2724 : 0 : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
2725 : : {
2726 : 0 : LOCK(cs_desc_man);
2727 [ # # # # ]: 0 : m_map_keys[key_id] = key;
2728 [ # # ]: 0 : return true;
2729 : 0 : }
2730 : :
2731 : 0 : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
2732 : : {
2733 : 0 : LOCK(cs_desc_man);
2734 [ # # ]: 0 : if (!m_map_keys.empty()) {
2735 : : return false;
2736 : : }
2737 : :
2738 [ # # # # ]: 0 : m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2739 : 0 : return true;
2740 : 0 : }
2741 : :
2742 : 364494 : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
2743 : : {
2744 : 364494 : LOCK(cs_desc_man);
2745 [ + - + - : 719796 : return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
+ + + - ]
2746 : 364494 : }
2747 : :
2748 : 57776 : void DescriptorScriptPubKeyMan::WriteDescriptor()
2749 : : {
2750 : 57776 : LOCK(cs_desc_man);
2751 [ + - + - ]: 57776 : WalletBatch batch(m_storage.GetDatabase());
2752 [ + - + - : 57776 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
- + ]
2753 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2754 : : }
2755 [ + - ]: 115552 : }
2756 : :
2757 : 8294 : WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
2758 : : {
2759 : 8294 : return m_wallet_descriptor;
2760 : : }
2761 : :
2762 : 14735 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
2763 : : {
2764 : 14735 : return GetScriptPubKeys(0);
2765 : : }
2766 : :
2767 : 14735 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
2768 : : {
2769 : 14735 : LOCK(cs_desc_man);
2770 [ + - ]: 14735 : std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
2771 [ + - ]: 14735 : script_pub_keys.reserve(m_map_script_pub_keys.size());
2772 : :
2773 [ + - + + ]: 50481 : for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
2774 [ + - + - ]: 35746 : if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
2775 : : }
2776 [ + - ]: 14735 : return script_pub_keys;
2777 : 14735 : }
2778 : :
2779 : 5583 : int32_t DescriptorScriptPubKeyMan::GetEndRange() const
2780 : : {
2781 : 5583 : return m_max_cached_index + 1;
2782 : : }
2783 : :
2784 : 5583 : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
2785 : : {
2786 : 5583 : LOCK(cs_desc_man);
2787 : :
2788 : 5583 : FlatSigningProvider provider;
2789 [ + - ]: 11166 : provider.keys = GetKeys();
2790 : :
2791 [ + + ]: 5583 : 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 [ + - ]: 1672 : return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
2796 : : }
2797 : :
2798 [ + - ]: 3911 : return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
2799 [ + - ]: 11166 : }
2800 : :
2801 : 0 : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
2802 : : {
2803 : 0 : LOCK(cs_desc_man);
2804 [ # # # # : 0 : 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 [ # # # # ]: 0 : if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
2810 : : return;
2811 : : }
2812 : :
2813 : : // Expand the descriptor
2814 : 0 : FlatSigningProvider provider;
2815 [ # # ]: 0 : provider.keys = GetKeys();
2816 : 0 : FlatSigningProvider out_keys;
2817 : 0 : std::vector<CScript> scripts_temp;
2818 : 0 : DescriptorCache temp_cache;
2819 [ # # # # ]: 0 : 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 [ # # ]: 0 : DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2825 [ # # # # : 0 : if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
# # # # #
# ]
2826 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2827 : : }
2828 [ # # ]: 0 : }
2829 : :
2830 : 135 : void DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
2831 : : {
2832 : 135 : LOCK(cs_desc_man);
2833 [ + - ]: 135 : std::string error;
2834 [ + - - + ]: 135 : if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2835 [ # # # # : 0 : throw std::runtime_error(std::string(__func__) + ": " + error);
# # ]
2836 : : }
2837 : :
2838 : 135 : m_map_pubkeys.clear();
2839 : 135 : m_map_script_pub_keys.clear();
2840 : 135 : m_max_cached_index = -1;
2841 [ + - ]: 135 : m_wallet_descriptor = descriptor;
2842 : :
2843 [ + - ]: 135 : NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
2844 [ + - ]: 270 : }
2845 : :
2846 : 1595 : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
2847 : : {
2848 : 1595 : LOCK(cs_desc_man);
2849 [ + - + + ]: 1595 : if (!HasWalletDescriptor(descriptor)) {
2850 [ + - + - ]: 1595 : error = "can only update matching descriptor";
2851 : : return false;
2852 : : }
2853 : :
2854 [ + - ]: 549 : if (descriptor.range_start > m_wallet_descriptor.range_start ||
2855 [ + + ]: 549 : descriptor.range_end < m_wallet_descriptor.range_end) {
2856 : : // Use inclusive range for error
2857 : 558 : error = strprintf("new range must include current range = [%d,%d]",
2858 : 279 : m_wallet_descriptor.range_start,
2859 [ + - ]: 279 : m_wallet_descriptor.range_end - 1);
2860 : 279 : return false;
2861 : : }
2862 : :
2863 : : return true;
2864 : 1595 : }
2865 : : } // namespace wallet
|