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