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