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