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