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