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 : 2922 : bool PermitsUncompressed(IsMineSigVersion sigversion)
64 : : {
65 : 2922 : return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
66 : : }
67 : :
68 : 48 : bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
69 : : {
70 [ + + ]: 108 : for (const valtype& pubkey : pubkeys) {
71 [ - + ]: 99 : CKeyID keyID = CPubKey(pubkey).GetID();
72 [ + + ]: 99 : 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 : 7929 : IsMineResult LegacyWalletIsMineInnerDONOTUSE(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
87 : : {
88 : 7929 : IsMineResult ret = IsMineResult::NO;
89 : :
90 : 7929 : std::vector<valtype> vSolutions;
91 [ + - ]: 7929 : TxoutType whichType = Solver(scriptPubKey, vSolutions);
92 : :
93 [ + + + + : 7929 : CKeyID keyID;
+ + + ]
94 [ + + + + : 7929 : 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 : 640 : case TxoutType::PUBKEY:
102 [ - + + - ]: 640 : keyID = CPubKey(vSolutions[0]).GetID();
103 [ - + - - : 640 : if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
- - ]
104 : : return IsMineResult::INVALID;
105 : : }
106 [ + - + + ]: 640 : if (keystore.HaveKey(keyID)) {
107 [ - + ]: 610 : ret = std::max(ret, IsMineResult::SPENDABLE);
108 : : }
109 : : break;
110 : 1581 : case TxoutType::WITNESS_V0_KEYHASH:
111 : 1581 : {
112 [ + - ]: 1581 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
113 : : // P2WPKH inside P2WSH is invalid.
114 : : return IsMineResult::INVALID;
115 : : }
116 [ + + + - : 2225 : 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 [ - + + - : 1589 : ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
+ - + + ]
123 : 1565 : break;
124 : : }
125 : 2234 : case TxoutType::PUBKEYHASH:
126 [ - + + + ]: 2234 : keyID = CKeyID(uint160(vSolutions[0]));
127 [ + + ]: 2234 : if (!PermitsUncompressed(sigversion)) {
128 [ + - ]: 1583 : CPubKey pubkey;
129 [ + - + - : 1583 : if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
+ + ]
130 : : return IsMineResult::INVALID;
131 : : }
132 : : }
133 [ + - + + ]: 2229 : if (keystore.HaveKey(keyID)) {
134 [ - + ]: 2154 : ret = std::max(ret, IsMineResult::SPENDABLE);
135 : : }
136 : : break;
137 : 2226 : case TxoutType::SCRIPTHASH:
138 : 2226 : {
139 [ + + ]: 2226 : if (sigversion != IsMineSigVersion::TOP) {
140 : : // P2SH inside P2WSH or P2SH is invalid.
141 : : return IsMineResult::INVALID;
142 : : }
143 [ - + + - ]: 2216 : CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
144 : 2216 : CScript subscript;
145 [ + - + + ]: 2216 : if (keystore.GetCScript(scriptID, subscript)) {
146 [ + + + - : 1069 : ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
+ + ]
147 : : }
148 : 2216 : break;
149 : 2216 : }
150 : 1169 : case TxoutType::WITNESS_V0_SCRIPTHASH:
151 : 1169 : {
152 [ + + ]: 1169 : if (sigversion == IsMineSigVersion::WITNESS_V0) {
153 : : // P2WSH inside P2WSH is invalid.
154 : : return IsMineResult::INVALID;
155 : : }
156 [ + + + - : 2296 : if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
- + + - +
- + + +
+ ]
157 : : break;
158 : : }
159 [ - + + - ]: 76 : CScriptID scriptID{RIPEMD160(vSolutions[0])};
160 : 76 : CScript subscript;
161 [ + - + + ]: 76 : if (keystore.GetCScript(scriptID, subscript)) {
162 [ + + + - : 96 : ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
+ + ]
163 : : }
164 : 76 : break;
165 : 76 : }
166 : :
167 : 55 : case TxoutType::MULTISIG:
168 : 55 : {
169 : : // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
170 [ + + ]: 55 : 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 [ - + + - ]: 48 : std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
180 [ + + ]: 48 : if (!PermitsUncompressed(sigversion)) {
181 [ - + + + ]: 112 : for (size_t i = 0; i < keys.size(); i++) {
182 [ - + - + ]: 79 : if (keys[i].size() != 33) {
183 : 0 : return IsMineResult::INVALID;
184 : : }
185 : : }
186 : : }
187 [ + - + + ]: 48 : if (HaveKeys(keys, keystore)) {
188 [ - + ]: 9 : ret = std::max(ret, IsMineResult::SPENDABLE);
189 : : }
190 : 48 : break;
191 : 48 : }
192 : : } // no default case, so the compiler can warn about missing cases
193 : :
194 [ + + + - : 7909 : if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
+ + ]
195 [ - + ]: 158 : ret = std::max(ret, IsMineResult::WATCH_ONLY);
196 : : }
197 : 7909 : return ret;
198 : 7929 : }
199 : :
200 : : } // namespace
201 : :
202 : 4505 : bool LegacyDataSPKM::IsMine(const CScript& script) const
203 : : {
204 [ + - + ]: 4505 : switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
205 : : case IsMineResult::INVALID:
206 : : case IsMineResult::NO:
207 : : return false;
208 : 2931 : case IsMineResult::WATCH_ONLY:
209 : 2931 : case IsMineResult::SPENDABLE:
210 : 2931 : return true;
211 : : }
212 : 0 : assert(false);
213 : : }
214 : :
215 : 3 : bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
216 : : {
217 : 3 : {
218 : 3 : LOCK(cs_KeyStore);
219 [ - + ]: 3 : assert(mapKeys.empty());
220 : :
221 [ + - ]: 3 : bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
222 : 3 : bool keyFail = false;
223 [ + - ]: 3 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
224 [ + - + - ]: 3 : WalletBatch batch(m_storage.GetDatabase());
225 [ + + ]: 63 : for (; mi != mapCryptedKeys.end(); ++mi)
226 : : {
227 [ - + ]: 61 : const CPubKey &vchPubKey = (*mi).second.first;
228 : 61 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
229 : 61 : CKey key;
230 [ - + + - : 61 : if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
+ - ]
231 : : {
232 : : keyFail = true;
233 : : break;
234 : : }
235 : 61 : keyPass = true;
236 [ + + ]: 61 : if (fDecryptionThoroughlyChecked)
237 : : break;
238 : : else {
239 : : // Rewrite these encrypted keys with checksums
240 [ + - + - : 60 : batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
+ - ]
241 : : }
242 : 61 : }
243 [ - + ]: 3 : 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 [ - + ]: 3 : if (keyFail || !keyPass)
249 : 0 : return false;
250 : 3 : fDecryptionThoroughlyChecked = true;
251 [ - - + - ]: 3 : }
252 : 3 : return true;
253 : : }
254 : :
255 : 89 : std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
256 : : {
257 : 89 : return std::make_unique<LegacySigningProvider>(*this);
258 : : }
259 : :
260 : 779 : bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
261 : : {
262 : 779 : IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
263 [ + + ]: 779 : 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 : 751 : ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
271 [ + + ]: 751 : if (!sigdata.signatures.empty()) {
272 : : // If we could make signatures, make sure we have a private key to actually make a signature
273 : 1 : bool has_privkeys = false;
274 [ + + ]: 2 : for (const auto& key_sig_pair : sigdata.signatures) {
275 : 1 : has_privkeys |= HaveKey(key_sig_pair.first);
276 : : }
277 : : return has_privkeys;
278 : : }
279 : : return false;
280 : : }
281 : : }
282 : :
283 : 239 : bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
284 : : {
285 : 239 : return AddKeyPubKeyInner(key, pubkey);
286 : : }
287 : :
288 : 86 : 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 [ + + - + ]: 86 : 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 : 86 : return FillableSigningProvider::AddCScript(redeemScript);
301 : : }
302 : :
303 : 327 : void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
304 : : {
305 : 327 : LOCK(cs_KeyStore);
306 [ + - + - ]: 327 : mapKeyMetadata[keyID] = meta;
307 : 327 : }
308 : :
309 : 49 : void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
310 : : {
311 : 49 : LOCK(cs_KeyStore);
312 [ + - + - ]: 49 : m_script_metadata[script_id] = meta;
313 : 49 : }
314 : :
315 : 239 : bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
316 : : {
317 : 239 : LOCK(cs_KeyStore);
318 [ + - + - ]: 239 : return FillableSigningProvider::AddKeyPubKey(key, pubkey);
319 : 239 : }
320 : :
321 : 84 : 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 [ + + ]: 84 : if (!checksum_valid) {
325 : 60 : fDecryptionThoroughlyChecked = false;
326 : : }
327 : :
328 : 84 : return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
329 : : }
330 : :
331 : 84 : bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
332 : : {
333 : 84 : LOCK(cs_KeyStore);
334 [ - + ]: 84 : assert(mapKeys.empty());
335 : :
336 [ + - + - : 168 : mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
+ - ]
337 [ + - ]: 84 : ImplicitlyLearnRelatedKeyScripts(vchPubKey);
338 [ + - ]: 84 : return true;
339 : 84 : }
340 : :
341 : 2544 : bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
342 : : {
343 : 2544 : LOCK(cs_KeyStore);
344 [ + - ]: 2544 : return setWatchOnly.contains(dest);
345 : 2544 : }
346 : :
347 : 49 : bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
348 : : {
349 : 49 : return AddWatchOnlyInMem(dest);
350 : : }
351 : :
352 : 49 : static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
353 : : {
354 : 49 : std::vector<std::vector<unsigned char>> solutions;
355 [ + - + + : 58 : return Solver(dest, solutions) == TxoutType::PUBKEY &&
- + ]
356 [ - + + - ]: 58 : (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
357 : 49 : }
358 : :
359 : 49 : bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
360 : : {
361 : 49 : LOCK(cs_KeyStore);
362 [ + - ]: 49 : setWatchOnly.insert(dest);
363 [ + - ]: 49 : CPubKey pubKey;
364 [ + - + + ]: 49 : if (ExtractPubKey(dest, pubKey)) {
365 [ + - + - ]: 9 : mapWatchKeys[pubKey.GetID()] = pubKey;
366 [ + - ]: 9 : ImplicitlyLearnRelatedKeyScripts(pubKey);
367 : : }
368 [ + - ]: 49 : return true;
369 : 49 : }
370 : :
371 : 38 : void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
372 : : {
373 : 38 : LOCK(cs_KeyStore);
374 [ + - ]: 38 : m_hd_chain = chain;
375 : 38 : }
376 : :
377 : 7 : void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
378 : : {
379 : 7 : LOCK(cs_KeyStore);
380 [ - + ]: 14 : assert(!chain.seed_id.IsNull());
381 [ + - + - ]: 7 : m_inactive_hd_chains[chain.seed_id] = chain;
382 : 7 : }
383 : :
384 : 2969 : bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
385 : : {
386 : 2969 : LOCK(cs_KeyStore);
387 [ + - + + ]: 2969 : if (!m_storage.HasEncryptionKeys()) {
388 [ + - ]: 2375 : return FillableSigningProvider::HaveKey(address);
389 : : }
390 : 594 : return mapCryptedKeys.contains(address);
391 : 2969 : }
392 : :
393 : 1541 : bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
394 : : {
395 : 1541 : LOCK(cs_KeyStore);
396 [ + - + + ]: 1541 : if (!m_storage.HasEncryptionKeys()) {
397 [ + - ]: 1502 : return FillableSigningProvider::GetKey(address, keyOut);
398 : : }
399 : :
400 : 39 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
401 [ + - ]: 39 : if (mi != mapCryptedKeys.end())
402 : : {
403 [ + - ]: 39 : const CPubKey &vchPubKey = (*mi).second.first;
404 : 39 : const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
405 [ + - + - ]: 39 : return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
406 [ - + ]: 39 : return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
407 : : });
408 : : }
409 : : return false;
410 : 1541 : }
411 : :
412 : 195 : bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
413 : : {
414 : 195 : CKeyMetadata meta;
415 : 195 : {
416 [ + - ]: 195 : LOCK(cs_KeyStore);
417 : 195 : auto it = mapKeyMetadata.find(keyID);
418 [ + + ]: 195 : if (it == mapKeyMetadata.end()) {
419 [ + - ]: 56 : return false;
420 : : }
421 [ + - ]: 139 : meta = it->second;
422 : 56 : }
423 [ + + ]: 139 : if (meta.has_key_origin) {
424 : 42 : info.fingerprint = meta.key_origin.fingerprint;
425 [ + - ]: 42 : info.path = meta.key_origin.path;
426 : : } else { // Single pubkeys get the master fingerprint of themselves
427 : 97 : info.fingerprint = keyID.fingerprint();
428 : : }
429 : : return true;
430 : 195 : }
431 : :
432 : 77 : bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
433 : : {
434 : 77 : LOCK(cs_KeyStore);
435 : 77 : WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
436 [ + + ]: 77 : if (it != mapWatchKeys.end()) {
437 : 64 : pubkey_out = it->second;
438 : 64 : return true;
439 : : }
440 : : return false;
441 : 77 : }
442 : :
443 : 1626 : bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
444 : : {
445 : 1626 : LOCK(cs_KeyStore);
446 [ + - + + ]: 1626 : if (!m_storage.HasEncryptionKeys()) {
447 [ + - + + ]: 1296 : if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
448 [ + - ]: 77 : return GetWatchPubKey(address, vchPubKeyOut);
449 : : }
450 : : return true;
451 : : }
452 : :
453 : 330 : CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
454 [ + - ]: 330 : if (mi != mapCryptedKeys.end())
455 : : {
456 : 330 : vchPubKeyOut = (*mi).second.first;
457 : 330 : return true;
458 : : }
459 : : // Check for watch-only pubkeys
460 [ # # ]: 0 : return GetWatchPubKey(address, vchPubKeyOut);
461 : 1626 : }
462 : :
463 : 92 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
464 : : {
465 : 92 : LOCK(cs_KeyStore);
466 [ + - ]: 92 : 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 : 702 : const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
470 [ + - ]: 610 : candidate_spks.insert(GetScriptForRawPubKey(pub));
471 [ + - ]: 1220 : candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
472 : :
473 [ + - ]: 610 : CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
474 [ + - ]: 610 : candidate_spks.insert(wpkh);
475 [ + - + - ]: 1220 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
476 : 610 : };
477 [ + - + + ]: 570 : for (const auto& [_, key] : mapKeys) {
478 [ + - + - ]: 478 : add_pubkey(key.GetPubKey());
479 : : }
480 [ + - + + ]: 224 : for (const auto& [_, ckeypair] : mapCryptedKeys) {
481 [ + - ]: 132 : 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 : 878 : const auto& add_script = [&candidate_spks](const CScript& script) -> void {
489 : 786 : candidate_spks.insert(script);
490 [ + - ]: 1572 : candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
491 : :
492 [ + - ]: 786 : CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
493 [ + - ]: 786 : candidate_spks.insert(wsh);
494 [ + - + - ]: 1572 : candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
495 : 786 : };
496 [ + - + + ]: 780 : for (const auto& [_, script] : mapScripts) {
497 [ + - ]: 688 : 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 [ + + ]: 190 : for (const auto& script : setWatchOnly) {
503 [ + - ]: 98 : add_script(script);
504 : : }
505 : :
506 [ + - ]: 92 : return candidate_spks;
507 : 92 : }
508 : :
509 : 46 : 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 : 46 : std::unordered_set<CScript, SaltedSipHasher> spks;
515 [ + - + + : 2116 : for (const CScript& script : GetCandidateScriptPubKeys()) {
+ - ]
516 [ + + + - ]: 2070 : if (IsMine(script)) {
517 [ + - ]: 1279 : spks.insert(script);
518 : : }
519 : : }
520 : :
521 : 46 : return spks;
522 : 0 : }
523 : :
524 : 42 : std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
525 : : {
526 : 42 : LOCK(cs_KeyStore);
527 [ + - ]: 42 : std::unordered_set<CScript, SaltedSipHasher> spks;
528 [ + + ]: 87 : for (const CScript& script : setWatchOnly) {
529 [ + - + + : 45 : if (!IsMine(script)) spks.insert(script);
+ - ]
530 : : }
531 [ + - ]: 42 : return spks;
532 : 42 : }
533 : :
534 : 46 : std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
535 : : {
536 : 46 : LOCK(cs_KeyStore);
537 [ + - - + ]: 46 : if (m_storage.IsLocked()) {
538 : 0 : return std::nullopt;
539 : : }
540 : :
541 : 46 : MigrationData out;
542 : :
543 [ + - ]: 46 : std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
544 : :
545 : : // Get all key ids
546 : 46 : std::set<CKeyID> keyids;
547 [ + + ]: 285 : for (const auto& key_pair : mapKeys) {
548 [ + - ]: 239 : keyids.insert(key_pair.first);
549 : : }
550 [ + + ]: 112 : for (const auto& key_pair : mapCryptedKeys) {
551 [ + - ]: 66 : 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 [ + + ]: 351 : for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
557 : 305 : const CKeyID& keyid = *keyid_it;
558 : 305 : const auto& it = mapKeyMetadata.find(keyid);
559 [ + - ]: 305 : if (it != mapKeyMetadata.end()) {
560 [ + + ]: 305 : const CKeyMetadata& meta = it->second;
561 [ + + + + ]: 305 : if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
562 : 40 : keyid_it++;
563 : 40 : continue;
564 : : }
565 [ + + + + : 530 : 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 : 213 : keyid_it = keyids.erase(keyid_it);
567 : 213 : continue;
568 : : }
569 : : }
570 : 52 : keyid_it++;
571 : : }
572 : :
573 [ + - + - ]: 46 : WalletBatch batch(m_storage.GetDatabase());
574 [ + - - + ]: 46 : 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 [ + + ]: 138 : for (const CKeyID& keyid : keyids) {
581 : 92 : CKey key;
582 [ + - - + ]: 92 : if (!GetKey(keyid, key)) {
583 : 0 : assert(false);
584 : : }
585 : :
586 : : // Get birthdate from key meta
587 : 92 : uint64_t creation_time = 0;
588 : 92 : const auto& it = mapKeyMetadata.find(keyid);
589 [ + - ]: 92 : if (it != mapKeyMetadata.end()) {
590 : 92 : 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 [ + - ]: 92 : KeyOriginInfo info;
596 [ + - ]: 92 : bool has_info = GetKeyOrigin(keyid, info);
597 [ + - + - : 460 : std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
+ - + - +
- + - - -
+ - + - +
- - - - -
- - - - ]
598 : :
599 : : // Construct the combo descriptor
600 [ + - + - : 184 : std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
+ - + - ]
601 : 92 : FlatSigningProvider provider;
602 [ - + ]: 92 : std::string error;
603 [ - + + - ]: 92 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
604 [ - + + - ]: 92 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
605 [ + - + - : 92 : WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
+ - ]
606 : :
607 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
608 [ + - + - : 92 : provider.keys.emplace(key.GetPubKey().GetID(), key);
+ - ]
609 [ + - ]: 92 : auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
610 [ + - ]: 92 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
611 : :
612 : : // Remove the scriptPubKeys from our current set
613 [ + + + - ]: 458 : for (const CScript& spk : desc_spks) {
614 [ + - ]: 366 : size_t erased = spks.erase(spk);
615 [ - + ]: 366 : assert(erased == 1);
616 [ + - - + ]: 366 : assert(IsMine(spk));
617 : : }
618 : :
619 [ + - ]: 92 : out.desc_spkms.push_back(std::move(desc_spk_man));
620 : 92 : }
621 : :
622 : : // Handle HD keys by using the CHDChains
623 [ + - ]: 46 : std::set<CHDChain> chains;
624 [ + - ]: 46 : chains.insert(m_hd_chain);
625 [ + + + - ]: 50 : for (const auto& chain_pair : m_inactive_hd_chains) {
626 [ + - ]: 4 : chains.insert(chain_pair.second);
627 : : }
628 : :
629 : 46 : bool can_support_hd_split_feature = m_hd_chain.nVersion >= CHDChain::VERSION_HD_CHAIN_SPLIT;
630 : :
631 : 46 : std::set<CExtPubKey> master_xpubs;
632 [ + + ]: 96 : for (const CHDChain& chain : chains) {
633 [ + + ]: 100 : if (chain.seed_id.IsNull()) continue;
634 : :
635 : : // Get the master xprv
636 : 39 : CKey seed_key;
637 [ + - - + ]: 39 : if (!GetKey(chain.seed_id, seed_key)) {
638 : 0 : assert(false);
639 : : }
640 [ + - ]: 39 : CExtKey master_key;
641 [ + - + - ]: 78 : master_key.SetSeed(seed_key);
642 : :
643 : : // Get the xpub and verify that we haven't already seen this xpub before
644 [ + - ]: 39 : CExtPubKey master_xpub = master_key.Neuter();
645 [ + - - + ]: 39 : const auto& [_, inserted] = master_xpubs.insert(master_xpub);
646 [ - + ]: 39 : if (!inserted) continue;
647 : :
648 [ + + ]: 117 : for (int i = 0; i < 2; ++i) {
649 : : // Skip if doing internal chain and split chain is not supported
650 [ + + + + ]: 78 : if (i == 1 && !can_support_hd_split_feature) {
651 : 3 : continue;
652 : : }
653 : :
654 : : // Make the combo descriptor
655 [ + - + - ]: 75 : std::string xpub = EncodeExtPubKey(master_key.Neuter());
656 [ + - + - : 225 : std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
+ - ]
657 : 75 : FlatSigningProvider provider;
658 [ - + ]: 75 : std::string error;
659 [ - + + - ]: 75 : std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
660 [ - + + - ]: 75 : CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
661 [ + + ]: 75 : uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
662 [ + - + - : 75 : WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
+ - ]
663 : :
664 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
665 [ + - + - : 75 : provider.keys.emplace(master_key.key.GetPubKey().GetID(), master_key.key);
+ - ]
666 [ + - ]: 75 : auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
667 [ + - ]: 75 : auto desc_spks = desc_spk_man->GetScriptPubKeys();
668 : :
669 : : // Remove the scriptPubKeys from our current set
670 [ + + + - ]: 927 : for (const CScript& spk : desc_spks) {
671 [ + - ]: 852 : size_t erased = spks.erase(spk);
672 [ - + ]: 852 : assert(erased == 1);
673 [ + - - + ]: 852 : assert(IsMine(spk));
674 : : }
675 : :
676 [ + - ]: 75 : out.desc_spkms.push_back(std::move(desc_spk_man));
677 : 75 : }
678 : 39 : }
679 : : // Add the current master seed to the migration data
680 [ + + ]: 92 : if (!m_hd_chain.seed_id.IsNull()) {
681 : 35 : CKey seed_key;
682 [ + - - + ]: 35 : if (!GetKey(m_hd_chain.seed_id, seed_key)) {
683 : 0 : assert(false);
684 : : }
685 [ + - + - ]: 70 : out.master_key.SetSeed(seed_key);
686 : 35 : }
687 : :
688 : : // Handle the rest of the scriptPubKeys which must be imports and may not have all info
689 [ + + ]: 107 : for (auto it = spks.begin(); it != spks.end();) {
690 [ + - ]: 61 : const CScript& spk = *it;
691 : :
692 : : // Get birthdate from script meta
693 : 61 : uint64_t creation_time = 0;
694 [ + - ]: 61 : const auto& mit = m_script_metadata.find(CScriptID(spk));
695 [ + + ]: 61 : if (mit != m_script_metadata.end()) {
696 : 44 : creation_time = mit->second.nCreateTime;
697 : : }
698 : :
699 : : // InferDescriptor as that will get us all the solving info if it is there
700 [ + - + - ]: 122 : 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 : 61 : {
705 [ + - ]: 61 : std::string desc_str = desc->ToString();
706 : 61 : FlatSigningProvider parsed_keys;
707 [ - + ]: 61 : std::string parse_error;
708 [ - + + - ]: 61 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
709 [ - + ]: 61 : if (parsed_descs.empty()) {
710 : : // Remove this scriptPubKey from the set
711 : 0 : it = spks.erase(it);
712 : 0 : continue;
713 : : }
714 : 61 : }
715 : :
716 : : // Get the private keys for this descriptor
717 : 61 : std::vector<CScript> scripts;
718 : 61 : FlatSigningProvider keys;
719 [ + - - + ]: 61 : if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
720 : 0 : assert(false);
721 : : }
722 : 61 : std::set<CKeyID> privkeyids;
723 [ + + ]: 113 : for (const auto& key_orig_pair : keys.origins) {
724 [ + - ]: 52 : privkeyids.insert(key_orig_pair.first);
725 : : }
726 : :
727 : 61 : 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 [ + - + + : 61 : if (!desc->HavePrivateKeys(*this) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
+ - + + ]
732 [ + - + - ]: 40 : out.watch_descs.emplace_back(desc->ToString(), creation_time);
733 : :
734 : : // Get the scriptPubKeys without writing this to the wallet
735 : 40 : FlatSigningProvider provider;
736 [ + - ]: 40 : desc->Expand(0, provider, desc_spks, provider);
737 : 40 : } else {
738 : : // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
739 [ + + ]: 48 : for (const auto& keyid : privkeyids) {
740 : 27 : CKey key;
741 [ + - + + ]: 27 : if (!GetKey(keyid, key)) {
742 : 10 : continue;
743 : : }
744 [ + - + - : 17 : keys.keys.emplace(key.GetPubKey().GetID(), key);
+ - ]
745 : 27 : }
746 [ + - + - ]: 21 : WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
747 [ + - ]: 21 : auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, keys);
748 [ + - ]: 21 : auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
749 [ + - ]: 21 : desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
750 : :
751 [ + - ]: 21 : out.desc_spkms.push_back(std::move(desc_spk_man));
752 : 21 : }
753 : :
754 : : // Remove the scriptPubKeys from our current set
755 [ + + ]: 122 : for (const CScript& desc_spk : desc_spks) {
756 [ + - ]: 61 : auto del_it = spks.find(desc_spk);
757 [ + - ]: 61 : assert(del_it != spks.end());
758 [ + - - + ]: 61 : assert(IsMine(desc_spk));
759 : 61 : it = spks.erase(del_it);
760 : : }
761 : 61 : }
762 : :
763 : : // Make sure that we have accounted for all scriptPubKeys
764 [ - + ]: 46 : if (!Assume(spks.empty())) {
765 [ # # # # ]: 0 : LogError("%s", STR_INTERNAL_BUG("Error: Some output scripts were not migrated."));
766 : 0 : 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 [ + - + + : 2116 : 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 [ + + + - : 2070 : if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
+ + + - ]
777 : 959 : continue;
778 : : }
779 [ + - + + ]: 1111 : if (IsMine(script)) {
780 : 332 : continue;
781 : : }
782 : 779 : SignatureData dummy_sigdata;
783 [ + - + + ]: 779 : if (!CanProvide(script, dummy_sigdata)) {
784 : 751 : continue;
785 : : }
786 : :
787 : : // Get birthdate from script meta
788 : 28 : uint64_t creation_time = 0;
789 [ + - ]: 28 : const auto& it = m_script_metadata.find(CScriptID(script));
790 [ + + ]: 28 : if (it != m_script_metadata.end()) {
791 : 4 : creation_time = it->second.nCreateTime;
792 : : }
793 : :
794 : : // InferDescriptor as that will get us all the solving info if it is there
795 [ + - + - ]: 28 : std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
796 [ + - + + ]: 28 : 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 : 10 : 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 : 18 : {
805 [ + - ]: 18 : std::string desc_str = desc->ToString();
806 : 18 : FlatSigningProvider parsed_keys;
807 [ - + ]: 18 : std::string parse_error;
808 [ - + + - ]: 18 : std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
809 [ - + ]: 18 : if (parsed_descs.empty()) {
810 : 0 : continue;
811 : : }
812 : 18 : }
813 : :
814 [ + - + - ]: 18 : out.solvable_descs.emplace_back(desc->ToString(), creation_time);
815 : 779 : }
816 : :
817 : : // Finalize transaction
818 [ + - - + ]: 46 : if (!batch.TxnCommit()) {
819 [ # # ]: 0 : LogWarning("Error generating descriptors for migration, cannot commit db transaction");
820 : 0 : return std::nullopt;
821 : : }
822 : :
823 : 46 : return out;
824 : 138 : }
825 : :
826 : 42 : bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
827 : : {
828 : 42 : LOCK(cs_KeyStore);
829 [ + - + - ]: 42 : return batch.EraseRecords(DBKeys::LEGACY_TYPES);
830 : 42 : }
831 : :
832 : 960 : std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromImport(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
833 : : {
834 [ + - + - ]: 960 : auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835 [ + - ]: 960 : LOCK(spkm->cs_desc_man);
836 [ + - + - ]: 960 : WalletBatch batch(storage.GetDatabase());
837 [ + + ]: 960 : spkm->UpdateWithSigningProvider(batch, provider);
838 : 959 : return spkm;
839 [ + - ]: 1920 : }
840 : :
841 : 188 : std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromMigration(WalletStorage& storage, WalletBatch& batch, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
842 : : {
843 [ + - + - ]: 188 : auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
844 [ + - ]: 188 : LOCK(spkm->cs_desc_man);
845 [ + - ]: 188 : spkm->UpdateWithSigningProvider(batch, provider);
846 [ + - ]: 188 : return spkm;
847 : 188 : }
848 : :
849 : 3043 : DescriptorScriptPubKeyMan::DescriptorScriptPubKeyMan(WalletStorage& storage, const uint256& id, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
850 : : : ScriptPubKeyMan(storage),
851 [ + - ]: 3043 : m_map_keys(keys),
852 [ + - ]: 3043 : m_map_crypted_keys(ckeys),
853 : 3043 : m_keypool_size(keypool_size),
854 [ + - ]: 3043 : m_id(id),
855 [ + - + - : 6086 : m_wallet_descriptor(descriptor)
+ + ]
856 : : {
857 [ + + + + ]: 3043 : if (!keys.empty() && !ckeys.empty()) {
858 [ + - ]: 1 : throw std::runtime_error("Wallet contains both unencrypted and encrypted keys");
859 : : }
860 [ + - ]: 3042 : Load();
861 : 3044 : }
862 : :
863 : 3035 : 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 [ + + ]: 3035 : return std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, id, descriptor, keypool_size, keys, ckeys));
866 : : }
867 : :
868 : 4140 : 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 [ + - ]: 4140 : WalletDescriptor desc = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
871 : :
872 [ + - + - : 4140 : auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, desc, keypool_size));
+ - ]
873 : :
874 [ + - ]: 4140 : LOCK(spkm->cs_desc_man);
875 [ + - - + ]: 4140 : Assert(spkm->m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
876 : :
877 : : // Store the master private key, and descriptor
878 [ + - + - : 4140 : 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 [ + - + - : 4140 : 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 [ + - + + ]: 4140 : if (spkm->m_storage.HasEncryptionKeys()) {
887 : 202 : spkm->m_decryption_thoroughly_checked = true;
888 : : }
889 : :
890 : : // TopUp
891 [ + - ]: 4140 : spkm->TopUpWithDB(batch);
892 : :
893 [ + - ]: 4140 : spkm->m_storage.UnsetBlankWalletFlag(batch);
894 [ + - ]: 8280 : return spkm;
895 : 4140 : }
896 : :
897 : 43884 : void DescriptorScriptPubKeyMan::IncIndex()
898 : : {
899 : 43884 : AssertLockHeld(cs_desc_man);
900 : :
901 : 43884 : const auto old_can = CanGetAddresses();
902 : 43884 : m_wallet_descriptor.IncNext();
903 : 43884 : const auto new_can = CanGetAddresses();
904 [ + + ]: 43884 : if (old_can != new_can) {
905 : 1 : NotifyCanGetAddressesChanged();
906 : : }
907 : 43884 : }
908 : :
909 : 105 : void DescriptorScriptPubKeyMan::DecIndex()
910 : : {
911 : 105 : AssertLockHeld(cs_desc_man);
912 : :
913 : 105 : const auto old_can = CanGetAddresses();
914 : 105 : m_wallet_descriptor.DecNext();
915 : 105 : const auto new_can = CanGetAddresses();
916 [ - + ]: 105 : if (old_can != new_can) {
917 : 0 : NotifyCanGetAddressesChanged();
918 : : }
919 : 105 : }
920 : :
921 : 77508 : void DescriptorScriptPubKeyMan::SetRangeEnd(int32_t end)
922 : : {
923 : 77508 : AssertLockHeld(cs_desc_man);
924 : :
925 : 77508 : const auto old_can = CanGetAddresses();
926 : 77508 : m_wallet_descriptor.SetEnd(end);
927 : 77508 : const auto new_can = CanGetAddresses();
928 [ - + ]: 77508 : if (old_can != new_can) {
929 : 0 : NotifyCanGetAddressesChanged();
930 : : }
931 : 77508 : }
932 : :
933 : 19459 : 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 [ + + ]: 19459 : if (!CanGetAddresses()) {
937 : 2 : return util::Error{_("No addresses available")};
938 : : }
939 : 19458 : {
940 : 19458 : LOCK(cs_desc_man);
941 [ + - - + ]: 19458 : assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
942 [ + - ]: 19458 : std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
943 [ - + ]: 19458 : assert(desc_addr_type);
944 [ - + ]: 19458 : 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 [ + - ]: 19458 : TopUp();
949 : :
950 : : // Get the scriptPubKey from the descriptor
951 : 19458 : FlatSigningProvider out_keys;
952 : 19458 : std::vector<CScript> scripts_temp;
953 [ - + - - : 19458 : 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 [ + - + + ]: 19458 : 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 [ + - ]: 24 : return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
960 : : }
961 : :
962 : 19450 : CTxDestination dest;
963 [ + - - + ]: 19450 : if (!ExtractDestination(scripts_temp[0], dest)) {
964 [ # # ]: 0 : return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
965 : : }
966 [ + - ]: 19450 : IncIndex();
967 [ + - + - : 19450 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - ]
968 : 19450 : return dest;
969 [ + - ]: 38916 : }
970 : : }
971 : :
972 : 514031 : bool DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
973 : : {
974 : 514031 : LOCK(cs_desc_man);
975 [ + - ]: 514031 : return m_map_script_pub_keys.contains(script);
976 : 514031 : }
977 : :
978 : 890 : bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
979 : : {
980 : 890 : LOCK(cs_desc_man);
981 [ + - ]: 890 : if (!m_map_keys.empty()) {
982 : : return false;
983 : : }
984 : :
985 : 890 : bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
986 : 890 : bool keyFail = false;
987 [ + + ]: 1191 : for (const auto& mi : m_map_crypted_keys) {
988 : 884 : const CPubKey &pubkey = mi.second.first;
989 : 884 : const std::vector<unsigned char> &crypted_secret = mi.second.second;
990 : 884 : CKey key;
991 [ - + + - : 884 : if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
+ - ]
992 : : keyFail = true;
993 : : break;
994 : : }
995 : 884 : keyPass = true;
996 [ + + ]: 884 : if (m_decryption_thoroughly_checked)
997 : : break;
998 : 884 : }
999 [ - + ]: 890 : 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 [ + - ]: 890 : if (keyFail || !keyPass) {
1004 : : return false;
1005 : : }
1006 : 890 : m_decryption_thoroughly_checked = true;
1007 : 890 : return true;
1008 : 890 : }
1009 : :
1010 : 155 : bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
1011 : : {
1012 : 155 : LOCK(cs_desc_man);
1013 [ + - ]: 155 : if (!m_map_crypted_keys.empty()) {
1014 : : return false;
1015 : : }
1016 : :
1017 : 155 : CryptedKeyMap crypted_keys;
1018 [ + + ]: 305 : for (const KeyMap::value_type& key_in : m_map_keys)
1019 : : {
1020 : 152 : const CKey &key = key_in.second;
1021 [ + - ]: 152 : CPubKey pubkey = key.GetPubKey();
1022 [ + - + - : 456 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
1023 : 152 : std::vector<unsigned char> crypted_secret;
1024 [ + - + - : 152 : if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
+ - ]
1025 : : return false;
1026 : : }
1027 [ + - + - : 152 : if (!batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret)) {
+ + ]
1028 : : return false;
1029 : : }
1030 [ + - + - ]: 150 : crypted_keys[pubkey.GetID()] = make_pair(pubkey, std::move(crypted_secret));
1031 : 152 : }
1032 : :
1033 [ + - ]: 153 : batch->RegisterTxnListener({
1034 [ - - ]: 612 : .on_commit = [this, keys = std::move(crypted_keys)]() mutable {
1035 : 143 : LOCK(cs_desc_man);
1036 : 143 : m_map_crypted_keys = std::move(keys);
1037 [ + - ]: 143 : m_map_keys.clear();
1038 : 143 : },
1039 : : .on_abort = [] {}});
1040 : 153 : return true;
1041 [ + - + - ]: 463 : }
1042 : :
1043 : 2225 : util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
1044 : : {
1045 : 2225 : LOCK(cs_desc_man);
1046 [ + - ]: 2225 : auto op_dest = GetNewDestination(type);
1047 [ + - ]: 2225 : index = m_wallet_descriptor.GetNext() - 1;
1048 [ + - ]: 2225 : return op_dest;
1049 : 2225 : }
1050 : :
1051 : 105 : void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
1052 : : {
1053 : 105 : LOCK(cs_desc_man);
1054 : : // Only return when the index was the most recent
1055 [ + - ]: 105 : if (m_wallet_descriptor.GetNext() - 1 == index) {
1056 [ + - ]: 105 : DecIndex();
1057 : : }
1058 [ + - + - : 210 : WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
+ - + - +
- ]
1059 : 105 : }
1060 : :
1061 : 94500 : std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
1062 : : {
1063 : 94500 : AssertLockHeld(cs_desc_man);
1064 [ + + + + ]: 94500 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
1065 : 2479 : KeyMap keys;
1066 [ + + ]: 4958 : for (const auto& key_pair : m_map_crypted_keys) {
1067 : 2479 : const CPubKey& pubkey = key_pair.second.first;
1068 : 2479 : const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1069 : 2479 : CKey key;
1070 [ + - + - ]: 2479 : m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1071 [ - + ]: 2479 : return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1072 : : });
1073 [ + - + - : 2479 : keys[pubkey.GetID()] = key;
+ - ]
1074 : 2479 : }
1075 : : return keys;
1076 : 0 : }
1077 : 92021 : return m_map_keys;
1078 : : }
1079 : :
1080 : 280 : bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
1081 : : {
1082 : 280 : AssertLockHeld(cs_desc_man);
1083 [ + + + + ]: 280 : return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
1084 : : }
1085 : :
1086 : 131 : std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
1087 : : {
1088 : 131 : AssertLockHeld(cs_desc_man);
1089 [ + + + - ]: 131 : if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
1090 : 20 : const auto& it = m_map_crypted_keys.find(keyid);
1091 [ + + ]: 20 : if (it == m_map_crypted_keys.end()) {
1092 : 6 : return std::nullopt;
1093 : : }
1094 [ + - ]: 14 : const std::vector<unsigned char>& crypted_secret = it->second.second;
1095 : 14 : CKey key;
1096 [ + - + - : 28 : if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
- + - + ]
1097 : : return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1098 : : }))) {
1099 : 0 : return std::nullopt;
1100 : : }
1101 : 14 : return key;
1102 : 14 : }
1103 : 111 : const auto& it = m_map_keys.find(keyid);
1104 [ + + ]: 111 : if (it == m_map_keys.end()) {
1105 : 5 : return std::nullopt;
1106 : : }
1107 : 106 : return it->second;
1108 : : }
1109 : :
1110 : 72288 : bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1111 : : {
1112 : 72288 : WalletBatch batch(m_storage.GetDatabase());
1113 [ + - + - ]: 72288 : if (!batch.TxnBegin()) return false;
1114 [ + - ]: 72288 : bool res = TopUpWithDB(batch, size);
1115 [ + - - + : 72288 : if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
- - - - -
- ]
1116 : : return res;
1117 : 72288 : }
1118 : :
1119 : 77616 : bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1120 : : {
1121 : 77616 : LOCK(cs_desc_man);
1122 [ + + ]: 77616 : std::set<CScript> new_spks;
1123 : 77616 : unsigned int target_size;
1124 [ + + ]: 77616 : if (size > 0) {
1125 : : target_size = size;
1126 : : } else {
1127 : 77544 : target_size = m_keypool_size;
1128 : : }
1129 : :
1130 : : // Calculate the new range_end
1131 [ + + ]: 77616 : int32_t new_range_end = std::max(m_wallet_descriptor.GetNext() + (int32_t)target_size, m_wallet_descriptor.GetEnd());
1132 : :
1133 : : // If the descriptor is not ranged, we actually just want to fill the first cache item
1134 [ + - + + ]: 77616 : if (!m_wallet_descriptor.descriptor->IsRange()) {
1135 : 13707 : new_range_end = 1;
1136 : : }
1137 : :
1138 : 77616 : FlatSigningProvider provider;
1139 [ + - ]: 155232 : provider.keys = GetKeys();
1140 : :
1141 [ + - ]: 77616 : uint256 id = GetID();
1142 [ + + ]: 555675 : for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1143 : 478167 : FlatSigningProvider out_keys;
1144 : 478167 : std::vector<CScript> scripts_temp;
1145 : 478167 : DescriptorCache temp_cache;
1146 : : // Maybe we have a cached xpub and we can expand from the cache first
1147 [ + - + + ]: 478167 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1148 [ + - + + ]: 28933 : if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1149 : : }
1150 : : // Add all of the scriptPubKeys to the scriptPubKey set
1151 [ + - ]: 478059 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1152 [ + + ]: 957662 : for (const CScript& script : scripts_temp) {
1153 [ + - ]: 479603 : m_map_script_pub_keys[script] = i;
1154 : : }
1155 [ + + ]: 1004599 : for (const auto& pk_pair : out_keys.pubkeys) {
1156 : 526540 : const CPubKey& pubkey = pk_pair.second;
1157 [ + + ]: 526540 : if (m_map_pubkeys.contains(pubkey)) {
1158 : : // We don't need to give an error here.
1159 : : // 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
1160 : 10712 : continue;
1161 : : }
1162 [ + - ]: 515828 : m_map_pubkeys[pubkey] = i;
1163 : : }
1164 : : // Merge and write the cache
1165 [ + - ]: 478059 : DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1166 [ + - - + ]: 478059 : if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1167 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1168 : : }
1169 : 478059 : m_max_cached_index++;
1170 : 478167 : }
1171 [ + - ]: 77508 : SetRangeEnd(new_range_end);
1172 [ + - + - ]: 77508 : batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1173 : :
1174 : : // By this point, the cache size should be the size of the entire range
1175 [ - + ]: 77508 : assert(m_wallet_descriptor.GetEnd() - 1 == m_max_cached_index);
1176 : :
1177 [ + - ]: 77508 : m_storage.TopUpCallback(new_spks, this);
1178 : : return true;
1179 [ + - ]: 155232 : }
1180 : :
1181 : 46423 : std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1182 : : {
1183 : 46423 : LOCK(cs_desc_man);
1184 : 46423 : std::vector<WalletDestination> result;
1185 [ + - + - ]: 46423 : if (IsMine(script)) {
1186 [ + - ]: 46423 : int32_t index = m_map_script_pub_keys[script];
1187 [ + + ]: 46423 : if (index >= m_wallet_descriptor.GetNext()) {
1188 [ + - ]: 506 : WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1189 [ + - ]: 506 : auto out_keys = std::make_unique<FlatSigningProvider>();
1190 : 506 : std::vector<CScript> scripts_temp;
1191 [ + + ]: 24940 : while (index >= m_wallet_descriptor.GetNext()) {
1192 [ + - - + ]: 24434 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1193 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1194 : : }
1195 : 24434 : CTxDestination dest;
1196 [ + - ]: 24434 : ExtractDestination(scripts_temp[0], dest);
1197 : 24434 : result.push_back({dest, std::nullopt});
1198 [ + - ]: 24434 : IncIndex();
1199 : 24434 : }
1200 [ + - ]: 1012 : }
1201 [ + - - + ]: 46423 : if (!TopUp()) {
1202 [ # # ]: 0 : WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1203 : : }
1204 : : }
1205 : :
1206 [ + - ]: 46423 : return result;
1207 [ + - + - ]: 95291 : }
1208 : :
1209 : 5045 : bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
1210 : : {
1211 : 5045 : AssertLockHeld(cs_desc_man);
1212 [ - + ]: 5045 : assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1213 : :
1214 : : // Check if provided key already exists
1215 [ + + - + ]: 10080 : if (m_map_keys.contains(pubkey.GetID()) ||
1216 : 5035 : m_map_crypted_keys.contains(pubkey.GetID())) {
1217 : 10 : return true;
1218 : : }
1219 : :
1220 [ + + ]: 5035 : if (m_storage.HasEncryptionKeys()) {
1221 [ + - ]: 267 : if (m_storage.IsLocked()) {
1222 : : return false;
1223 : : }
1224 : :
1225 : 267 : std::vector<unsigned char> crypted_secret;
1226 [ + - + - : 801 : CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
+ - ]
1227 [ + - + - : 267 : if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
+ - ]
1228 : 267 : return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1229 : : })) {
1230 : : return false;
1231 : : }
1232 : :
1233 [ + - + - : 267 : if (!batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret)) {
+ + ]
1234 : : return false;
1235 : : }
1236 [ + - + - ]: 264 : m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, std::move(crypted_secret));
1237 : 267 : } else {
1238 [ + - + - : 4768 : if (!batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey())) {
+ + ]
1239 : : return false;
1240 : : }
1241 : 4767 : m_map_keys[pubkey.GetID()] = key;
1242 : : }
1243 : : return true;
1244 : : }
1245 : :
1246 : 80 : bool DescriptorScriptPubKeyMan::IsHDEnabled() const
1247 : : {
1248 : 80 : LOCK(cs_desc_man);
1249 [ + - + - ]: 80 : return m_wallet_descriptor.descriptor->IsRange();
1250 : 80 : }
1251 : :
1252 : 273921 : bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
1253 : : {
1254 : : // We can only give out addresses from descriptors that are single type (not combo), ranged,
1255 : : // and either have cached keys or can generate more keys (ignoring encryption)
1256 : 273921 : LOCK(cs_desc_man);
1257 [ + - + + ]: 521036 : return m_wallet_descriptor.descriptor->IsSingleType() &&
1258 [ + + + - : 519820 : m_wallet_descriptor.descriptor->IsRange() &&
+ + ]
1259 [ + - + + : 520097 : (HavePrivateKeys() || m_wallet_descriptor.GetNext() < m_wallet_descriptor.GetEnd() || m_wallet_descriptor.descriptor->CanSelfExpand());
+ - + + +
- ]
1260 : 273921 : }
1261 : :
1262 : 473804 : bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1263 : : {
1264 : 473804 : LOCK(cs_desc_man);
1265 [ + + + + : 518333 : return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
+ - ]
1266 : 473804 : }
1267 : :
1268 : 41 : bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
1269 : : {
1270 : 41 : LOCK(cs_desc_man);
1271 [ + - ]: 41 : return !m_map_crypted_keys.empty();
1272 : 41 : }
1273 : :
1274 : 10080 : unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
1275 : : {
1276 : 10080 : LOCK(cs_desc_man);
1277 [ + - ]: 10080 : return m_wallet_descriptor.GetEnd() - m_wallet_descriptor.GetNext();
1278 : 10080 : }
1279 : :
1280 : 8342 : int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1281 : : {
1282 : 8342 : LOCK(cs_desc_man);
1283 [ + - ]: 8342 : return m_wallet_descriptor.creation_time;
1284 : 8342 : }
1285 : :
1286 : 359433 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1287 : : {
1288 : 359433 : LOCK(cs_desc_man);
1289 : :
1290 : : // Find the index of the script
1291 : 359433 : auto it = m_map_script_pub_keys.find(script);
1292 [ + + ]: 359433 : if (it == m_map_script_pub_keys.end()) {
1293 : 132992 : return nullptr;
1294 : : }
1295 [ + - ]: 226441 : int32_t index = it->second;
1296 : :
1297 [ + - ]: 226441 : return GetSigningProvider(index, include_private);
1298 : 359433 : }
1299 : :
1300 : 51800 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1301 : : {
1302 : 51800 : LOCK(cs_desc_man);
1303 : :
1304 : : // Find index of the pubkey
1305 : 51800 : auto it = m_map_pubkeys.find(pubkey);
1306 [ + + ]: 51800 : if (it == m_map_pubkeys.end()) {
1307 : 50406 : return nullptr;
1308 : : }
1309 [ + - ]: 1394 : int32_t index = it->second;
1310 : :
1311 : : // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1312 [ + - ]: 1394 : std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1313 [ + - + - : 1394 : if (!out->HaveKey(pubkey.GetID())) {
+ + ]
1314 : 880 : return nullptr;
1315 : : }
1316 : 514 : return out;
1317 : 53194 : }
1318 : :
1319 : 227835 : std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1320 : : {
1321 : 227835 : AssertLockHeld(cs_desc_man);
1322 : :
1323 : 227835 : std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1324 : :
1325 : : // Fetch SigningProvider from cache to avoid re-deriving
1326 : 227835 : auto it = m_map_signing_providers.find(index);
1327 [ + + ]: 227835 : if (it != m_map_signing_providers.end()) {
1328 [ + - + - ]: 211405 : out_keys->Merge(FlatSigningProvider{it->second});
1329 : : } else {
1330 : : // Get the scripts, keys, and key origins for this script
1331 : 16430 : std::vector<CScript> scripts_temp;
1332 [ + - - + ]: 16430 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1333 : :
1334 : : // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1335 [ + - + - ]: 16430 : m_map_signing_providers[index] = *out_keys;
1336 : 16430 : }
1337 : :
1338 [ + - + + : 227835 : if (HavePrivateKeys() && include_private) {
+ + ]
1339 : 14158 : FlatSigningProvider master_provider;
1340 [ + - ]: 28316 : master_provider.keys = GetKeys();
1341 [ + - ]: 14158 : m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1342 : :
1343 : : // Always include musig_secnonces as this descriptor may have a participant private key
1344 : : // but not a musig() descriptor
1345 : 14158 : out_keys->musig2_secnonces = &m_musig2_secnonces;
1346 : 14158 : }
1347 : :
1348 : 227835 : return out_keys;
1349 : 227835 : }
1350 : :
1351 : 289037 : std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1352 : : {
1353 [ - + ]: 289037 : return GetSigningProvider(script, false);
1354 : : }
1355 : :
1356 : 267309 : bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
1357 : : {
1358 : 267309 : return IsMine(script);
1359 : : }
1360 : :
1361 : 17766 : bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1362 : : {
1363 : 17766 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1364 [ + + ]: 62685 : for (const auto& coin_pair : coins) {
1365 [ + - ]: 44919 : std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1366 [ + + ]: 44919 : if (!coin_keys) {
1367 : 33997 : continue;
1368 : : }
1369 [ + - ]: 10922 : keys->Merge(std::move(*coin_keys));
1370 : 44919 : }
1371 : :
1372 [ + - + - ]: 17766 : return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1373 : 17766 : }
1374 : :
1375 : 9 : SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1376 : : {
1377 [ + - + - ]: 18 : std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1378 [ + - ]: 9 : if (!keys) {
1379 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1380 : : }
1381 : :
1382 : 9 : CKey key;
1383 [ + - + - : 9 : if (!keys->GetKey(ToKeyID(pkhash), key)) {
+ - ]
1384 : : return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1385 : : }
1386 : :
1387 [ + - - + ]: 9 : if (!MessageSign(key, message, str_sig)) {
1388 : 0 : return SigningResult::SIGNING_FAILED;
1389 : : }
1390 : : return SigningResult::OK;
1391 : 18 : }
1392 : :
1393 : 10393 : std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, const common::PSBTFillOptions& options, int* n_signed) const
1394 : : {
1395 [ + - ]: 10393 : if (n_signed) {
1396 : 10393 : *n_signed = 0;
1397 : : }
1398 [ - + + + ]: 43203 : for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1399 : 32818 : PSBTInput& input = psbtx.inputs.at(i);
1400 : :
1401 [ + + ]: 32818 : if (PSBTInputSigned(input)) {
1402 : 7763 : continue;
1403 : : }
1404 : :
1405 : : // Get the scriptPubKey to know which SigningProvider to use
1406 : 25055 : CScript script;
1407 [ + + ]: 25055 : if (!input.witness_utxo.IsNull()) {
1408 : 18924 : script = input.witness_utxo.scriptPubKey;
1409 [ + + ]: 6131 : } else if (input.non_witness_utxo) {
1410 [ - + + + ]: 5894 : if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1411 : 1 : return PSBTError::MISSING_INPUTS;
1412 : : }
1413 : 5893 : script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1414 : : } else {
1415 : : // There's no UTXO so we can just skip this now
1416 : 237 : continue;
1417 : : }
1418 : :
1419 [ + - ]: 24817 : std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1420 [ + - ]: 24817 : std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1421 [ + + ]: 24817 : if (script_keys) {
1422 [ + - ]: 3723 : keys->Merge(std::move(*script_keys));
1423 : : } else {
1424 : : // Maybe there are pubkeys listed that we can sign for
1425 : 21094 : std::vector<CPubKey> pubkeys;
1426 [ + - ]: 21094 : pubkeys.reserve(input.hd_keypaths.size() + 2);
1427 : :
1428 : : // ECDSA Pubkeys
1429 [ + - + + ]: 34484 : for (const auto& [pk, _] : input.hd_keypaths) {
1430 [ + - ]: 13390 : pubkeys.push_back(pk);
1431 : : }
1432 : :
1433 : : // Taproot output pubkey
1434 : 21094 : std::vector<std::vector<unsigned char>> sols;
1435 [ + - + + ]: 21094 : if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
1436 [ + - ]: 3889 : sols[0].insert(sols[0].begin(), 0x02);
1437 [ + - ]: 3889 : pubkeys.emplace_back(sols[0]);
1438 [ + - ]: 3889 : sols[0][0] = 0x03;
1439 [ + - ]: 3889 : pubkeys.emplace_back(sols[0]);
1440 : : }
1441 : :
1442 : : // Taproot pubkeys
1443 [ + + ]: 36409 : for (const auto& pk_pair : input.m_tap_bip32_paths) {
1444 : 15315 : const XOnlyPubKey& pubkey = pk_pair.first;
1445 [ + + ]: 45945 : for (unsigned char prefix : {0x02, 0x03}) {
1446 : 30630 : unsigned char b[33] = {prefix};
1447 : 30630 : std::copy(pubkey.begin(), pubkey.end(), b + 1);
1448 : 30630 : CPubKey fullpubkey;
1449 : 30630 : fullpubkey.Set(b, b + 33);
1450 [ + - ]: 30630 : pubkeys.push_back(fullpubkey);
1451 : : }
1452 : : }
1453 : :
1454 [ + + ]: 72892 : for (const auto& pubkey : pubkeys) {
1455 [ + - ]: 51798 : std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1456 [ + + ]: 51798 : if (pk_keys) {
1457 [ + - ]: 513 : keys->Merge(std::move(*pk_keys));
1458 : : }
1459 : 51798 : }
1460 : 21094 : }
1461 : :
1462 [ + - ]: 24817 : const auto sign_result = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1463 [ + + + + ]: 24817 : if (!sign_result.has_value() && sign_result.error() != PSBTError::INCOMPLETE) {
1464 [ - + ]: 7 : return sign_result.error();
1465 : : }
1466 : :
1467 [ + - ]: 24810 : bool signed_one = PSBTInputSigned(input);
1468 [ + - + + : 24810 : if (n_signed && (signed_one || !options.sign)) {
+ + ]
1469 : : // If sign is false, we assume that we _could_ sign if we get here. This
1470 : : // will never have false negatives; it is hard to tell under what i
1471 : : // circumstances it could have false positives.
1472 : 16337 : (*n_signed)++;
1473 : : }
1474 [ + - + - ]: 49879 : }
1475 : :
1476 : : // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1477 [ - + + + ]: 89390 : for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1478 : 80109 : std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1479 [ + + ]: 79005 : if (!keys) {
1480 : 77901 : continue;
1481 : : }
1482 [ + - ]: 1104 : UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1483 : 79005 : }
1484 : :
1485 : 10385 : return {};
1486 : : }
1487 : :
1488 : 651 : std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1489 : : {
1490 [ + - ]: 651 : std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1491 [ + - ]: 651 : if (provider) {
1492 [ + - ]: 651 : KeyOriginInfo orig;
1493 [ + - ]: 651 : CKeyID key_id = GetKeyForDestination(*provider, dest);
1494 [ + - + + ]: 651 : if (provider->GetKeyOrigin(key_id, orig)) {
1495 [ + - ]: 563 : LOCK(cs_desc_man);
1496 [ + - ]: 563 : std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1497 [ + - ]: 563 : meta->key_origin = orig;
1498 [ + - ]: 563 : meta->has_key_origin = true;
1499 : 563 : meta->nCreateTime = m_wallet_descriptor.creation_time;
1500 [ + - ]: 563 : return meta;
1501 : 563 : }
1502 : 651 : }
1503 : 88 : return nullptr;
1504 : 651 : }
1505 : :
1506 : 191335 : uint256 DescriptorScriptPubKeyMan::GetID() const
1507 : : {
1508 : 191335 : return m_id;
1509 : : }
1510 : :
1511 : 3042 : void DescriptorScriptPubKeyMan::Load()
1512 : : {
1513 : 3042 : LOCK(cs_desc_man);
1514 : 3042 : std::set<CScript> new_spks;
1515 [ + + ]: 73082 : for (int32_t i = m_wallet_descriptor.GetStart(); i < m_wallet_descriptor.GetEnd(); ++i) {
1516 : 70040 : FlatSigningProvider out_keys;
1517 : 70040 : std::vector<CScript> scripts_temp;
1518 [ + - - + ]: 70040 : if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1519 [ # # ]: 0 : throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1520 : : }
1521 : : // Add all of the scriptPubKeys to the scriptPubKey set
1522 [ + - ]: 70040 : new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1523 [ + + ]: 141401 : for (const CScript& script : scripts_temp) {
1524 [ - + ]: 71361 : if (m_map_script_pub_keys.contains(script)) {
1525 [ # # # # : 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]));
# # ]
1526 : : }
1527 [ + - ]: 71361 : m_map_script_pub_keys[script] = i;
1528 : : }
1529 [ + + ]: 144178 : for (const auto& pk_pair : out_keys.pubkeys) {
1530 : 74138 : const CPubKey& pubkey = pk_pair.second;
1531 [ + + ]: 74138 : if (m_map_pubkeys.contains(pubkey)) {
1532 : : // We don't need to give an error here.
1533 : : // 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
1534 : 38 : continue;
1535 : : }
1536 [ + - ]: 74100 : m_map_pubkeys[pubkey] = i;
1537 : : }
1538 : 70040 : m_max_cached_index++;
1539 : 70040 : }
1540 : : // Make sure the wallet knows about our new spks
1541 [ + - ]: 3042 : m_storage.TopUpCallback(new_spks, this);
1542 [ + - ]: 6084 : }
1543 : :
1544 : 4831 : bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
1545 : : {
1546 : 4831 : LOCK(cs_desc_man);
1547 [ + - + - ]: 4831 : return m_wallet_descriptor.IsCanonicallyEquivalent(desc);
1548 : 4831 : }
1549 : :
1550 : 983 : void DescriptorScriptPubKeyMan::WriteDescriptor()
1551 : : {
1552 : 983 : LOCK(cs_desc_man);
1553 [ + - + - ]: 983 : WalletBatch batch(m_storage.GetDatabase());
1554 [ + - + - : 983 : if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
- + ]
1555 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1556 : : }
1557 [ + - ]: 1966 : }
1558 : :
1559 : 30229 : WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1560 : : {
1561 : 30229 : return m_wallet_descriptor;
1562 : : }
1563 : :
1564 : 562 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1565 : : {
1566 : 562 : return GetScriptPubKeys(0);
1567 : : }
1568 : :
1569 : 674 : std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1570 : : {
1571 : 674 : LOCK(cs_desc_man);
1572 [ + - ]: 674 : std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1573 [ + - ]: 674 : script_pub_keys.reserve(m_map_script_pub_keys.size());
1574 : :
1575 [ + + + + ]: 28554 : for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1576 [ + + + - ]: 27880 : if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1577 : : }
1578 [ + - ]: 674 : return script_pub_keys;
1579 : 674 : }
1580 : :
1581 : 4968 : int32_t DescriptorScriptPubKeyMan::GetEndRange() const
1582 : : {
1583 : 4968 : return m_max_cached_index + 1;
1584 : : }
1585 : :
1586 : 2720 : bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1587 : : {
1588 : 2720 : LOCK(cs_desc_man);
1589 : :
1590 : 2720 : FlatSigningProvider provider;
1591 [ + - ]: 5440 : provider.keys = GetKeys();
1592 : :
1593 [ + + ]: 2720 : if (priv) {
1594 : : // For the private version, always return the master key to avoid
1595 : : // exposing child private keys. The risk implications of exposing child
1596 : : // private keys together with the parent xpub may be non-obvious for users.
1597 [ + - ]: 689 : return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1598 : : }
1599 : :
1600 [ + - ]: 2031 : return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1601 [ + - ]: 5440 : }
1602 : :
1603 : 46 : void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
1604 : : {
1605 : 46 : LOCK(cs_desc_man);
1606 [ + - + - : 46 : if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
+ - - + ]
1607 : 0 : return;
1608 : : }
1609 : :
1610 : : // Skip if we have the last hardened xpub cache
1611 [ + - + + ]: 46 : if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1612 : : return;
1613 : : }
1614 : :
1615 : : // Expand the descriptor
1616 : 6 : FlatSigningProvider provider;
1617 [ + - ]: 12 : provider.keys = GetKeys();
1618 : 6 : FlatSigningProvider out_keys;
1619 : 6 : std::vector<CScript> scripts_temp;
1620 : 6 : DescriptorCache temp_cache;
1621 [ + - - + ]: 6 : if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1622 [ # # ]: 0 : throw std::runtime_error("Unable to expand descriptor");
1623 : : }
1624 : :
1625 : : // Cache the last hardened xpubs
1626 [ + - ]: 6 : DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1627 [ + - + - : 12 : if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
+ - + - -
+ ]
1628 [ # # # # ]: 0 : throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1629 : : }
1630 [ + - ]: 52 : }
1631 : :
1632 : 31 : util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor, const FlatSigningProvider& provider)
1633 : : {
1634 : 31 : LOCK(cs_desc_man);
1635 [ + - ]: 31 : std::string error;
1636 [ + - + + ]: 31 : if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1637 [ + - ]: 9 : return util::Error{Untranslated(std::move(error))};
1638 : : }
1639 : :
1640 : 28 : m_map_pubkeys.clear();
1641 : 28 : m_map_script_pub_keys.clear();
1642 : 28 : m_max_cached_index = -1;
1643 [ + - ]: 28 : m_wallet_descriptor.UpdateFrom(descriptor);
1644 : :
1645 [ + - + - ]: 28 : WalletBatch batch(m_storage.GetDatabase());
1646 [ + + ]: 28 : UpdateWithSigningProvider(batch, provider);
1647 [ + - ]: 24 : NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1648 : 24 : return {};
1649 [ + - ]: 86 : }
1650 : :
1651 : 1176 : void DescriptorScriptPubKeyMan::UpdateWithSigningProvider(WalletBatch& batch, const FlatSigningProvider& signing_provider)
1652 : : {
1653 : 1176 : AssertLockHeld(cs_desc_man);
1654 : : // Add the private keys to the descriptor
1655 [ + + ]: 2077 : for (const auto& entry : signing_provider.keys) {
1656 : 905 : const CKey& key = entry.second;
1657 [ + + ]: 905 : if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
1658 [ + - + - ]: 12 : throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1659 : : }
1660 : : }
1661 : :
1662 : : // Top up key pool, to generate scriptPubKeys
1663 [ + + ]: 1172 : if (!TopUpWithDB(batch)) {
1664 [ + - ]: 1 : throw std::runtime_error("Could not top up scriptPubKeys");
1665 : : }
1666 : 1171 : }
1667 : :
1668 : 31 : bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
1669 : : {
1670 : 31 : LOCK(cs_desc_man);
1671 [ + - - + ]: 31 : if (!HasWalletDescriptor(descriptor)) {
1672 [ - - + - ]: 31 : error = "can only update matching descriptor";
1673 : : return false;
1674 : : }
1675 : :
1676 [ + - + + ]: 31 : if (!descriptor.descriptor->IsRange()) {
1677 : : // Skip range check for non-range descriptors
1678 : : return true;
1679 : : }
1680 : :
1681 [ + + ]: 17 : if (descriptor.GetStart() > m_wallet_descriptor.GetStart() ||
1682 [ + + ]: 15 : descriptor.GetEnd() < m_wallet_descriptor.GetEnd()) {
1683 : : // Use inclusive range for error
1684 : 6 : error = strprintf("new range must include current range = [%d,%d]",
1685 [ + - ]: 3 : m_wallet_descriptor.GetStart(),
1686 [ + - ]: 3 : m_wallet_descriptor.GetEnd() - 1);
1687 : 3 : return false;
1688 : : }
1689 : :
1690 : : return true;
1691 : 31 : }
1692 : : } // namespace wallet
|