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