Branch data Line data Source code
1 : : // Copyright (c) 2019-present 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 : :
29 : : typedef std::vector<unsigned char> valtype;
30 : :
31 : : // Legacy wallet IsMine(). Used only in migration
32 : : // DO NOT USE ANYTHING IN THIS NAMESPACE OUTSIDE OF MIGRATION
33 : : namespace {
34 : :
35 : : /**
36 : : * This is an enum that tracks the execution context of a script, similar to
37 : : * SigVersion in script/interpreter. It is separate however because we want to
38 : : * distinguish between top-level scriptPubKey execution and P2SH redeemScript
39 : : * execution (a distinction that has no impact on consensus rules).
40 : : */
41 : : enum class IsMineSigVersion
42 : : {
43 : : TOP = 0, //!< scriptPubKey execution
44 : : P2SH = 1, //!< P2SH redeemScript
45 : : WITNESS_V0 = 2, //!< P2WSH witness script execution
46 : : };
47 : :
48 : : /**
49 : : * This is an internal representation of isminetype + invalidity.
50 : : * Its order is significant, as we return the max of all explored
51 : : * possibilities.
52 : : */
53 : : enum class IsMineResult
54 : : {
55 : : NO = 0, //!< Not ours
56 : : WATCH_ONLY = 1, //!< Included in watch-only balance
57 : : SPENDABLE = 2, //!< Included in all balances
58 : : INVALID = 3, //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
59 : : };
60 : :
61 : 1773 : bool PermitsUncompressed(IsMineSigVersion sigversion)
62 : : {
63 : 1773 : return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
64 : : }
65 : :
66 : 42 : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
67 : : {
68 [ + + ]: 102 : for (const valtype& pubkey : pubkeys) {
69 : 93 : CKeyID keyID = CPubKey(pubkey).GetID();
70 [ + + ]: 93 : if (!keystore.HaveKey(keyID)) return false;
71 : : }
72 : : return true;
73 : : }
74 : :
75 : : //! Recursively solve script and return spendable/watchonly/invalid status.
76 : : //!
77 : : //! @param keystore legacy key and script store
78 : : //! @param scriptPubKey script to solve
79 : : //! @param sigversion script type (top-level / redeemscript / witnessscript)
80 : : //! @param recurse_scripthash whether to recurse into nested p2sh and p2wsh
81 : : //! scripts or simply treat any script that has been
82 : : //! stored in the keystore as spendable
83 : : // NOLINTNEXTLINE(misc-no-recursion)
84 : 4950 : IsMineResult LegacyWalletIsMineInnerDONOTUSE(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
85 : : {
86 : 4950 : IsMineResult ret = IsMineResult::NO;
87 : :
88 : 4950 : std::vector<valtype> vSolutions;
89 [ + - ]: 4950 : TxoutType whichType = Solver(scriptPubKey, vSolutions);
90 : :
91 [ + + + + : 4950 : CKeyID keyID;
+ + + ]
92 [ + + + + : 4950 : switch (whichType) {
+ + + ]
93 : : case TxoutType::NONSTANDARD:
94 : : case TxoutType::NULL_DATA:
95 : : case TxoutType::WITNESS_UNKNOWN:
96 : : case TxoutType::WITNESS_V1_TAPROOT:
97 : : case TxoutType::ANCHOR:
98 : : break;
99 : 388 : case TxoutType::PUBKEY:
100 [ + - ]: 388 : keyID = CPubKey(vSolutions[0]).GetID();
101 [ - + - - ]: 388 : if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
102 : : return IsMineResult::INVALID;
103 : : }
104 [ + - + + ]: 388 : if (keystore.HaveKey(keyID)) {
105 [ - + ]: 358 : ret = std::max(ret, IsMineResult::SPENDABLE);
106 : : }
107 : : break;
108 : 948 : case TxoutType::WITNESS_V0_KEYHASH:
109 : 948 : {
110 [ + - ]: 948 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
111 : : // P2WPKH inside P2WSH is invalid.
112 : : return IsMineResult::INVALID;
113 : : }
114 [ + + + - : 1337 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
+ - + - +
+ + + ]
115 : : // We do not support bare witness outputs unless the P2SH version of it would be
116 : : // acceptable as well. This protects against matching before segwit activates.
117 : : // This also applies to the P2WSH case.
118 : : break;
119 : : }
120 [ + - + - : 959 : ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
+ + ]
121 : 935 : break;
122 : : }
123 : 1343 : case TxoutType::PUBKEYHASH:
124 [ + + ]: 1343 : keyID = CKeyID(uint160(vSolutions[0]));
125 [ + + ]: 1343 : if (!PermitsUncompressed(sigversion)) {
126 [ + - ]: 953 : CPubKey pubkey;
127 [ + - + - : 953 : if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
+ + ]
128 : : return IsMineResult::INVALID;
129 : : }
130 : : }
131 [ + - + + ]: 1338 : if (keystore.HaveKey(keyID)) {
132 [ - + ]: 1272 : ret = std::max(ret, IsMineResult::SPENDABLE);
133 : : }
134 : : break;
135 : 1431 : case TxoutType::SCRIPTHASH:
136 : 1431 : {
137 [ + + ]: 1431 : if (sigversion != IsMineSigVersion::TOP) {
138 : : // P2SH inside P2WSH or P2SH is invalid.
139 : : return IsMineResult::INVALID;
140 : : }
141 [ + - ]: 1421 : CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
142 : 1421 : CScript subscript;
143 [ + - + + ]: 1421 : if (keystore.GetCScript(scriptID, subscript)) {
144 [ + + + - : 681 : ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
+ + ]
145 : : }
146 : 1421 : break;
147 : 1421 : }
148 : 768 : case TxoutType::WITNESS_V0_SCRIPTHASH:
149 : 768 : {
150 [ + + ]: 768 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
151 : : // P2WSH inside P2WSH is invalid.
152 : : return IsMineResult::INVALID;
153 : : }
154 [ + + + - : 1496 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
+ - + - +
+ + + ]
155 : : break;
156 : : }
157 [ + - ]: 71 : CScriptID scriptID{RIPEMD160(vSolutions[0])};
158 : 71 : CScript subscript;
159 [ + - + + ]: 71 : if (keystore.GetCScript(scriptID, subscript)) {
160 [ + + + - : 87 : ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
+ + ]
161 : : }
162 : 71 : break;
163 : 71 : }
164 : :
165 : 48 : case TxoutType::MULTISIG:
166 : 48 : {
167 : : // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
168 [ + + ]: 48 : if (sigversion == IsMineSigVersion::TOP) {
169 : : break;
170 : : }
171 : :
172 : : // Only consider transactions "mine" if we own ALL the
173 : : // keys involved. Multi-signature transactions that are
174 : : // partially owned (somebody else has a key that can spend
175 : : // them) enable spend-out-from-under-you attacks, especially
176 : : // in shared-wallet situations.
177 [ + - ]: 42 : std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
178 [ + + ]: 42 : if (!PermitsUncompressed(sigversion)) {
179 [ + + ]: 104 : for (size_t i = 0; i < keys.size(); i++) {
180 [ - + ]: 75 : if (keys[i].size() != 33) {
181 : 0 : return IsMineResult::INVALID;
182 : : }
183 : : }
184 : : }
185 [ + - + + ]: 42 : if (HaveKeys(keys, keystore)) {
186 [ - + ]: 9 : ret = std::max(ret, IsMineResult::SPENDABLE);
187 : : }
188 : 42 : break;
189 : 42 : }
190 : : } // no default case, so the compiler can warn about missing cases
191 : :
192 [ + + + - : 4930 : if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
+ + ]
193 [ - + ]: 146 : ret = std::max(ret, IsMineResult::WATCH_ONLY);
194 : : }
195 : 4930 : return ret;
196 : 4950 : }
197 : :
198 : : } // namespace
199 : :
200 : 2814 : isminetype LegacyDataSPKM::IsMine(const CScript& script) const
201 : : {
202 [ + + - + ]: 2814 : switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
203 : : case IsMineResult::INVALID:
204 : : case IsMineResult::NO:
205 : : return ISMINE_NO;
206 : 146 : case IsMineResult::WATCH_ONLY:
207 : 146 : return ISMINE_WATCH_ONLY;
208 : 1639 : case IsMineResult::SPENDABLE:
209 : 1639 : return ISMINE_SPENDABLE;
210 : : }
211 : 0 : assert(false);
212 : : }
213 : :
214 : 1 : bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
215 : : {
216 : 1 : {
217 : 1 : LOCK(cs_KeyStore);
218 [ - + ]: 1 : assert(mapKeys.empty());
219 : :
220 [ + - ]: 1 : bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
221 : 1 : bool keyFail = false;
222 [ + - ]: 1 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
223 [ + - + - ]: 1 : WalletBatch batch(m_storage.GetDatabase());
224 [ + - ]: 1 : for (; mi != mapCryptedKeys.end(); ++mi)
225 : : {
226 [ + - ]: 1 : const CPubKey &vchPubKey = (*mi).second.first;
227 : 1 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
228 : 1 : CKey key;
229 [ + - + - ]: 1 : if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
230 : : {
231 : : keyFail = true;
232 : : break;
233 : : }
234 : 1 : keyPass = true;
235 [ - + ]: 1 : if (fDecryptionThoroughlyChecked)
236 : : break;
237 : : else {
238 : : // Rewrite these encrypted keys with checksums
239 [ # # # # : 0 : batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
# # ]
240 : : }
241 : 1 : }
242 [ - + ]: 1 : if (keyPass && keyFail)
243 : : {
244 [ # # ]: 0 : LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
245 [ # # ]: 0 : throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
246 : : }
247 [ - + ]: 1 : if (keyFail || !keyPass)
248 : 0 : return false;
249 : 1 : fDecryptionThoroughlyChecked = true;
250 [ - - + - ]: 1 : }
251 : 1 : return true;
252 : : }
253 : :
254 : 81 : std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
255 : : {
256 : 81 : return std::make_unique<LegacySigningProvider>(*this);
257 : : }
258 : :
259 : 507 : bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
260 : : {
261 : 507 : IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
262 [ + + ]: 507 : if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
263 : : // If ismine, it means we recognize keys or script ids in the script, or
264 : : // are watching the script itself, and we can at least provide metadata
265 : : // or solving information, even if not able to sign fully.
266 : : return true;
267 : : } else {
268 : : // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
269 : 482 : ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
270 [ + + ]: 482 : if (!sigdata.signatures.empty()) {
271 : : // If we could make signatures, make sure we have a private key to actually make a signature
272 : 1 : bool has_privkeys = false;
273 [ + + ]: 2 : for (const auto& key_sig_pair : sigdata.signatures) {
274 : 1 : has_privkeys |= HaveKey(key_sig_pair.first);
275 : : }
276 : : return has_privkeys;
277 : : }
278 : : return false;
279 : : }
280 : : }
281 : :
282 : 173 : bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
283 : : {
284 : 173 : return AddKeyPubKeyInner(key, pubkey);
285 : : }
286 : :
287 : 83 : bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
288 : : {
289 : : /* A sanity check was added in pull #3843 to avoid adding redeemScripts
290 : : * that never can be redeemed. However, old wallets may still contain
291 : : * these. Do not add them to the wallet and warn. */
292 [ + + - + ]: 83 : if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
293 : : {
294 [ # # ]: 0 : std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
295 [ # # # # ]: 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);
296 : 0 : return true;
297 : 0 : }
298 : :
299 : 83 : return FillableSigningProvider::AddCScript(redeemScript);
300 : : }
301 : :
302 : 201 : void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
303 : : {
304 : 201 : LOCK(cs_KeyStore);
305 [ + - + - ]: 201 : mapKeyMetadata[keyID] = meta;
306 : 201 : }
307 : :
308 : 44 : void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
309 : : {
310 : 44 : LOCK(cs_KeyStore);
311 [ + - + - ]: 44 : m_script_metadata[script_id] = meta;
312 : 44 : }
313 : :
314 : 173 : bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
315 : : {
316 : 173 : LOCK(cs_KeyStore);
317 [ + - + - ]: 173 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
318 : 173 : }
319 : :
320 : 24 : bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
321 : : {
322 : : // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
323 [ - + ]: 24 : if (!checksum_valid) {
324 : 0 : fDecryptionThoroughlyChecked = false;
325 : : }
326 : :
327 : 24 : return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
328 : : }
329 : :
330 : 24 : bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
331 : : {
332 : 24 : LOCK(cs_KeyStore);
333 [ - + ]: 24 : assert(mapKeys.empty());
334 : :
335 [ + - + - : 48 : mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
+ - ]
336 [ + - ]: 24 : ImplicitlyLearnRelatedKeyScripts(vchPubKey);
337 [ + - ]: 24 : return true;
338 : 24 : }
339 : :
340 : 1710 : bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
341 : : {
342 : 1710 : LOCK(cs_KeyStore);
343 [ + - ]: 1710 : return setWatchOnly.count(dest) > 0;
344 : 1710 : }
345 : :
346 : 44 : bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
347 : : {
348 : 44 : return AddWatchOnlyInMem(dest);
349 : : }
350 : :
351 : 44 : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
352 : : {
353 : 44 : std::vector<std::vector<unsigned char>> solutions;
354 [ + - + + : 53 : return Solver(dest, solutions) == TxoutType::PUBKEY &&
- + ]
355 [ + - ]: 53 : (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
356 : 44 : }
357 : :
358 : 44 : bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
359 : : {
360 : 44 : LOCK(cs_KeyStore);
361 [ + - ]: 44 : setWatchOnly.insert(dest);
362 [ + - ]: 44 : CPubKey pubKey;
363 [ + - + + ]: 44 : if (ExtractPubKey(dest, pubKey)) {
364 [ + - + - ]: 9 : mapWatchKeys[pubKey.GetID()] = pubKey;
365 [ + - ]: 9 : ImplicitlyLearnRelatedKeyScripts(pubKey);
366 : : }
367 [ + - ]: 44 : return true;
368 : 44 : }
369 : :
370 : 27 : void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
371 : : {
372 : 27 : LOCK(cs_KeyStore);
373 [ + - ]: 27 : m_hd_chain = chain;
374 : 27 : }
375 : :
376 : 6 : void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
377 : : {
378 : 6 : LOCK(cs_KeyStore);
379 [ - + ]: 6 : assert(!chain.seed_id.IsNull());
380 [ + - + - ]: 6 : m_inactive_hd_chains[chain.seed_id] = chain;
381 : 6 : }
382 : :
383 : 1820 : bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
384 : : {
385 : 1820 : LOCK(cs_KeyStore);
386 [ + - + + ]: 1820 : if (!m_storage.HasEncryptionKeys()) {
387 [ + - ]: 1766 : return FillableSigningProvider::HaveKey(address);
388 : : }
389 : 54 : return mapCryptedKeys.count(address) > 0;
390 : 1820 : }
391 : :
392 : 1153 : bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
393 : : {
394 : 1153 : LOCK(cs_KeyStore);
395 [ + - + + ]: 1153 : if (!m_storage.HasEncryptionKeys()) {
396 [ + - ]: 1146 : return FillableSigningProvider::GetKey(address, keyOut);
397 : : }
398 : :
399 : 7 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
400 [ + - ]: 7 : if (mi != mapCryptedKeys.end())
401 : : {
402 [ + - ]: 7 : const CPubKey &vchPubKey = (*mi).second.first;
403 : 7 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
404 [ + - + - ]: 7 : return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
405 : 7 : return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
406 : : });
407 : : }
408 : : return false;
409 : 1153 : }
410 : :
411 : 126 : bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
412 : : {
413 : 126 : CKeyMetadata meta;
414 : 126 : {
415 [ + - ]: 126 : LOCK(cs_KeyStore);
416 : 126 : auto it = mapKeyMetadata.find(keyID);
417 [ + + ]: 126 : if (it == mapKeyMetadata.end()) {
418 [ + - ]: 48 : return false;
419 : : }
420 [ + - ]: 78 : meta = it->second;
421 : 48 : }
422 [ + + ]: 78 : if (meta.has_key_origin) {
423 : 42 : std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
424 [ + - ]: 42 : info.path = meta.key_origin.path;
425 : : } else { // Single pubkeys get the master fingerprint of themselves
426 : 36 : std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
427 : : }
428 : : return true;
429 : 126 : }
430 : :
431 : 72 : bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
432 : : {
433 : 72 : LOCK(cs_KeyStore);
434 : 72 : WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
435 [ + + ]: 72 : if (it != mapWatchKeys.end()) {
436 : 64 : pubkey_out = it->second;
437 : 64 : return true;
438 : : }
439 : : return false;
440 : 72 : }
441 : :
442 : 991 : bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
443 : : {
444 : 991 : LOCK(cs_KeyStore);
445 [ + - + + ]: 991 : if (!m_storage.HasEncryptionKeys()) {
446 [ + - + + ]: 961 : if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
447 [ + - ]: 72 : return GetWatchPubKey(address, vchPubKeyOut);
448 : : }
449 : : return true;
450 : : }
451 : :
452 : 30 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
453 [ + - ]: 30 : if (mi != mapCryptedKeys.end())
454 : : {
455 : 30 : vchPubKeyOut = (*mi).second.first;
456 : 30 : return true;
457 : : }
458 : : // Check for watch-only pubkeys
459 [ # # ]: 0 : return GetWatchPubKey(address, vchPubKeyOut);
460 : 991 : }
461 : :
462 : 58 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
463 : : {
464 : 58 : LOCK(cs_KeyStore);
465 [ + - ]: 58 : std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
466 : :
467 : : // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
468 : 416 : const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
469 [ + - ]: 358 : candidate_spks.insert(GetScriptForRawPubKey(pub));
470 [ + - ]: 716 : candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
471 : :
472 [ + - ]: 358 : CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
473 [ + - ]: 358 : candidate_spks.insert(wpkh);
474 [ + - + - ]: 716 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
475 : 358 : };
476 [ + - + + ]: 404 : for (const auto& [_, key] : mapKeys) {
477 [ + - + - ]: 346 : add_pubkey(key.GetPubKey());
478 : : }
479 [ + - + + ]: 70 : for (const auto& [_, ckeypair] : mapCryptedKeys) {
480 [ + - ]: 12 : add_pubkey(ckeypair.first);
481 : : }
482 : :
483 : : // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
484 : : // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
485 : : // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
486 : : // Callers of this function will need to remove such scripts.
487 : 578 : const auto& add_script = [&candidate_spks](const CScript& script) -> void {
488 : 520 : candidate_spks.insert(script);
489 [ + - ]: 1040 : candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
490 : :
491 [ + - ]: 520 : CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
492 [ + - ]: 520 : candidate_spks.insert(wsh);
493 [ + - + - ]: 1040 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
494 : 520 : };
495 [ + - + + ]: 490 : for (const auto& [_, script] : mapScripts) {
496 [ + - ]: 432 : add_script(script);
497 : : }
498 : :
499 : : // Although setWatchOnly should only contain output scripts, we will also include each script's
500 : : // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
501 [ + + ]: 146 : for (const auto& script : setWatchOnly) {
502 [ + - ]: 88 : add_script(script);
503 : : }
504 : :
505 [ + - ]: 58 : return candidate_spks;
506 : 58 : }
507 : :
508 : 29 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
509 : : {
510 : : // Run IsMine() on each candidate output script. Any script that is not ISMINE_NO is an output
511 : : // script to return.
512 : : // This both filters out things that are not watched by the wallet, and things that are invalid.
513 : 29 : std::unordered_set<CScript, SaltedSipHasher> spks;
514 [ + - + + : 1317 : for (const CScript& script : GetCandidateScriptPubKeys()) {
+ - ]
515 [ + + + - ]: 1288 : if (IsMine(script) != ISMINE_NO) {
516 [ + - ]: 770 : spks.insert(script);
517 : : }
518 : 0 : }
519 : :
520 : 29 : return spks;
521 : 0 : }
522 : :
523 : 28 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
524 : : {
525 : 28 : LOCK(cs_KeyStore);
526 [ + - ]: 28 : std::unordered_set<CScript, SaltedSipHasher> spks;
527 [ + + ]: 71 : for (const CScript& script : setWatchOnly) {
528 [ + - + + : 43 : if (IsMine(script) == ISMINE_NO) spks.insert(script);
+ - ]
529 : : }
530 [ + - ]: 28 : return spks;
531 : 28 : }
532 : :
533 : 29 : std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
534 : : {
535 : 29 : LOCK(cs_KeyStore);
536 [ + - - + ]: 29 : if (m_storage.IsLocked()) {
537 : 0 : return std::nullopt;
538 : : }
539 : :
540 : 29 : MigrationData out;
541 : :
542 [ + - ]: 29 : std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
543 : :
544 : : // Get all key ids
545 : 29 : std::set<CKeyID> keyids;
546 [ + + ]: 202 : for (const auto& key_pair : mapKeys) {
547 [ + - ]: 173 : keyids.insert(key_pair.first);
548 : : }
549 [ + + ]: 35 : for (const auto& key_pair : mapCryptedKeys) {
550 [ + - ]: 6 : keyids.insert(key_pair.first);
551 : : }
552 : :
553 : : // Get key metadata and figure out which keys don't have a seed
554 : : // Note that we do not ignore the seeds themselves because they are considered IsMine!
555 [ + + ]: 208 : for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
556 : 179 : const CKeyID& keyid = *keyid_it;
557 : 179 : const auto& it = mapKeyMetadata.find(keyid);
558 [ + - ]: 179 : if (it != mapKeyMetadata.end()) {
559 [ + + ]: 179 : const CKeyMetadata& meta = it->second;
560 [ + + + + ]: 179 : if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
561 : 28 : keyid_it++;
562 : 28 : continue;
563 : : }
564 [ + + + + : 151 : 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)) {
+ - + - ]
565 : 147 : keyid_it = keyids.erase(keyid_it);
566 : 147 : continue;
567 : : }
568 : : }
569 : 4 : keyid_it++;
570 : : }
571 : :
572 [ + - + - ]: 29 : WalletBatch batch(m_storage.GetDatabase());
573 [ + - - + ]: 29 : if (!batch.TxnBegin()) {
574 [ # # ]: 0 : LogPrintf("Error generating descriptors for migration, cannot initialize db transaction\n");
575 : 0 : return std::nullopt;
576 : : }
577 : :
578 : : // keyids is now all non-HD keys. Each key will have its own combo descriptor
579 [ + + ]: 61 : for (const CKeyID& keyid : keyids) {
580 : 32 : CKey key;
581 [ + - - + ]: 32 : if (!GetKey(keyid, key)) {
582 : 0 : assert(false);
583 : : }
584 : :
585 : : // Get birthdate from key meta
586 : 32 : uint64_t creation_time = 0;
587 : 32 : const auto& it = mapKeyMetadata.find(keyid);
588 [ + - ]: 32 : if (it != mapKeyMetadata.end()) {
589 : 32 : creation_time = it->second.nCreateTime;
590 : : }
591 : :
592 : : // Get the key origin
593 : : // Maybe this doesn't matter because floating keys here shouldn't have origins
594 [ + - ]: 32 : KeyOriginInfo info;
595 [ + - ]: 32 : bool has_info = GetKeyOrigin(keyid, info);
596 [ + - + - : 160 : std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
+ - + - +
- + - - -
+ - + - +
- - - - -
- - - - ]
597 : :
598 : : // Construct the combo descriptor
599 [ + - + - : 64 : std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
+ - + - ]
600 : 32 : FlatSigningProvider keys;
601 [ + - ]: 32 : std::string error;
602 [ + - ]: 32 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
603 [ + - ]: 32 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
604 [ + - + - : 32 : WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
+ - ]
605 : :
606 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
607 [ + - ]: 32 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
608 [ + - + - : 96 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
+ - ]
609 [ + - ]: 32 : desc_spk_man->TopUpWithDB(batch);
610 [ + - ]: 32 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
611 : :
612 : : // Remove the scriptPubKeys from our current set
613 [ + + + - ]: 158 : for (const CScript& spk : desc_spks) {
614 [ + - ]: 126 : size_t erased = spks.erase(spk);
615 [ - + ]: 126 : assert(erased == 1);
616 [ + - - + ]: 126 : assert(IsMine(spk) == ISMINE_SPENDABLE);
617 : : }
618 : :
619 [ + - ]: 32 : out.desc_spkms.push_back(std::move(desc_spk_man));
620 : 32 : }
621 : :
622 : : // Handle HD keys by using the CHDChains
623 : 29 : std::vector<CHDChain> chains;
624 [ + - ]: 29 : chains.push_back(m_hd_chain);
625 [ + + + - ]: 32 : for (const auto& chain_pair : m_inactive_hd_chains) {
626 [ + - ]: 3 : chains.push_back(chain_pair.second);
627 : : }
628 [ + + ]: 61 : for (const CHDChain& chain : chains) {
629 [ + + ]: 96 : for (int i = 0; i < 2; ++i) {
630 : : // Skip if doing internal chain and split chain is not supported
631 [ + + + + : 64 : if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
+ - - + ]
632 : 10 : continue;
633 : : }
634 : : // Get the master xprv
635 : 54 : CKey seed_key;
636 [ + - - + ]: 54 : if (!GetKey(chain.seed_id, seed_key)) {
637 : 0 : assert(false);
638 : : }
639 [ + - ]: 54 : CExtKey master_key;
640 [ + - + - ]: 108 : master_key.SetSeed(seed_key);
641 : :
642 : : // Make the combo descriptor
643 [ + - + - ]: 54 : std::string xpub = EncodeExtPubKey(master_key.Neuter());
644 [ + - + - : 162 : std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
+ - ]
645 : 54 : FlatSigningProvider keys;
646 [ + - ]: 54 : std::string error;
647 [ + - ]: 54 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
648 [ + - ]: 54 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
649 [ + + ]: 54 : uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
650 [ + - + - : 54 : WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
+ - ]
651 : :
652 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
653 [ + - ]: 54 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
654 [ + - + - : 162 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
+ - ]
655 [ + - ]: 54 : desc_spk_man->TopUpWithDB(batch);
656 [ + - ]: 54 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
657 : :
658 : : // Remove the scriptPubKeys from our current set
659 [ + + + - ]: 642 : for (const CScript& spk : desc_spks) {
660 [ + - ]: 588 : size_t erased = spks.erase(spk);
661 [ - + ]: 588 : assert(erased == 1);
662 [ + - - + ]: 588 : assert(IsMine(spk) == ISMINE_SPENDABLE);
663 : : }
664 : :
665 [ + - ]: 54 : out.desc_spkms.push_back(std::move(desc_spk_man));
666 : 54 : }
667 : : }
668 : : // Add the current master seed to the migration data
669 [ + + ]: 29 : if (!m_hd_chain.seed_id.IsNull()) {
670 : 24 : CKey seed_key;
671 [ + - - + ]: 24 : if (!GetKey(m_hd_chain.seed_id, seed_key)) {
672 : 0 : assert(false);
673 : : }
674 [ + - + - ]: 48 : out.master_key.SetSeed(seed_key);
675 : 24 : }
676 : :
677 : : // Handle the rest of the scriptPubKeys which must be imports and may not have all info
678 [ + + ]: 85 : for (auto it = spks.begin(); it != spks.end();) {
679 [ + - ]: 56 : const CScript& spk = *it;
680 : :
681 : : // Get birthdate from script meta
682 : 56 : uint64_t creation_time = 0;
683 [ + - ]: 56 : const auto& mit = m_script_metadata.find(CScriptID(spk));
684 [ + + ]: 56 : if (mit != m_script_metadata.end()) {
685 : 39 : creation_time = mit->second.nCreateTime;
686 : : }
687 : :
688 : : // InferDescriptor as that will get us all the solving info if it is there
689 [ + - + - ]: 112 : std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
690 : :
691 : : // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
692 : : // Re-parse the descriptors to detect that, and skip any that do not parse.
693 : 56 : {
694 [ + - ]: 56 : std::string desc_str = desc->ToString();
695 : 56 : FlatSigningProvider parsed_keys;
696 [ + - ]: 56 : std::string parse_error;
697 [ + - ]: 56 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
698 [ - + ]: 56 : if (parsed_descs.empty()) {
699 : : // Remove this scriptPubKey from the set
700 : 0 : it = spks.erase(it);
701 : 0 : continue;
702 : : }
703 : 56 : }
704 : :
705 : : // Get the private keys for this descriptor
706 : 56 : std::vector<CScript> scripts;
707 : 56 : FlatSigningProvider keys;
708 [ + - - + ]: 56 : if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
709 : 0 : assert(false);
710 : : }
711 : 56 : std::set<CKeyID> privkeyids;
712 [ + + ]: 108 : for (const auto& key_orig_pair : keys.origins) {
713 [ + - ]: 52 : privkeyids.insert(key_orig_pair.first);
714 : : }
715 : :
716 : 56 : std::vector<CScript> desc_spks;
717 : :
718 : : // Make the descriptor string with private keys
719 [ + - ]: 56 : std::string desc_str;
720 [ + - ]: 56 : bool watchonly = !desc->ToPrivateString(*this, desc_str);
721 [ + + + - : 56 : if (watchonly && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
+ + ]
722 [ + - + - ]: 35 : out.watch_descs.emplace_back(desc->ToString(), creation_time);
723 : :
724 : : // Get the scriptPubKeys without writing this to the wallet
725 : 35 : FlatSigningProvider provider;
726 [ + - ]: 35 : desc->Expand(0, provider, desc_spks, provider);
727 : 35 : } else {
728 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
729 [ + - + - ]: 21 : WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
730 [ + - ]: 21 : auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
731 [ + + ]: 48 : for (const auto& keyid : privkeyids) {
732 : 27 : CKey key;
733 [ + - + + ]: 27 : if (!GetKey(keyid, key)) {
734 : 10 : continue;
735 : : }
736 [ + - + - : 51 : WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
+ - ]
737 : 27 : }
738 [ + - ]: 21 : desc_spk_man->TopUpWithDB(batch);
739 [ + - ]: 21 : auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
740 [ + - ]: 21 : desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
741 : :
742 [ + - ]: 21 : out.desc_spkms.push_back(std::move(desc_spk_man));
743 : 21 : }
744 : :
745 : : // Remove the scriptPubKeys from our current set
746 [ + + ]: 112 : for (const CScript& desc_spk : desc_spks) {
747 [ + - ]: 56 : auto del_it = spks.find(desc_spk);
748 [ + - ]: 56 : assert(del_it != spks.end());
749 [ + - - + ]: 56 : assert(IsMine(desc_spk) != ISMINE_NO);
750 : 56 : it = spks.erase(del_it);
751 : : }
752 : 56 : }
753 : :
754 : : // Make sure that we have accounted for all scriptPubKeys
755 [ - + ]: 29 : if (!Assume(spks.empty())) {
756 [ # # # # ]: 0 : LogPrintf("%s\n", STR_INTERNAL_BUG("Error: Some output scripts were not migrated.\n"));
757 : 0 : return std::nullopt;
758 : : }
759 : :
760 : : // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
761 : : // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
762 : : // be put into the separate "solvables" wallet.
763 : : // These can be detected by going through the entire candidate output scripts, finding the ISMINE_NO scripts,
764 : : // and checking CanProvide() which will dummy sign.
765 [ + - + + : 1317 : for (const CScript& script : GetCandidateScriptPubKeys()) {
+ - ]
766 : : // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
767 [ + + + - : 1288 : if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
+ + + - ]
768 : 575 : continue;
769 : : }
770 [ + - + + ]: 713 : if (IsMine(script) != ISMINE_NO) {
771 : 206 : continue;
772 : : }
773 : 507 : SignatureData dummy_sigdata;
774 [ + - + + ]: 507 : if (!CanProvide(script, dummy_sigdata)) {
775 : 482 : continue;
776 : : }
777 : :
778 : : // Get birthdate from script meta
779 : 25 : uint64_t creation_time = 0;
780 [ + - ]: 25 : const auto& it = m_script_metadata.find(CScriptID(script));
781 [ + + ]: 25 : if (it != m_script_metadata.end()) {
782 : 4 : creation_time = it->second.nCreateTime;
783 : : }
784 : :
785 : : // InferDescriptor as that will get us all the solving info if it is there
786 [ + - + - ]: 25 : std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
787 [ + - + + ]: 25 : if (!desc->IsSolvable()) {
788 : : // The wallet was able to provide some information, but not enough to make a descriptor that actually
789 : : // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
790 : 10 : continue;
791 : : }
792 : :
793 : : // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
794 : : // Re-parse the descriptors to detect that, and skip any that do not parse.
795 : 15 : {
796 [ + - ]: 15 : std::string desc_str = desc->ToString();
797 : 15 : FlatSigningProvider parsed_keys;
798 [ + - ]: 15 : std::string parse_error;
799 [ + - ]: 15 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
800 [ - + ]: 15 : if (parsed_descs.empty()) {
801 : 0 : continue;
802 : : }
803 : 15 : }
804 : :
805 [ + - + - ]: 15 : out.solvable_descs.emplace_back(desc->ToString(), creation_time);
806 : 507 : }
807 : :
808 : : // Finalize transaction
809 [ + - - + ]: 29 : if (!batch.TxnCommit()) {
810 [ # # ]: 0 : LogPrintf("Error generating descriptors for migration, cannot commit db transaction\n");
811 : 0 : return std::nullopt;
812 : : }
813 : :
814 : 29 : return out;
815 : 87 : }
816 : :
817 : 28 : bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
818 : : {
819 : 28 : LOCK(cs_KeyStore);
820 [ + - + - ]: 28 : return batch.EraseRecords(DBKeys::LEGACY_TYPES);
821 : 28 : }
822 : :
823 : 18160 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
824 : : {
825 : : // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
826 [ - + ]: 18160 : if (!CanGetAddresses()) {
827 : 0 : return util::Error{_("No addresses available")};
828 : : }
829 : 18160 : {
830 : 18160 : LOCK(cs_desc_man);
831 [ + - - + ]: 18160 : assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
832 [ + - ]: 18160 : std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
833 [ - + ]: 18160 : assert(desc_addr_type);
834 [ - + ]: 18160 : if (type != *desc_addr_type) {
835 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
836 : : }
837 : :
838 [ + - ]: 18160 : TopUp();
839 : :
840 : : // Get the scriptPubKey from the descriptor
841 : 18160 : FlatSigningProvider out_keys;
842 : 18160 : std::vector<CScript> scripts_temp;
843 [ - + - - : 18160 : if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
- - ]
844 : : // We can't generate anymore keys
845 [ # # ]: 0 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
846 : : }
847 [ + - + + ]: 18160 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
848 : : // We can't generate anymore keys
849 [ + - ]: 24 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
850 : : }
851 : :
852 : 18152 : CTxDestination dest;
853 [ + - - + ]: 18152 : if (!ExtractDestination(scripts_temp[0], dest)) {
854 [ # # ]: 0 : return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
855 : : }
856 : 18152 : m_wallet_descriptor.next_index++;
857 [ + - + - : 18152 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
858 : 18152 : return dest;
859 [ + - ]: 36320 : }
860 : : }
861 : :
862 : 762701 : isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
863 : : {
864 : 762701 : LOCK(cs_desc_man);
865 [ + + ]: 762701 : if (m_map_script_pub_keys.count(script) > 0) {
866 : 762649 : return ISMINE_SPENDABLE;
867 : : }
868 : : return ISMINE_NO;
869 : 762701 : }
870 : :
871 : 874 : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
872 : : {
873 : 874 : LOCK(cs_desc_man);
874 [ + - ]: 874 : if (!m_map_keys.empty()) {
875 : : return false;
876 : : }
877 : :
878 : 874 : bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
879 : 874 : bool keyFail = false;
880 [ + + ]: 1089 : for (const auto& mi : m_map_crypted_keys) {
881 : 736 : const CPubKey &pubkey = mi.second.first;
882 : 736 : const std::vector<unsigned char> &crypted_secret = mi.second.second;
883 : 736 : CKey key;
884 [ + - + - ]: 736 : if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
885 : : keyFail = true;
886 : : break;
887 : : }
888 : 736 : keyPass = true;
889 [ + + ]: 736 : if (m_decryption_thoroughly_checked)
890 : : break;
891 : 736 : }
892 [ - + ]: 874 : if (keyPass && keyFail) {
893 [ # # ]: 0 : LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
894 [ # # ]: 0 : throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
895 : : }
896 [ + - ]: 874 : if (keyFail || !keyPass) {
897 : : return false;
898 : : }
899 : 874 : m_decryption_thoroughly_checked = true;
900 : 874 : return true;
901 : 874 : }
902 : :
903 : 103 : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
904 : : {
905 : 103 : LOCK(cs_desc_man);
906 [ + - ]: 103 : if (!m_map_crypted_keys.empty()) {
907 : : return false;
908 : : }
909 : :
910 [ + + ]: 206 : for (const KeyMap::value_type& key_in : m_map_keys)
911 : : {
912 : 103 : const CKey &key = key_in.second;
913 [ + - ]: 103 : CPubKey pubkey = key.GetPubKey();
914 [ + - + - : 309 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
915 : 103 : std::vector<unsigned char> crypted_secret;
916 [ + - + - : 103 : if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
- + ]
917 : 0 : return false;
918 : : }
919 [ + - + - : 206 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
+ - ]
920 [ + - + - ]: 103 : batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
921 : 103 : }
922 : 103 : m_map_keys.clear();
923 : 103 : return true;
924 : 103 : }
925 : :
926 : 1912 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
927 : : {
928 : 1912 : LOCK(cs_desc_man);
929 [ + - ]: 1912 : auto op_dest = GetNewDestination(type);
930 : 1912 : index = m_wallet_descriptor.next_index - 1;
931 [ + - ]: 1912 : return op_dest;
932 : 1912 : }
933 : :
934 : 83 : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
935 : : {
936 : 83 : LOCK(cs_desc_man);
937 : : // Only return when the index was the most recent
938 [ + - ]: 83 : if (m_wallet_descriptor.next_index - 1 == index) {
939 : 83 : m_wallet_descriptor.next_index--;
940 : : }
941 [ + - + - : 83 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
942 [ + - ]: 83 : NotifyCanGetAddressesChanged();
943 : 83 : }
944 : :
945 : 86906 : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
946 : : {
947 : 86906 : AssertLockHeld(cs_desc_man);
948 [ + + + + ]: 86906 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
949 : 2289 : KeyMap keys;
950 [ + + ]: 4578 : for (const auto& key_pair : m_map_crypted_keys) {
951 : 2289 : const CPubKey& pubkey = key_pair.second.first;
952 : 2289 : const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
953 : 2289 : CKey key;
954 [ + - + - ]: 2289 : m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
955 : 2289 : return DecryptKey(encryption_key, crypted_secret, pubkey, key);
956 : : });
957 [ + - + - : 2289 : keys[pubkey.GetID()] = key;
+ - ]
958 : 2289 : }
959 : : return keys;
960 : 0 : }
961 : 84617 : return m_map_keys;
962 : : }
963 : :
964 : 225 : bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
965 : : {
966 : 225 : AssertLockHeld(cs_desc_man);
967 [ + + + + ]: 225 : return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
968 : : }
969 : :
970 : 72 : std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
971 : : {
972 : 72 : AssertLockHeld(cs_desc_man);
973 [ + + + - ]: 72 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
974 : 9 : const auto& it = m_map_crypted_keys.find(keyid);
975 [ - + ]: 9 : if (it == m_map_crypted_keys.end()) {
976 : 0 : return std::nullopt;
977 : : }
978 [ + - ]: 9 : const std::vector<unsigned char>& crypted_secret = it->second.second;
979 : 9 : CKey key;
980 [ + - + - : 18 : if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
- + ]
981 : : return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
982 : : }))) {
983 : 0 : return std::nullopt;
984 : : }
985 : 9 : return key;
986 : 9 : }
987 : 63 : const auto& it = m_map_keys.find(keyid);
988 [ + + ]: 63 : if (it == m_map_keys.end()) {
989 : 1 : return std::nullopt;
990 : : }
991 : 62 : return it->second;
992 : : }
993 : :
994 : 71399 : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
995 : : {
996 : 71399 : WalletBatch batch(m_storage.GetDatabase());
997 [ + - + + ]: 71399 : if (!batch.TxnBegin()) return false;
998 [ + - ]: 71398 : bool res = TopUpWithDB(batch, size);
999 [ + - - + : 71398 : if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
- - - - -
- ]
1000 : : return res;
1001 : 71399 : }
1002 : :
1003 : 74499 : bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1004 : : {
1005 : 74499 : LOCK(cs_desc_man);
1006 [ + + ]: 74499 : std::set<CScript> new_spks;
1007 : 74499 : unsigned int target_size;
1008 [ + + ]: 74499 : if (size > 0) {
1009 : : target_size = size;
1010 : : } else {
1011 : 74427 : target_size = m_keypool_size;
1012 : : }
1013 : :
1014 : : // Calculate the new range_end
1015 [ + + ]: 74499 : int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1016 : :
1017 : : // If the descriptor is not ranged, we actually just want to fill the first cache item
1018 [ + - + + ]: 74499 : if (!m_wallet_descriptor.descriptor->IsRange()) {
1019 : 12607 : new_range_end = 1;
1020 : 12607 : m_wallet_descriptor.range_end = 1;
1021 : 12607 : m_wallet_descriptor.range_start = 0;
1022 : : }
1023 : :
1024 : 74499 : FlatSigningProvider provider;
1025 [ + - ]: 148998 : provider.keys = GetKeys();
1026 : :
1027 [ + - ]: 74499 : uint256 id = GetID();
1028 [ + + ]: 511321 : for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1029 : 436929 : FlatSigningProvider out_keys;
1030 : 436929 : std::vector<CScript> scripts_temp;
1031 : 436929 : DescriptorCache temp_cache;
1032 : : // Maybe we have a cached xpub and we can expand from the cache first
1033 [ + - + + ]: 436929 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1034 [ + - + + ]: 13449 : if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1035 : : }
1036 : : // Add all of the scriptPubKeys to the scriptPubKey set
1037 [ + - ]: 436822 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1038 [ + + ]: 874713 : for (const CScript& script : scripts_temp) {
1039 [ + - ]: 437891 : m_map_script_pub_keys[script] = i;
1040 : : }
1041 [ + + ]: 920871 : for (const auto& pk_pair : out_keys.pubkeys) {
1042 : 484049 : const CPubKey& pubkey = pk_pair.second;
1043 [ + + ]: 484049 : if (m_map_pubkeys.count(pubkey) != 0) {
1044 : : // We don't need to give an error here.
1045 : : // 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
1046 : 10268 : continue;
1047 : : }
1048 [ + - ]: 473781 : m_map_pubkeys[pubkey] = i;
1049 : : }
1050 : : // Merge and write the cache
1051 [ + - ]: 436822 : DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1052 [ + - - + ]: 436822 : if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1053 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1054 : : }
1055 : 436822 : m_max_cached_index++;
1056 : 436929 : }
1057 : 74392 : m_wallet_descriptor.range_end = new_range_end;
1058 [ + - + - ]: 74392 : batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1059 : :
1060 : : // By this point, the cache size should be the size of the entire range
1061 [ - + ]: 74392 : assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1062 : :
1063 [ + - ]: 74392 : m_storage.TopUpCallback(new_spks, this);
1064 [ + - ]: 74392 : NotifyCanGetAddressesChanged();
1065 : : return true;
1066 [ + - ]: 148998 : }
1067 : :
1068 : 47839 : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1069 : : {
1070 : 47839 : LOCK(cs_desc_man);
1071 : 47839 : std::vector<WalletDestination> result;
1072 [ + - + - ]: 47839 : if (IsMine(script)) {
1073 [ + - ]: 47839 : int32_t index = m_map_script_pub_keys[script];
1074 [ + + ]: 47839 : if (index >= m_wallet_descriptor.next_index) {
1075 [ + - ]: 495 : WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1076 [ + - ]: 495 : auto out_keys = std::make_unique<FlatSigningProvider>();
1077 : 495 : std::vector<CScript> scripts_temp;
1078 [ + + ]: 28882 : while (index >= m_wallet_descriptor.next_index) {
1079 [ + - - + ]: 28387 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1080 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1081 : : }
1082 : 28387 : CTxDestination dest;
1083 [ + - ]: 28387 : ExtractDestination(scripts_temp[0], dest);
1084 : 28387 : result.push_back({dest, std::nullopt});
1085 : 28387 : m_wallet_descriptor.next_index++;
1086 : 28387 : }
1087 [ + - ]: 990 : }
1088 [ + - + + ]: 47839 : if (!TopUp()) {
1089 [ + - ]: 1 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1090 : : }
1091 : : }
1092 : :
1093 [ + - ]: 47839 : return result;
1094 [ + - + - ]: 104613 : }
1095 : :
1096 : 503 : void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
1097 : : {
1098 : 503 : LOCK(cs_desc_man);
1099 [ + - + - ]: 503 : WalletBatch batch(m_storage.GetDatabase());
1100 [ + - - + ]: 503 : if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1101 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1102 : : }
1103 [ + - ]: 1006 : }
1104 : :
1105 : 3592 : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
1106 : : {
1107 : 3592 : AssertLockHeld(cs_desc_man);
1108 [ - + ]: 3592 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1109 : :
1110 : : // Check if provided key already exists
1111 [ + + - + ]: 7176 : if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
1112 [ - + ]: 3584 : m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
1113 : 8 : return true;
1114 : : }
1115 : :
1116 [ + + ]: 3584 : if (m_storage.HasEncryptionKeys()) {
1117 [ + - ]: 162 : if (m_storage.IsLocked()) {
1118 : : return false;
1119 : : }
1120 : :
1121 : 162 : std::vector<unsigned char> crypted_secret;
1122 [ + - + - : 486 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
1123 [ + - + - : 162 : if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
+ - ]
1124 : 162 : return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1125 : : })) {
1126 : : return false;
1127 : : }
1128 : :
1129 [ + - + - : 324 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
+ - ]
1130 [ + - + - ]: 162 : return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1131 : 162 : } else {
1132 : 3422 : m_map_keys[pubkey.GetID()] = key;
1133 [ + - + - ]: 3422 : return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1134 : : }
1135 : : }
1136 : :
1137 : 2986 : bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1138 : : {
1139 : 2986 : LOCK(cs_desc_man);
1140 [ + - - + ]: 2986 : assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
1141 : :
1142 : : // Ignore when there is already a descriptor
1143 [ + - ]: 2986 : if (m_wallet_descriptor.descriptor) {
1144 : : return false;
1145 : : }
1146 : :
1147 [ + - + - ]: 2986 : m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1148 : :
1149 : : // Store the master private key, and descriptor
1150 [ + - + - : 2986 : if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
- + ]
1151 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1152 : : }
1153 [ + - + - : 2986 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
- + ]
1154 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1155 : : }
1156 : :
1157 : : // TopUp
1158 [ + - ]: 2986 : TopUpWithDB(batch);
1159 : :
1160 [ + - ]: 2986 : m_storage.UnsetBlankWalletFlag(batch);
1161 : : return true;
1162 : 2986 : }
1163 : :
1164 : 77 : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
1165 : : {
1166 : 77 : LOCK(cs_desc_man);
1167 [ + - + - ]: 77 : return m_wallet_descriptor.descriptor->IsRange();
1168 : 77 : }
1169 : :
1170 : 28485 : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
1171 : : {
1172 : : // We can only give out addresses from descriptors that are single type (not combo), ranged,
1173 : : // and either have cached keys or can generate more keys (ignoring encryption)
1174 : 28485 : LOCK(cs_desc_man);
1175 [ + - + - ]: 56970 : return m_wallet_descriptor.descriptor->IsSingleType() &&
1176 [ + - + - : 56970 : m_wallet_descriptor.descriptor->IsRange() &&
+ + ]
1177 [ + - - + : 56970 : (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
+ - ]
1178 : 28485 : }
1179 : :
1180 : 323216 : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1181 : : {
1182 : 323216 : LOCK(cs_desc_man);
1183 [ + + + + : 352404 : return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
+ - ]
1184 : 323216 : }
1185 : :
1186 : 0 : bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
1187 : : {
1188 : 0 : LOCK(cs_desc_man);
1189 [ # # ]: 0 : return !m_map_crypted_keys.empty();
1190 : 0 : }
1191 : :
1192 : 7544 : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
1193 : : {
1194 : 7544 : LOCK(cs_desc_man);
1195 [ + - ]: 7544 : return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1196 : 7544 : }
1197 : :
1198 : 10895 : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1199 : : {
1200 : 10895 : LOCK(cs_desc_man);
1201 [ + - ]: 10895 : return m_wallet_descriptor.creation_time;
1202 : 10895 : }
1203 : :
1204 : 403179 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1205 : : {
1206 : 403179 : LOCK(cs_desc_man);
1207 : :
1208 : : // Find the index of the script
1209 : 403179 : auto it = m_map_script_pub_keys.find(script);
1210 [ + + ]: 403179 : if (it == m_map_script_pub_keys.end()) {
1211 : 109028 : return nullptr;
1212 : : }
1213 [ + - ]: 294151 : int32_t index = it->second;
1214 : :
1215 [ + - ]: 294151 : return GetSigningProvider(index, include_private);
1216 : 403179 : }
1217 : :
1218 : 17108 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1219 : : {
1220 : 17108 : LOCK(cs_desc_man);
1221 : :
1222 : : // Find index of the pubkey
1223 : 17108 : auto it = m_map_pubkeys.find(pubkey);
1224 [ + + ]: 17108 : if (it == m_map_pubkeys.end()) {
1225 : 16534 : return nullptr;
1226 : : }
1227 [ + - ]: 574 : int32_t index = it->second;
1228 : :
1229 : : // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1230 [ + - ]: 574 : std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1231 [ + - + - : 574 : if (!out->HaveKey(pubkey.GetID())) {
+ + ]
1232 : 286 : return nullptr;
1233 : : }
1234 : 288 : return out;
1235 : 17682 : }
1236 : :
1237 : 294725 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1238 : : {
1239 : 294725 : AssertLockHeld(cs_desc_man);
1240 : :
1241 : 294725 : std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1242 : :
1243 : : // Fetch SigningProvider from cache to avoid re-deriving
1244 : 294725 : auto it = m_map_signing_providers.find(index);
1245 [ + + ]: 294725 : if (it != m_map_signing_providers.end()) {
1246 [ + - + - ]: 278750 : out_keys->Merge(FlatSigningProvider{it->second});
1247 : : } else {
1248 : : // Get the scripts, keys, and key origins for this script
1249 : 15975 : std::vector<CScript> scripts_temp;
1250 [ + - - + ]: 15975 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1251 : :
1252 : : // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1253 [ + - + - ]: 15975 : m_map_signing_providers[index] = *out_keys;
1254 : 15975 : }
1255 : :
1256 [ + - + + : 294725 : if (HavePrivateKeys() && include_private) {
+ + ]
1257 : 11005 : FlatSigningProvider master_provider;
1258 [ + - ]: 22010 : master_provider.keys = GetKeys();
1259 [ + - ]: 11005 : m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1260 : 11005 : }
1261 : :
1262 : 294725 : return out_keys;
1263 : 294725 : }
1264 : :
1265 : 345734 : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1266 : : {
1267 [ - + ]: 345734 : return GetSigningProvider(script, false);
1268 : : }
1269 : :
1270 : 364614 : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
1271 : : {
1272 : 364614 : return IsMine(script);
1273 : : }
1274 : :
1275 : 16883 : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1276 : : {
1277 : 16883 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1278 [ + + ]: 55554 : for (const auto& coin_pair : coins) {
1279 [ + - ]: 38671 : std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1280 [ + + ]: 38671 : if (!coin_keys) {
1281 : 29511 : continue;
1282 : : }
1283 [ + - ]: 9160 : keys->Merge(std::move(*coin_keys));
1284 : 38671 : }
1285 : :
1286 [ + - + - ]: 16883 : return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
1287 : 16883 : }
1288 : :
1289 : 9 : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1290 : : {
1291 [ + - + - ]: 18 : std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1292 [ + - ]: 9 : if (!keys) {
1293 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1294 : : }
1295 : :
1296 : 9 : CKey key;
1297 [ + - + - : 9 : if (!keys->GetKey(ToKeyID(pkhash), key)) {
+ - ]
1298 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1299 : : }
1300 : :
1301 [ + - - + ]: 9 : if (!MessageSign(key, message, str_sig)) {
1302 : 0 : return SigningResult::SIGNING_FAILED;
1303 : : }
1304 : : return SigningResult::OK;
1305 : 18 : }
1306 : :
1307 : 5779 : std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, std::optional<int> sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
1308 : : {
1309 [ + - ]: 5779 : if (n_signed) {
1310 : 5779 : *n_signed = 0;
1311 : : }
1312 [ + + ]: 30013 : for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
1313 : 24242 : const CTxIn& txin = psbtx.tx->vin[i];
1314 : 24242 : PSBTInput& input = psbtx.inputs.at(i);
1315 : :
1316 [ + + ]: 24242 : if (PSBTInputSigned(input)) {
1317 : 5930 : continue;
1318 : : }
1319 : :
1320 : : // Get the scriptPubKey to know which SigningProvider to use
1321 : 18312 : CScript script;
1322 [ + + ]: 18312 : if (!input.witness_utxo.IsNull()) {
1323 : 12460 : script = input.witness_utxo.scriptPubKey;
1324 [ + + ]: 5852 : } else if (input.non_witness_utxo) {
1325 [ + + ]: 5655 : if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
1326 : 1 : return PSBTError::MISSING_INPUTS;
1327 : : }
1328 : 5654 : script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
1329 : : } else {
1330 : : // There's no UTXO so we can just skip this now
1331 : 197 : continue;
1332 : : }
1333 : :
1334 [ + - ]: 18114 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1335 [ + - ]: 18114 : std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
1336 [ + + ]: 18114 : if (script_keys) {
1337 [ + - ]: 2779 : keys->Merge(std::move(*script_keys));
1338 : : } else {
1339 : : // Maybe there are pubkeys listed that we can sign for
1340 : 15335 : std::vector<CPubKey> pubkeys;
1341 [ + - ]: 15335 : pubkeys.reserve(input.hd_keypaths.size() + 2);
1342 : :
1343 : : // ECDSA Pubkeys
1344 [ + - + + ]: 26025 : for (const auto& [pk, _] : input.hd_keypaths) {
1345 [ + - ]: 10690 : pubkeys.push_back(pk);
1346 : : }
1347 : :
1348 : : // Taproot output pubkey
1349 : 15335 : std::vector<std::vector<unsigned char>> sols;
1350 [ + - + + ]: 15335 : if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
1351 [ + - ]: 982 : sols[0].insert(sols[0].begin(), 0x02);
1352 [ + - ]: 982 : pubkeys.emplace_back(sols[0]);
1353 [ + - ]: 982 : sols[0][0] = 0x03;
1354 [ + - ]: 982 : pubkeys.emplace_back(sols[0]);
1355 : : }
1356 : :
1357 : : // Taproot pubkeys
1358 [ + + ]: 17561 : for (const auto& pk_pair : input.m_tap_bip32_paths) {
1359 : 2226 : const XOnlyPubKey& pubkey = pk_pair.first;
1360 [ + + ]: 6678 : for (unsigned char prefix : {0x02, 0x03}) {
1361 : 4452 : unsigned char b[33] = {prefix};
1362 : 4452 : std::copy(pubkey.begin(), pubkey.end(), b + 1);
1363 : 4452 : CPubKey fullpubkey;
1364 : 4452 : fullpubkey.Set(b, b + 33);
1365 [ + - ]: 4452 : pubkeys.push_back(fullpubkey);
1366 : : }
1367 : : }
1368 : :
1369 [ + + ]: 32441 : for (const auto& pubkey : pubkeys) {
1370 [ + - ]: 17106 : std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1371 [ + + ]: 17106 : if (pk_keys) {
1372 [ + - ]: 287 : keys->Merge(std::move(*pk_keys));
1373 : : }
1374 : 17106 : }
1375 : 15335 : }
1376 : :
1377 [ + - + + ]: 18114 : PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
1378 [ + + ]: 18114 : if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1379 [ - + ]: 7 : return res;
1380 : : }
1381 : :
1382 [ + - ]: 18107 : bool signed_one = PSBTInputSigned(input);
1383 [ + - + + ]: 18107 : if (n_signed && (signed_one || !sign)) {
1384 : : // If sign is false, we assume that we _could_ sign if we get here. This
1385 : : // will never have false negatives; it is hard to tell under what i
1386 : : // circumstances it could have false positives.
1387 : 12919 : (*n_signed)++;
1388 : : }
1389 [ + - + - ]: 36433 : }
1390 : :
1391 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1392 [ + + ]: 70787 : for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1393 : 65850 : std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
1394 [ + + ]: 65016 : if (!keys) {
1395 : 64182 : continue;
1396 : : }
1397 [ + - ]: 834 : UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
1398 : 65016 : }
1399 : :
1400 : 5771 : return {};
1401 : : }
1402 : :
1403 : 651 : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1404 : : {
1405 [ + - ]: 651 : std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1406 [ + - ]: 651 : if (provider) {
1407 [ + - ]: 651 : KeyOriginInfo orig;
1408 [ + - ]: 651 : CKeyID key_id = GetKeyForDestination(*provider, dest);
1409 [ + - + + ]: 651 : if (provider->GetKeyOrigin(key_id, orig)) {
1410 [ + - ]: 565 : LOCK(cs_desc_man);
1411 [ + - ]: 565 : std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1412 [ + - ]: 565 : meta->key_origin = orig;
1413 [ + - ]: 565 : meta->has_key_origin = true;
1414 : 565 : meta->nCreateTime = m_wallet_descriptor.creation_time;
1415 [ + - ]: 565 : return meta;
1416 : 565 : }
1417 : 651 : }
1418 : 86 : return nullptr;
1419 : 651 : }
1420 : :
1421 : 181556 : uint256 DescriptorScriptPubKeyMan::GetID() const
1422 : : {
1423 : 181556 : LOCK(cs_desc_man);
1424 [ + - ]: 181556 : return m_wallet_descriptor.id;
1425 : 181556 : }
1426 : :
1427 : 2387 : void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
1428 : : {
1429 : 2387 : LOCK(cs_desc_man);
1430 [ + - ]: 2387 : std::set<CScript> new_spks;
1431 [ + - ]: 2387 : m_wallet_descriptor.cache = cache;
1432 [ + + ]: 59486 : for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1433 : 57099 : FlatSigningProvider out_keys;
1434 : 57099 : std::vector<CScript> scripts_temp;
1435 [ + - - + ]: 57099 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1436 [ # # ]: 0 : throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1437 : : }
1438 : : // Add all of the scriptPubKeys to the scriptPubKey set
1439 [ + - ]: 57099 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1440 [ + + ]: 115105 : for (const CScript& script : scripts_temp) {
1441 [ - + ]: 58006 : if (m_map_script_pub_keys.count(script) != 0) {
1442 [ # # # # : 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]));
# # ]
1443 : : }
1444 [ + - ]: 58006 : m_map_script_pub_keys[script] = i;
1445 : : }
1446 [ + + ]: 118211 : for (const auto& pk_pair : out_keys.pubkeys) {
1447 : 61112 : const CPubKey& pubkey = pk_pair.second;
1448 [ - + ]: 61112 : if (m_map_pubkeys.count(pubkey) != 0) {
1449 : : // We don't need to give an error here.
1450 : : // 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
1451 : 0 : continue;
1452 : : }
1453 [ + - ]: 61112 : m_map_pubkeys[pubkey] = i;
1454 : : }
1455 : 57099 : m_max_cached_index++;
1456 : 57099 : }
1457 : : // Make sure the wallet knows about our new spks
1458 [ + - ]: 2387 : m_storage.TopUpCallback(new_spks, this);
1459 [ + - ]: 4774 : }
1460 : :
1461 : 2070 : bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
1462 : : {
1463 : 2070 : LOCK(cs_desc_man);
1464 [ + - + - ]: 2070 : m_map_keys[key_id] = key;
1465 [ + - ]: 2070 : return true;
1466 : 2070 : }
1467 : :
1468 : 231 : bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
1469 : : {
1470 : 231 : LOCK(cs_desc_man);
1471 [ + - ]: 231 : if (!m_map_keys.empty()) {
1472 : : return false;
1473 : : }
1474 : :
1475 [ + - + - ]: 462 : m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
1476 : 231 : return true;
1477 : 231 : }
1478 : :
1479 : 40 : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
1480 : : {
1481 : 40 : LOCK(cs_desc_man);
1482 [ + - + - : 40 : return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
- + + - ]
1483 : 40 : }
1484 : :
1485 : 681 : void DescriptorScriptPubKeyMan::WriteDescriptor()
1486 : : {
1487 : 681 : LOCK(cs_desc_man);
1488 [ + - + - ]: 681 : WalletBatch batch(m_storage.GetDatabase());
1489 [ + - + - : 681 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
- + ]
1490 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1491 : : }
1492 [ + - ]: 1362 : }
1493 : :
1494 : 54755 : WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1495 : : {
1496 : 54755 : return m_wallet_descriptor;
1497 : : }
1498 : :
1499 : 421 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1500 : : {
1501 : 421 : return GetScriptPubKeys(0);
1502 : : }
1503 : :
1504 : 546 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1505 : : {
1506 : 546 : LOCK(cs_desc_man);
1507 [ + - ]: 546 : std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1508 [ + - ]: 546 : script_pub_keys.reserve(m_map_script_pub_keys.size());
1509 : :
1510 [ + + + + ]: 37345 : for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1511 [ + + + - ]: 36799 : if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1512 : : }
1513 [ + - ]: 546 : return script_pub_keys;
1514 : 546 : }
1515 : :
1516 : 4968 : int32_t DescriptorScriptPubKeyMan::GetEndRange() const
1517 : : {
1518 : 4968 : return m_max_cached_index + 1;
1519 : : }
1520 : :
1521 : 1190 : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1522 : : {
1523 : 1190 : LOCK(cs_desc_man);
1524 : :
1525 : 1190 : FlatSigningProvider provider;
1526 [ + - ]: 2380 : provider.keys = GetKeys();
1527 : :
1528 [ + + ]: 1190 : if (priv) {
1529 : : // For the private version, always return the master key to avoid
1530 : : // exposing child private keys. The risk implications of exposing child
1531 : : // private keys together with the parent xpub may be non-obvious for users.
1532 [ + - ]: 64 : return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1533 : : }
1534 : :
1535 [ + - ]: 1126 : return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1536 [ + - ]: 2380 : }
1537 : :
1538 : 1307 : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
1539 : : {
1540 : 1307 : LOCK(cs_desc_man);
1541 [ + - + - : 1307 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
+ - - + ]
1542 : 0 : return;
1543 : : }
1544 : :
1545 : : // Skip if we have the last hardened xpub cache
1546 [ + - + + ]: 1307 : if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1547 : : return;
1548 : : }
1549 : :
1550 : : // Expand the descriptor
1551 : 212 : FlatSigningProvider provider;
1552 [ + - ]: 424 : provider.keys = GetKeys();
1553 : 212 : FlatSigningProvider out_keys;
1554 : 212 : std::vector<CScript> scripts_temp;
1555 : 212 : DescriptorCache temp_cache;
1556 [ + - - + ]: 212 : if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1557 [ # # ]: 0 : throw std::runtime_error("Unable to expand descriptor");
1558 : : }
1559 : :
1560 : : // Cache the last hardened xpubs
1561 [ + - ]: 212 : DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1562 [ + - + - : 424 : if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
+ - + - -
+ ]
1563 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1564 : : }
1565 [ + - ]: 1519 : }
1566 : :
1567 : 20 : util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
1568 : : {
1569 : 20 : LOCK(cs_desc_man);
1570 [ + - ]: 20 : std::string error;
1571 [ + - + + ]: 20 : if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1572 [ + - ]: 9 : return util::Error{Untranslated(std::move(error))};
1573 : : }
1574 : :
1575 : 17 : m_map_pubkeys.clear();
1576 : 17 : m_map_script_pub_keys.clear();
1577 : 17 : m_max_cached_index = -1;
1578 [ + - ]: 17 : m_wallet_descriptor = descriptor;
1579 : :
1580 [ + - ]: 17 : NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1581 : 17 : return {};
1582 [ + - ]: 40 : }
1583 : :
1584 : 20 : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
1585 : : {
1586 : 20 : LOCK(cs_desc_man);
1587 [ + - - + ]: 20 : if (!HasWalletDescriptor(descriptor)) {
1588 [ - - + - ]: 20 : error = "can only update matching descriptor";
1589 : : return false;
1590 : : }
1591 : :
1592 [ + - + + ]: 20 : if (!descriptor.descriptor->IsRange()) {
1593 : : // Skip range check for non-range descriptors
1594 : : return true;
1595 : : }
1596 : :
1597 [ + + ]: 15 : if (descriptor.range_start > m_wallet_descriptor.range_start ||
1598 [ + + ]: 13 : descriptor.range_end < m_wallet_descriptor.range_end) {
1599 : : // Use inclusive range for error
1600 : 6 : error = strprintf("new range must include current range = [%d,%d]",
1601 : 3 : m_wallet_descriptor.range_start,
1602 [ + - ]: 3 : m_wallet_descriptor.range_end - 1);
1603 : 3 : return false;
1604 : : }
1605 : :
1606 : : return true;
1607 : 20 : }
1608 : : } // namespace wallet
|