/Users/brunogarcia/projects/bitcoin-core-dev/src/script/sign.cpp
Line | Count | Source |
1 | | // Copyright (c) 2009-2010 Satoshi Nakamoto |
2 | | // Copyright (c) 2009-present The Bitcoin Core developers |
3 | | // Distributed under the MIT software license, see the accompanying |
4 | | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5 | | |
6 | | #include <script/sign.h> |
7 | | |
8 | | #include <consensus/amount.h> |
9 | | #include <key.h> |
10 | | #include <musig.h> |
11 | | #include <policy/policy.h> |
12 | | #include <primitives/transaction.h> |
13 | | #include <random.h> |
14 | | #include <script/keyorigin.h> |
15 | | #include <script/miniscript.h> |
16 | | #include <script/script.h> |
17 | | #include <script/signingprovider.h> |
18 | | #include <script/solver.h> |
19 | | #include <uint256.h> |
20 | | #include <util/translation.h> |
21 | | #include <util/vector.h> |
22 | | |
23 | | typedef std::vector<unsigned char> valtype; |
24 | | |
25 | | MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, int hash_type) |
26 | 0 | : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount}, checker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}, |
27 | 0 | m_txdata(nullptr) |
28 | 0 | { |
29 | 0 | } |
30 | | |
31 | | MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const PrecomputedTransactionData* txdata, int hash_type) |
32 | 0 | : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount}, |
33 | 0 | checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} : |
34 | 0 | MutableTransactionSignatureChecker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}}, |
35 | 0 | m_txdata(txdata) |
36 | 0 | { |
37 | 0 | } |
38 | | |
39 | | bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const |
40 | 0 | { |
41 | 0 | assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0); |
42 | | |
43 | 0 | CKey key; |
44 | 0 | if (!provider.GetKey(address, key)) |
45 | 0 | return false; |
46 | | |
47 | | // Signing with uncompressed keys is disabled in witness scripts |
48 | 0 | if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed()) |
49 | 0 | return false; |
50 | | |
51 | | // Signing without known amount does not work in witness scripts. |
52 | 0 | if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false; |
53 | | |
54 | | // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead. |
55 | 0 | const int hashtype = nHashType == SIGHASH_DEFAULT ? SIGHASH_ALL : nHashType; |
56 | |
|
57 | 0 | uint256 hash = SignatureHash(scriptCode, m_txto, nIn, hashtype, amount, sigversion, m_txdata); |
58 | 0 | if (!key.Sign(hash, vchSig)) |
59 | 0 | return false; |
60 | 0 | vchSig.push_back((unsigned char)hashtype); |
61 | 0 | return true; |
62 | 0 | } |
63 | | |
64 | | std::optional<uint256> MutableTransactionSignatureCreator::ComputeSchnorrSignatureHash(const uint256* leaf_hash, SigVersion sigversion) const |
65 | 0 | { |
66 | 0 | assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); |
67 | | |
68 | | // BIP341/BIP342 signing needs lots of precomputed transaction data. While some |
69 | | // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset |
70 | | // of data present, for now, only support signing when everything is provided. |
71 | 0 | if (!m_txdata || !m_txdata->m_bip341_taproot_ready || !m_txdata->m_spent_outputs_ready) return std::nullopt; |
72 | | |
73 | 0 | ScriptExecutionData execdata; |
74 | 0 | execdata.m_annex_init = true; |
75 | 0 | execdata.m_annex_present = false; // Only support annex-less signing for now. |
76 | 0 | if (sigversion == SigVersion::TAPSCRIPT) { |
77 | 0 | execdata.m_codeseparator_pos_init = true; |
78 | 0 | execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now. |
79 | 0 | if (!leaf_hash) return std::nullopt; // BIP342 signing needs leaf hash. |
80 | 0 | execdata.m_tapleaf_hash_init = true; |
81 | 0 | execdata.m_tapleaf_hash = *leaf_hash; |
82 | 0 | } |
83 | 0 | uint256 hash; |
84 | 0 | if (!SignatureHashSchnorr(hash, execdata, m_txto, nIn, nHashType, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return std::nullopt; |
85 | 0 | return hash; |
86 | 0 | } |
87 | | |
88 | | bool MutableTransactionSignatureCreator::CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion) const |
89 | 0 | { |
90 | 0 | assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); |
91 | | |
92 | 0 | CKey key; |
93 | 0 | if (!provider.GetKeyByXOnly(pubkey, key)) return false; |
94 | | |
95 | 0 | std::optional<uint256> hash = ComputeSchnorrSignatureHash(leaf_hash, sigversion); |
96 | 0 | if (!hash.has_value()) return false; |
97 | | |
98 | 0 | sig.resize(64); |
99 | | // Use uint256{} as aux_rnd for now. |
100 | 0 | if (!key.SignSchnorr(*hash, sig, merkle_root, {})) return false; |
101 | 0 | if (nHashType) sig.push_back(nHashType); |
102 | 0 | return true; |
103 | 0 | } |
104 | | |
105 | | std::vector<uint8_t> MutableTransactionSignatureCreator::CreateMuSig2Nonce(const SigningProvider& provider, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion, const SignatureData& sigdata) const |
106 | 0 | { |
107 | 0 | assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); |
108 | | |
109 | | // Retrieve the private key |
110 | 0 | CKey key; |
111 | 0 | if (!provider.GetKey(part_pubkey.GetID(), key)) return {}; |
112 | | |
113 | | // Retrieve participant pubkeys |
114 | 0 | auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey); |
115 | 0 | if (it == sigdata.musig2_pubkeys.end()) return {}; |
116 | 0 | const std::vector<CPubKey>& pubkeys = it->second; |
117 | 0 | if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {}; |
118 | | |
119 | | // Compute sighash |
120 | 0 | std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion); |
121 | 0 | if (!sighash.has_value()) return {}; |
122 | | |
123 | 0 | MuSig2SecNonce secnonce; |
124 | 0 | std::vector<uint8_t> out = key.CreateMuSig2Nonce(secnonce, *sighash, aggregate_pubkey, pubkeys); |
125 | 0 | if (out.empty()) return {}; |
126 | | |
127 | | // Store the secnonce in the SigningProvider |
128 | 0 | provider.SetMuSig2SecNonce(MuSig2SessionID(script_pubkey, part_pubkey, *sighash), std::move(secnonce)); |
129 | |
|
130 | 0 | return out; |
131 | 0 | } |
132 | | |
133 | | bool MutableTransactionSignatureCreator::CreateMuSig2PartialSig(const SigningProvider& provider, uint256& partial_sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const |
134 | 0 | { |
135 | 0 | assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); |
136 | | |
137 | | // Retrieve private key |
138 | 0 | CKey key; |
139 | 0 | if (!provider.GetKey(part_pubkey.GetID(), key)) return false; |
140 | | |
141 | | // Retrieve participant pubkeys |
142 | 0 | auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey); |
143 | 0 | if (it == sigdata.musig2_pubkeys.end()) return false; |
144 | 0 | const std::vector<CPubKey>& pubkeys = it->second; |
145 | 0 | if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {}; |
146 | | |
147 | | // Retrieve pubnonces |
148 | 0 | auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256()); |
149 | 0 | auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey); |
150 | 0 | if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false; |
151 | 0 | const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second; |
152 | | |
153 | | // Check if enough pubnonces |
154 | 0 | if (pubnonces.size() != pubkeys.size()) return false; |
155 | | |
156 | | // Compute sighash |
157 | 0 | std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion); |
158 | 0 | if (!sighash.has_value()) return false; |
159 | | |
160 | | // Retrieve the secnonce |
161 | 0 | uint256 session_id = MuSig2SessionID(script_pubkey, part_pubkey, *sighash); |
162 | 0 | std::optional<std::reference_wrapper<MuSig2SecNonce>> secnonce = provider.GetMuSig2SecNonce(session_id); |
163 | 0 | if (!secnonce || !secnonce->get().IsValid()) return false; |
164 | | |
165 | | // Compute the sig |
166 | 0 | std::optional<uint256> sig = key.CreateMuSig2PartialSig(*sighash, aggregate_pubkey, pubkeys, pubnonces, *secnonce, tweaks); |
167 | 0 | if (!sig) return false; |
168 | 0 | partial_sig = std::move(*sig); |
169 | | |
170 | | // Delete the secnonce now that we're done with it |
171 | 0 | assert(!secnonce->get().IsValid()); |
172 | 0 | provider.DeleteMuSig2Session(session_id); |
173 | |
|
174 | 0 | return true; |
175 | 0 | } |
176 | | |
177 | | bool MutableTransactionSignatureCreator::CreateMuSig2AggregateSig(const std::vector<CPubKey>& participants, std::vector<uint8_t>& sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const |
178 | 0 | { |
179 | 0 | assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); |
180 | 0 | if (!participants.size()) return false; |
181 | | |
182 | | // Retrieve pubnonces and partial sigs |
183 | 0 | auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256()); |
184 | 0 | auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey); |
185 | 0 | if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false; |
186 | 0 | const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second; |
187 | 0 | auto partial_sigs_it = sigdata.musig2_partial_sigs.find(this_leaf_aggkey); |
188 | 0 | if (partial_sigs_it == sigdata.musig2_partial_sigs.end()) return false; |
189 | 0 | const std::map<CPubKey, uint256>& partial_sigs = partial_sigs_it->second; |
190 | | |
191 | | // Check if enough pubnonces and partial sigs |
192 | 0 | if (pubnonces.size() != participants.size()) return false; |
193 | 0 | if (partial_sigs.size() != participants.size()) return false; |
194 | | |
195 | | // Compute sighash |
196 | 0 | std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion); |
197 | 0 | if (!sighash.has_value()) return false; |
198 | | |
199 | 0 | std::optional<std::vector<uint8_t>> res = ::CreateMuSig2AggregateSig(participants, aggregate_pubkey, tweaks, *sighash, pubnonces, partial_sigs); |
200 | 0 | if (!res) return false; |
201 | 0 | sig = res.value(); |
202 | 0 | if (nHashType) sig.push_back(nHashType); |
203 | |
|
204 | 0 | return true; |
205 | 0 | } |
206 | | |
207 | | static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script) |
208 | 0 | { |
209 | 0 | if (provider.GetCScript(scriptid, script)) { |
210 | 0 | return true; |
211 | 0 | } |
212 | | // Look for scripts in SignatureData |
213 | 0 | if (CScriptID(sigdata.redeem_script) == scriptid) { |
214 | 0 | script = sigdata.redeem_script; |
215 | 0 | return true; |
216 | 0 | } else if (CScriptID(sigdata.witness_script) == scriptid) { |
217 | 0 | script = sigdata.witness_script; |
218 | 0 | return true; |
219 | 0 | } |
220 | 0 | return false; |
221 | 0 | } |
222 | | |
223 | | static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey) |
224 | 0 | { |
225 | | // Look for pubkey in all partial sigs |
226 | 0 | const auto it = sigdata.signatures.find(address); |
227 | 0 | if (it != sigdata.signatures.end()) { |
228 | 0 | pubkey = it->second.first; |
229 | 0 | return true; |
230 | 0 | } |
231 | | // Look for pubkey in pubkey lists |
232 | 0 | const auto& pk_it = sigdata.misc_pubkeys.find(address); |
233 | 0 | if (pk_it != sigdata.misc_pubkeys.end()) { |
234 | 0 | pubkey = pk_it->second.first; |
235 | 0 | return true; |
236 | 0 | } |
237 | 0 | const auto& tap_pk_it = sigdata.tap_pubkeys.find(address); |
238 | 0 | if (tap_pk_it != sigdata.tap_pubkeys.end()) { |
239 | 0 | pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey(); |
240 | 0 | return true; |
241 | 0 | } |
242 | | // Query the underlying provider |
243 | 0 | return provider.GetPubKey(address, pubkey); |
244 | 0 | } |
245 | | |
246 | | static bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const CPubKey& pubkey, const CScript& scriptcode, SigVersion sigversion) |
247 | 0 | { |
248 | 0 | CKeyID keyid = pubkey.GetID(); |
249 | 0 | const auto it = sigdata.signatures.find(keyid); |
250 | 0 | if (it != sigdata.signatures.end()) { |
251 | 0 | sig_out = it->second.second; |
252 | 0 | return true; |
253 | 0 | } |
254 | 0 | KeyOriginInfo info; |
255 | 0 | if (provider.GetKeyOrigin(keyid, info)) { |
256 | 0 | sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info))); |
257 | 0 | } |
258 | 0 | if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) { |
259 | 0 | auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out)); |
260 | 0 | assert(i.second); |
261 | 0 | return true; |
262 | 0 | } |
263 | | // Could not make signature or signature not found, add keyid to missing |
264 | 0 | sigdata.missing_sigs.push_back(keyid); |
265 | 0 | return false; |
266 | 0 | } |
267 | | |
268 | | static bool SignMuSig2(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const XOnlyPubKey& script_pubkey, const uint256* merkle_root, const uint256* leaf_hash, SigVersion sigversion) |
269 | 0 | { |
270 | 0 | Assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); Line | Count | Source | 113 | 0 | #define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val) |
|
271 | | |
272 | | // Lookup derivation paths for the script pubkey |
273 | 0 | KeyOriginInfo agg_info; |
274 | 0 | auto misc_pk_it = sigdata.taproot_misc_pubkeys.find(script_pubkey); |
275 | 0 | if (misc_pk_it != sigdata.taproot_misc_pubkeys.end()) { |
276 | 0 | agg_info = misc_pk_it->second.second; |
277 | 0 | } |
278 | |
|
279 | 0 | for (const auto& [agg_pub, part_pks] : sigdata.musig2_pubkeys) { |
280 | 0 | if (part_pks.empty()) continue; |
281 | | |
282 | | // Fill participant derivation path info |
283 | 0 | for (const auto& part_pk : part_pks) { |
284 | 0 | KeyOriginInfo part_info; |
285 | 0 | if (provider.GetKeyOrigin(part_pk.GetID(), part_info)) { |
286 | 0 | XOnlyPubKey xonly_part(part_pk); |
287 | 0 | auto it = sigdata.taproot_misc_pubkeys.find(xonly_part); |
288 | 0 | if (it == sigdata.taproot_misc_pubkeys.end()) { |
289 | 0 | it = sigdata.taproot_misc_pubkeys.emplace(xonly_part, std::make_pair(std::set<uint256>(), part_info)).first; |
290 | 0 | } |
291 | 0 | if (leaf_hash) it->second.first.insert(*leaf_hash); |
292 | 0 | } |
293 | 0 | } |
294 | | |
295 | | // The pubkey in the script may not be the actual aggregate of the participants, but derived from it. |
296 | | // Check the derivation, and compute the BIP 32 derivation tweaks |
297 | 0 | std::vector<std::pair<uint256, bool>> tweaks; |
298 | 0 | CPubKey plain_pub = agg_pub; |
299 | 0 | if (XOnlyPubKey(agg_pub) != script_pubkey) { |
300 | 0 | if (agg_info.path.empty()) continue; |
301 | | // Compute and compare fingerprint |
302 | 0 | CKeyID keyid = agg_pub.GetID(); |
303 | 0 | if (!std::equal(agg_info.fingerprint, agg_info.fingerprint + sizeof(agg_info.fingerprint), keyid.data())) { |
304 | 0 | continue; |
305 | 0 | } |
306 | | // Get the BIP32 derivation tweaks |
307 | 0 | CExtPubKey extpub = CreateMuSig2SyntheticXpub(agg_pub); |
308 | 0 | for (const int i : agg_info.path) { |
309 | 0 | auto& [t, xonly] = tweaks.emplace_back(); |
310 | 0 | xonly = false; |
311 | 0 | if (!extpub.Derive(extpub, i, &t)) { |
312 | 0 | return false; |
313 | 0 | } |
314 | 0 | } |
315 | 0 | Assert(XOnlyPubKey(extpub.pubkey) == script_pubkey); Line | Count | Source | 113 | 0 | #define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val) |
|
316 | 0 | plain_pub = extpub.pubkey; |
317 | 0 | } |
318 | | |
319 | | // Add the merkle root tweak |
320 | 0 | if (sigversion == SigVersion::TAPROOT && merkle_root) { |
321 | 0 | tweaks.emplace_back(script_pubkey.ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root), true); |
322 | 0 | std::optional<std::pair<XOnlyPubKey, bool>> tweaked = script_pubkey.CreateTapTweak(merkle_root->IsNull() ? nullptr : merkle_root); |
323 | 0 | if (!Assume(tweaked)) return false; Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
|
324 | 0 | plain_pub = tweaked->first.GetCPubKeys().at(tweaked->second ? 1 : 0); |
325 | 0 | } |
326 | | |
327 | | // First try to aggregate |
328 | 0 | if (creator.CreateMuSig2AggregateSig(part_pks, sig_out, agg_pub, plain_pub, leaf_hash, tweaks, sigversion, sigdata)) { |
329 | 0 | if (sigversion == SigVersion::TAPROOT) { |
330 | 0 | sigdata.taproot_key_path_sig = sig_out; |
331 | 0 | } else { |
332 | 0 | auto lookup_key = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256()); |
333 | 0 | sigdata.taproot_script_sigs[lookup_key] = sig_out; |
334 | 0 | } |
335 | 0 | continue; |
336 | 0 | } |
337 | | // Cannot aggregate, try making partial sigs for every participant |
338 | 0 | auto pub_key_leaf_hash = std::make_pair(plain_pub, leaf_hash ? *leaf_hash : uint256()); |
339 | 0 | for (const CPubKey& part_pk : part_pks) { |
340 | 0 | uint256 partial_sig; |
341 | 0 | if (creator.CreateMuSig2PartialSig(provider, partial_sig, agg_pub, plain_pub, part_pk, leaf_hash, tweaks, sigversion, sigdata) && Assume(!partial_sig.IsNull())) {Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
|
342 | 0 | sigdata.musig2_partial_sigs[pub_key_leaf_hash].emplace(part_pk, partial_sig); |
343 | 0 | } |
344 | 0 | } |
345 | | // If there are any partial signatures, exit early |
346 | 0 | auto partial_sigs_it = sigdata.musig2_partial_sigs.find(pub_key_leaf_hash); |
347 | 0 | if (partial_sigs_it != sigdata.musig2_partial_sigs.end() && !partial_sigs_it->second.empty()) { |
348 | 0 | continue; |
349 | 0 | } |
350 | | // No partial sigs, try to make pubnonces |
351 | 0 | std::map<CPubKey, std::vector<uint8_t>>& pubnonces = sigdata.musig2_pubnonces[pub_key_leaf_hash]; |
352 | 0 | for (const CPubKey& part_pk : part_pks) { |
353 | 0 | if (pubnonces.contains(part_pk)) continue; |
354 | 0 | std::vector<uint8_t> pubnonce = creator.CreateMuSig2Nonce(provider, agg_pub, plain_pub, part_pk, leaf_hash, merkle_root, sigversion, sigdata); |
355 | 0 | if (pubnonce.empty()) continue; |
356 | 0 | pubnonces[part_pk] = std::move(pubnonce); |
357 | 0 | } |
358 | 0 | } |
359 | 0 | return true; |
360 | 0 | } |
361 | | |
362 | | static bool CreateTaprootScriptSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const XOnlyPubKey& pubkey, const uint256& leaf_hash, SigVersion sigversion) |
363 | 0 | { |
364 | 0 | KeyOriginInfo info; |
365 | 0 | if (provider.GetKeyOriginByXOnly(pubkey, info)) { |
366 | 0 | auto it = sigdata.taproot_misc_pubkeys.find(pubkey); |
367 | 0 | if (it == sigdata.taproot_misc_pubkeys.end()) { |
368 | 0 | sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info)); |
369 | 0 | } else { |
370 | 0 | it->second.first.insert(leaf_hash); |
371 | 0 | } |
372 | 0 | } |
373 | |
|
374 | 0 | auto lookup_key = std::make_pair(pubkey, leaf_hash); |
375 | 0 | auto it = sigdata.taproot_script_sigs.find(lookup_key); |
376 | 0 | if (it != sigdata.taproot_script_sigs.end()) { |
377 | 0 | sig_out = it->second; |
378 | 0 | return true; |
379 | 0 | } |
380 | | |
381 | 0 | if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) { |
382 | 0 | sigdata.taproot_script_sigs[lookup_key] = sig_out; |
383 | 0 | } else if (!SignMuSig2(creator, sigdata, provider, sig_out, pubkey, /*merkle_root=*/nullptr, &leaf_hash, sigversion)) { |
384 | 0 | return false; |
385 | 0 | } |
386 | | |
387 | 0 | return sigdata.taproot_script_sigs.contains(lookup_key); |
388 | 0 | } |
389 | | |
390 | | template<typename M, typename K, typename V> |
391 | | miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value) |
392 | 0 | { |
393 | 0 | auto it = map.find(key); |
394 | 0 | if (it != map.end()) { |
395 | 0 | value = it->second; |
396 | 0 | return miniscript::Availability::YES; |
397 | 0 | } |
398 | 0 | return miniscript::Availability::NO; |
399 | 0 | } |
400 | | |
401 | | /** |
402 | | * Context for solving a Miniscript. |
403 | | * If enough material (access to keys, hash preimages, ..) is given, produces a valid satisfaction. |
404 | | */ |
405 | | template<typename Pk> |
406 | | struct Satisfier { |
407 | | using Key = Pk; |
408 | | |
409 | | const SigningProvider& m_provider; |
410 | | SignatureData& m_sig_data; |
411 | | const BaseSignatureCreator& m_creator; |
412 | | const CScript& m_witness_script; |
413 | | //! The context of the script we are satisfying (either P2WSH or Tapscript). |
414 | | const miniscript::MiniscriptContext m_script_ctx; |
415 | | |
416 | | explicit Satisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND, |
417 | | const BaseSignatureCreator& creator LIFETIMEBOUND, |
418 | | const CScript& witscript LIFETIMEBOUND, |
419 | 0 | miniscript::MiniscriptContext script_ctx) : m_provider(provider), |
420 | 0 | m_sig_data(sig_data), |
421 | 0 | m_creator(creator), |
422 | 0 | m_witness_script(witscript), |
423 | 0 | m_script_ctx(script_ctx) {}Unexecuted instantiation: Satisfier<XOnlyPubKey>::Satisfier(SigningProvider const&, SignatureData&, BaseSignatureCreator const&, CScript const&, miniscript::MiniscriptContext) Unexecuted instantiation: Satisfier<CPubKey>::Satisfier(SigningProvider const&, SignatureData&, BaseSignatureCreator const&, CScript const&, miniscript::MiniscriptContext) |
424 | | |
425 | 0 | static bool KeyCompare(const Key& a, const Key& b) { |
426 | 0 | return a < b; |
427 | 0 | } Unexecuted instantiation: Satisfier<XOnlyPubKey>::KeyCompare(XOnlyPubKey const&, XOnlyPubKey const&) Unexecuted instantiation: Satisfier<CPubKey>::KeyCompare(CPubKey const&, CPubKey const&) |
428 | | |
429 | | //! Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey. |
430 | | template<typename I> |
431 | 0 | std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const { |
432 | 0 | assert(last - first == 20); |
433 | 0 | CPubKey pubkey; |
434 | 0 | CKeyID key_id; |
435 | 0 | std::copy(first, last, key_id.begin()); |
436 | 0 | if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey; |
437 | 0 | m_sig_data.missing_pubkeys.push_back(key_id); |
438 | 0 | return {}; |
439 | 0 | } Unexecuted instantiation: std::__1::optional<CPubKey> Satisfier<XOnlyPubKey>::CPubFromPKHBytes<std::__1::__wrap_iter<unsigned char*>>(std::__1::__wrap_iter<unsigned char*>, std::__1::__wrap_iter<unsigned char*>) const Unexecuted instantiation: std::__1::optional<CPubKey> Satisfier<CPubKey>::CPubFromPKHBytes<std::__1::__wrap_iter<unsigned char*>>(std::__1::__wrap_iter<unsigned char*>, std::__1::__wrap_iter<unsigned char*>) const |
440 | | |
441 | | //! Conversion to raw public key. |
442 | 0 | std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }Unexecuted instantiation: Satisfier<XOnlyPubKey>::ToPKBytes(XOnlyPubKey const&) const Unexecuted instantiation: Satisfier<CPubKey>::ToPKBytes(CPubKey const&) const |
443 | | |
444 | | //! Time lock satisfactions. |
445 | 0 | bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }Unexecuted instantiation: Satisfier<XOnlyPubKey>::CheckAfter(unsigned int) const Unexecuted instantiation: Satisfier<CPubKey>::CheckAfter(unsigned int) const |
446 | 0 | bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }Unexecuted instantiation: Satisfier<XOnlyPubKey>::CheckOlder(unsigned int) const Unexecuted instantiation: Satisfier<CPubKey>::CheckOlder(unsigned int) const |
447 | | |
448 | | //! Hash preimage satisfactions. |
449 | 0 | miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { |
450 | 0 | return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage); |
451 | 0 | } Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatSHA256(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const Unexecuted instantiation: Satisfier<CPubKey>::SatSHA256(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const |
452 | 0 | miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { |
453 | 0 | return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage); |
454 | 0 | } Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatRIPEMD160(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const Unexecuted instantiation: Satisfier<CPubKey>::SatRIPEMD160(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const |
455 | 0 | miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { |
456 | 0 | return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage); |
457 | 0 | } Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatHASH256(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const Unexecuted instantiation: Satisfier<CPubKey>::SatHASH256(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const |
458 | 0 | miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const { |
459 | 0 | return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage); |
460 | 0 | } Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatHASH160(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const Unexecuted instantiation: Satisfier<CPubKey>::SatHASH160(std::__1::vector<unsigned char, std::__1::allocator<unsigned char>> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char>>&) const |
461 | | |
462 | 0 | miniscript::MiniscriptContext MsContext() const { |
463 | 0 | return m_script_ctx; |
464 | 0 | } Unexecuted instantiation: Satisfier<XOnlyPubKey>::MsContext() const Unexecuted instantiation: Satisfier<CPubKey>::MsContext() const |
465 | | }; |
466 | | |
467 | | /** Miniscript satisfier specific to P2WSH context. */ |
468 | | struct WshSatisfier: Satisfier<CPubKey> { |
469 | | explicit WshSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND, |
470 | | const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& witscript LIFETIMEBOUND) |
471 | 0 | : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {} |
472 | | |
473 | | //! Conversion from a raw compressed public key. |
474 | | template <typename I> |
475 | 0 | std::optional<CPubKey> FromPKBytes(I first, I last) const { |
476 | 0 | CPubKey pubkey{first, last}; |
477 | 0 | if (pubkey.IsValid()) return pubkey; |
478 | 0 | return {}; |
479 | 0 | } |
480 | | |
481 | | //! Conversion from a raw compressed public key hash. |
482 | | template<typename I> |
483 | 0 | std::optional<CPubKey> FromPKHBytes(I first, I last) const { |
484 | 0 | return Satisfier::CPubFromPKHBytes(first, last); |
485 | 0 | } |
486 | | |
487 | | //! Satisfy an ECDSA signature check. |
488 | 0 | miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const { |
489 | 0 | if (CreateSig(m_creator, m_sig_data, m_provider, sig, key, m_witness_script, SigVersion::WITNESS_V0)) { |
490 | 0 | return miniscript::Availability::YES; |
491 | 0 | } |
492 | 0 | return miniscript::Availability::NO; |
493 | 0 | } |
494 | | }; |
495 | | |
496 | | /** Miniscript satisfier specific to Tapscript context. */ |
497 | | struct TapSatisfier: Satisfier<XOnlyPubKey> { |
498 | | const uint256& m_leaf_hash; |
499 | | |
500 | | explicit TapSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND, |
501 | | const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& script LIFETIMEBOUND, |
502 | | const uint256& leaf_hash LIFETIMEBOUND) |
503 | 0 | : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT), |
504 | 0 | m_leaf_hash(leaf_hash) {} |
505 | | |
506 | | //! Conversion from a raw xonly public key. |
507 | | template <typename I> |
508 | 0 | std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const { |
509 | 0 | if (last - first != 32) return {}; |
510 | 0 | XOnlyPubKey pubkey; |
511 | 0 | std::copy(first, last, pubkey.begin()); |
512 | 0 | return pubkey; |
513 | 0 | } |
514 | | |
515 | | //! Conversion from a raw xonly public key hash. |
516 | | template<typename I> |
517 | 0 | std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const { |
518 | 0 | if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey}; |
519 | 0 | return {}; |
520 | 0 | } |
521 | | |
522 | | //! Satisfy a BIP340 signature check. |
523 | 0 | miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const { |
524 | 0 | if (CreateTaprootScriptSig(m_creator, m_sig_data, m_provider, sig, key, m_leaf_hash, SigVersion::TAPSCRIPT)) { |
525 | 0 | return miniscript::Availability::YES; |
526 | 0 | } |
527 | 0 | return miniscript::Availability::NO; |
528 | 0 | } |
529 | | }; |
530 | | |
531 | | static bool SignTaprootScript(const SigningProvider& provider, const BaseSignatureCreator& creator, SignatureData& sigdata, int leaf_version, std::span<const unsigned char> script_bytes, std::vector<valtype>& result) |
532 | 0 | { |
533 | | // Only BIP342 tapscript signing is supported for now. |
534 | 0 | if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false; |
535 | | |
536 | 0 | uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes); |
537 | 0 | CScript script = CScript(script_bytes.begin(), script_bytes.end()); |
538 | |
|
539 | 0 | TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash}; |
540 | 0 | const auto ms = miniscript::FromScript(script, ms_satisfier); |
541 | 0 | return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES; |
542 | 0 | } |
543 | | |
544 | | static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result) |
545 | 0 | { |
546 | 0 | TaprootSpendData spenddata; |
547 | 0 | TaprootBuilder builder; |
548 | | |
549 | | // Gather information about this output. |
550 | 0 | if (provider.GetTaprootSpendData(output, spenddata)) { |
551 | 0 | sigdata.tr_spenddata.Merge(spenddata); |
552 | 0 | } |
553 | 0 | if (provider.GetTaprootBuilder(output, builder)) { |
554 | 0 | sigdata.tr_builder = builder; |
555 | 0 | } |
556 | 0 | if (auto agg_keys = provider.GetAllMuSig2ParticipantPubkeys(); !agg_keys.empty()) { |
557 | 0 | sigdata.musig2_pubkeys.insert(agg_keys.begin(), agg_keys.end()); |
558 | 0 | } |
559 | | |
560 | | |
561 | | // Try key path spending. |
562 | 0 | { |
563 | 0 | KeyOriginInfo internal_key_info; |
564 | 0 | if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, internal_key_info)) { |
565 | 0 | auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key); |
566 | 0 | if (it == sigdata.taproot_misc_pubkeys.end()) { |
567 | 0 | sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), internal_key_info)); |
568 | 0 | } |
569 | 0 | } |
570 | |
|
571 | 0 | KeyOriginInfo output_key_info; |
572 | 0 | if (provider.GetKeyOriginByXOnly(output, output_key_info)) { |
573 | 0 | auto it = sigdata.taproot_misc_pubkeys.find(output); |
574 | 0 | if (it == sigdata.taproot_misc_pubkeys.end()) { |
575 | 0 | sigdata.taproot_misc_pubkeys.emplace(output, std::make_pair(std::set<uint256>(), output_key_info)); |
576 | 0 | } |
577 | 0 | } |
578 | |
|
579 | 0 | auto make_keypath_sig = [&](const XOnlyPubKey& pk, const uint256* merkle_root) { |
580 | 0 | std::vector<unsigned char> sig; |
581 | 0 | if (creator.CreateSchnorrSig(provider, sig, pk, nullptr, merkle_root, SigVersion::TAPROOT)) { |
582 | 0 | sigdata.taproot_key_path_sig = sig; |
583 | 0 | } else { |
584 | 0 | SignMuSig2(creator, sigdata, provider, sig, pk, merkle_root, /*leaf_hash=*/nullptr, SigVersion::TAPROOT); |
585 | 0 | } |
586 | 0 | }; |
587 | | |
588 | | // First try signing with internal key |
589 | 0 | if (sigdata.taproot_key_path_sig.size() == 0) { |
590 | 0 | make_keypath_sig(sigdata.tr_spenddata.internal_key, &sigdata.tr_spenddata.merkle_root); |
591 | 0 | } |
592 | | // Try signing with output key if still no signature |
593 | 0 | if (sigdata.taproot_key_path_sig.size() == 0) { |
594 | 0 | make_keypath_sig(output, nullptr); |
595 | 0 | } |
596 | 0 | if (sigdata.taproot_key_path_sig.size()) { |
597 | 0 | result = Vector(sigdata.taproot_key_path_sig); |
598 | 0 | return true; |
599 | 0 | } |
600 | 0 | } |
601 | | |
602 | | // Try script path spending. |
603 | 0 | std::vector<std::vector<unsigned char>> smallest_result_stack; |
604 | 0 | for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) { |
605 | 0 | const auto& [script, leaf_ver] = key; |
606 | 0 | std::vector<std::vector<unsigned char>> result_stack; |
607 | 0 | if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) { |
608 | 0 | result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script |
609 | 0 | result_stack.push_back(*control_blocks.begin()); // Push the smallest control block |
610 | 0 | if (smallest_result_stack.size() == 0 || |
611 | 0 | GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) { |
612 | 0 | smallest_result_stack = std::move(result_stack); |
613 | 0 | } |
614 | 0 | } |
615 | 0 | } |
616 | 0 | if (smallest_result_stack.size() != 0) { |
617 | 0 | result = std::move(smallest_result_stack); |
618 | 0 | return true; |
619 | 0 | } |
620 | | |
621 | 0 | return false; |
622 | 0 | } |
623 | | |
624 | | /** |
625 | | * Sign scriptPubKey using signature made with creator. |
626 | | * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed), |
627 | | * unless whichTypeRet is TxoutType::SCRIPTHASH, in which case scriptSigRet is the redemption script. |
628 | | * Returns false if scriptPubKey could not be completely satisfied. |
629 | | */ |
630 | | static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, |
631 | | std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata) |
632 | 0 | { |
633 | 0 | CScript scriptRet; |
634 | 0 | ret.clear(); |
635 | 0 | std::vector<unsigned char> sig; |
636 | |
|
637 | 0 | std::vector<valtype> vSolutions; |
638 | 0 | whichTypeRet = Solver(scriptPubKey, vSolutions); |
639 | |
|
640 | 0 | switch (whichTypeRet) { |
641 | 0 | case TxoutType::NONSTANDARD: |
642 | 0 | case TxoutType::NULL_DATA: |
643 | 0 | case TxoutType::WITNESS_UNKNOWN: |
644 | 0 | return false; |
645 | 0 | case TxoutType::PUBKEY: |
646 | 0 | if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false; |
647 | 0 | ret.push_back(std::move(sig)); |
648 | 0 | return true; |
649 | 0 | case TxoutType::PUBKEYHASH: { |
650 | 0 | CKeyID keyID = CKeyID(uint160(vSolutions[0])); |
651 | 0 | CPubKey pubkey; |
652 | 0 | if (!GetPubKey(provider, sigdata, keyID, pubkey)) { |
653 | | // Pubkey could not be found, add to missing |
654 | 0 | sigdata.missing_pubkeys.push_back(keyID); |
655 | 0 | return false; |
656 | 0 | } |
657 | 0 | if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false; |
658 | 0 | ret.push_back(std::move(sig)); |
659 | 0 | ret.push_back(ToByteVector(pubkey)); |
660 | 0 | return true; |
661 | 0 | } |
662 | 0 | case TxoutType::SCRIPTHASH: { |
663 | 0 | uint160 h160{vSolutions[0]}; |
664 | 0 | if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) { |
665 | 0 | ret.emplace_back(scriptRet.begin(), scriptRet.end()); |
666 | 0 | return true; |
667 | 0 | } |
668 | | // Could not find redeemScript, add to missing |
669 | 0 | sigdata.missing_redeem_script = h160; |
670 | 0 | return false; |
671 | 0 | } |
672 | 0 | case TxoutType::MULTISIG: { |
673 | 0 | size_t required = vSolutions.front()[0]; |
674 | 0 | ret.emplace_back(); // workaround CHECKMULTISIG bug |
675 | 0 | for (size_t i = 1; i < vSolutions.size() - 1; ++i) { |
676 | 0 | CPubKey pubkey = CPubKey(vSolutions[i]); |
677 | | // We need to always call CreateSig in order to fill sigdata with all |
678 | | // possible signatures that we can create. This will allow further PSBT |
679 | | // processing to work as it needs all possible signature and pubkey pairs |
680 | 0 | if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) { |
681 | 0 | if (ret.size() < required + 1) { |
682 | 0 | ret.push_back(std::move(sig)); |
683 | 0 | } |
684 | 0 | } |
685 | 0 | } |
686 | 0 | bool ok = ret.size() == required + 1; |
687 | 0 | for (size_t i = 0; i + ret.size() < required + 1; ++i) { |
688 | 0 | ret.emplace_back(); |
689 | 0 | } |
690 | 0 | return ok; |
691 | 0 | } |
692 | 0 | case TxoutType::WITNESS_V0_KEYHASH: |
693 | 0 | ret.push_back(vSolutions[0]); |
694 | 0 | return true; |
695 | | |
696 | 0 | case TxoutType::WITNESS_V0_SCRIPTHASH: |
697 | 0 | if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) { |
698 | 0 | ret.emplace_back(scriptRet.begin(), scriptRet.end()); |
699 | 0 | return true; |
700 | 0 | } |
701 | | // Could not find witnessScript, add to missing |
702 | 0 | sigdata.missing_witness_script = uint256(vSolutions[0]); |
703 | 0 | return false; |
704 | | |
705 | 0 | case TxoutType::WITNESS_V1_TAPROOT: |
706 | 0 | return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret); |
707 | | |
708 | 0 | case TxoutType::ANCHOR: |
709 | 0 | return true; |
710 | 0 | } // no default case, so the compiler can warn about missing cases |
711 | 0 | assert(false); |
712 | 0 | } |
713 | | |
714 | | static CScript PushAll(const std::vector<valtype>& values) |
715 | 0 | { |
716 | 0 | CScript result; |
717 | 0 | for (const valtype& v : values) { |
718 | 0 | if (v.size() == 0) { |
719 | 0 | result << OP_0; |
720 | 0 | } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) { |
721 | 0 | result << CScript::EncodeOP_N(v[0]); |
722 | 0 | } else if (v.size() == 1 && v[0] == 0x81) { |
723 | 0 | result << OP_1NEGATE; |
724 | 0 | } else { |
725 | 0 | result << v; |
726 | 0 | } |
727 | 0 | } |
728 | 0 | return result; |
729 | 0 | } |
730 | | |
731 | | bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata) |
732 | 0 | { |
733 | 0 | if (sigdata.complete) return true; |
734 | | |
735 | 0 | std::vector<valtype> result; |
736 | 0 | TxoutType whichType; |
737 | 0 | bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata); |
738 | 0 | bool P2SH = false; |
739 | 0 | CScript subscript; |
740 | |
|
741 | 0 | if (solved && whichType == TxoutType::SCRIPTHASH) |
742 | 0 | { |
743 | | // Solver returns the subscript that needs to be evaluated; |
744 | | // the final scriptSig is the signatures from that |
745 | | // and then the serialized subscript: |
746 | 0 | subscript = CScript(result[0].begin(), result[0].end()); |
747 | 0 | sigdata.redeem_script = subscript; |
748 | 0 | solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH; |
749 | 0 | P2SH = true; |
750 | 0 | } |
751 | |
|
752 | 0 | if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH) |
753 | 0 | { |
754 | 0 | CScript witnessscript; |
755 | 0 | witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG; |
756 | 0 | TxoutType subType; |
757 | 0 | solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata); |
758 | 0 | sigdata.scriptWitness.stack = result; |
759 | 0 | sigdata.witness = true; |
760 | 0 | result.clear(); |
761 | 0 | } |
762 | 0 | else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH) |
763 | 0 | { |
764 | 0 | CScript witnessscript(result[0].begin(), result[0].end()); |
765 | 0 | sigdata.witness_script = witnessscript; |
766 | |
|
767 | 0 | TxoutType subType{TxoutType::NONSTANDARD}; |
768 | 0 | solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata) && subType != TxoutType::SCRIPTHASH && subType != TxoutType::WITNESS_V0_SCRIPTHASH && subType != TxoutType::WITNESS_V0_KEYHASH; |
769 | | |
770 | | // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript. |
771 | | // Note we need to check if the result stack is empty before, because it might be used even if the Script |
772 | | // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures |
773 | | // and the extractor relies on this behaviour to combine witnesses. |
774 | 0 | if (!solved && result.empty()) { |
775 | 0 | WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript}; |
776 | 0 | const auto ms = miniscript::FromScript(witnessscript, ms_satisfier); |
777 | 0 | solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES; |
778 | 0 | } |
779 | 0 | result.emplace_back(witnessscript.begin(), witnessscript.end()); |
780 | |
|
781 | 0 | sigdata.scriptWitness.stack = result; |
782 | 0 | sigdata.witness = true; |
783 | 0 | result.clear(); |
784 | 0 | } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) { |
785 | 0 | sigdata.witness = true; |
786 | 0 | if (solved) { |
787 | 0 | sigdata.scriptWitness.stack = std::move(result); |
788 | 0 | } |
789 | 0 | result.clear(); |
790 | 0 | } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) { |
791 | 0 | sigdata.witness = true; |
792 | 0 | } |
793 | |
|
794 | 0 | if (!sigdata.witness) sigdata.scriptWitness.stack.clear(); |
795 | 0 | if (P2SH) { |
796 | 0 | result.emplace_back(subscript.begin(), subscript.end()); |
797 | 0 | } |
798 | 0 | sigdata.scriptSig = PushAll(result); |
799 | | |
800 | | // Test solution |
801 | 0 | sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker()); |
802 | 0 | return sigdata.complete; |
803 | 0 | } |
804 | | |
805 | | namespace { |
806 | | class SignatureExtractorChecker final : public DeferringSignatureChecker |
807 | | { |
808 | | private: |
809 | | SignatureData& sigdata; |
810 | | |
811 | | public: |
812 | 0 | SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {} |
813 | | |
814 | | bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override |
815 | 0 | { |
816 | 0 | if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) { |
817 | 0 | CPubKey pubkey(vchPubKey); |
818 | 0 | sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig)); |
819 | 0 | return true; |
820 | 0 | } |
821 | 0 | return false; |
822 | 0 | } |
823 | | }; |
824 | | |
825 | | struct Stacks |
826 | | { |
827 | | std::vector<valtype> script; |
828 | | std::vector<valtype> witness; |
829 | | |
830 | | Stacks() = delete; |
831 | | Stacks(const Stacks&) = delete; |
832 | 0 | explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) { |
833 | 0 | EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE); |
834 | 0 | } |
835 | | }; |
836 | | } |
837 | | |
838 | | // Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead |
839 | | SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout) |
840 | 0 | { |
841 | 0 | SignatureData data; |
842 | 0 | assert(tx.vin.size() > nIn); |
843 | 0 | data.scriptSig = tx.vin[nIn].scriptSig; |
844 | 0 | data.scriptWitness = tx.vin[nIn].scriptWitness; |
845 | 0 | Stacks stack(data); |
846 | | |
847 | | // Get signatures |
848 | 0 | MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue, MissingDataBehavior::FAIL); |
849 | 0 | SignatureExtractorChecker extractor_checker(data, tx_checker); |
850 | 0 | if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) { |
851 | 0 | data.complete = true; |
852 | 0 | return data; |
853 | 0 | } |
854 | | |
855 | | // Get scripts |
856 | 0 | std::vector<std::vector<unsigned char>> solutions; |
857 | 0 | TxoutType script_type = Solver(txout.scriptPubKey, solutions); |
858 | 0 | SigVersion sigversion = SigVersion::BASE; |
859 | 0 | CScript next_script = txout.scriptPubKey; |
860 | |
|
861 | 0 | if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) { |
862 | | // Get the redeemScript |
863 | 0 | CScript redeem_script(stack.script.back().begin(), stack.script.back().end()); |
864 | 0 | data.redeem_script = redeem_script; |
865 | 0 | next_script = std::move(redeem_script); |
866 | | |
867 | | // Get redeemScript type |
868 | 0 | script_type = Solver(next_script, solutions); |
869 | 0 | stack.script.pop_back(); |
870 | 0 | } |
871 | 0 | if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) { |
872 | | // Get the witnessScript |
873 | 0 | CScript witness_script(stack.witness.back().begin(), stack.witness.back().end()); |
874 | 0 | data.witness_script = witness_script; |
875 | 0 | next_script = std::move(witness_script); |
876 | | |
877 | | // Get witnessScript type |
878 | 0 | script_type = Solver(next_script, solutions); |
879 | 0 | stack.witness.pop_back(); |
880 | 0 | stack.script = std::move(stack.witness); |
881 | 0 | stack.witness.clear(); |
882 | 0 | sigversion = SigVersion::WITNESS_V0; |
883 | 0 | } |
884 | 0 | if (script_type == TxoutType::MULTISIG && !stack.script.empty()) { |
885 | | // Build a map of pubkey -> signature by matching sigs to pubkeys: |
886 | 0 | assert(solutions.size() > 1); |
887 | 0 | unsigned int num_pubkeys = solutions.size()-2; |
888 | 0 | unsigned int last_success_key = 0; |
889 | 0 | for (const valtype& sig : stack.script) { |
890 | 0 | for (unsigned int i = last_success_key; i < num_pubkeys; ++i) { |
891 | 0 | const valtype& pubkey = solutions[i+1]; |
892 | | // We either have a signature for this pubkey, or we have found a signature and it is valid |
893 | 0 | if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) { |
894 | 0 | last_success_key = i + 1; |
895 | 0 | break; |
896 | 0 | } |
897 | 0 | } |
898 | 0 | } |
899 | 0 | } |
900 | | |
901 | 0 | return data; |
902 | 0 | } |
903 | | |
904 | | void UpdateInput(CTxIn& input, const SignatureData& data) |
905 | 0 | { |
906 | 0 | input.scriptSig = data.scriptSig; |
907 | 0 | input.scriptWitness = data.scriptWitness; |
908 | 0 | } |
909 | | |
910 | | void SignatureData::MergeSignatureData(SignatureData sigdata) |
911 | 0 | { |
912 | 0 | if (complete) return; |
913 | 0 | if (sigdata.complete) { |
914 | 0 | *this = std::move(sigdata); |
915 | 0 | return; |
916 | 0 | } |
917 | 0 | if (redeem_script.empty() && !sigdata.redeem_script.empty()) { |
918 | 0 | redeem_script = sigdata.redeem_script; |
919 | 0 | } |
920 | 0 | if (witness_script.empty() && !sigdata.witness_script.empty()) { |
921 | 0 | witness_script = sigdata.witness_script; |
922 | 0 | } |
923 | 0 | signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end())); |
924 | 0 | } |
925 | | |
926 | | namespace { |
927 | | /** Dummy signature checker which accepts all signatures. */ |
928 | | class DummySignatureChecker final : public BaseSignatureChecker |
929 | | { |
930 | | public: |
931 | 0 | DummySignatureChecker() = default; |
932 | 0 | bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return sig.size() != 0; } |
933 | 0 | bool CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return sig.size() != 0; } |
934 | 0 | bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; } |
935 | 0 | bool CheckSequence(const CScriptNum& nSequence) const override { return true; } |
936 | | }; |
937 | | } |
938 | | |
939 | | const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker(); |
940 | | |
941 | | namespace { |
942 | | class DummySignatureCreator final : public BaseSignatureCreator { |
943 | | private: |
944 | | char m_r_len = 32; |
945 | | char m_s_len = 32; |
946 | | public: |
947 | 0 | DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {} |
948 | 0 | const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; } |
949 | | bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override |
950 | 0 | { |
951 | | // Create a dummy signature that is a valid DER-encoding |
952 | 0 | vchSig.assign(m_r_len + m_s_len + 7, '\000'); |
953 | 0 | vchSig[0] = 0x30; |
954 | 0 | vchSig[1] = m_r_len + m_s_len + 4; |
955 | 0 | vchSig[2] = 0x02; |
956 | 0 | vchSig[3] = m_r_len; |
957 | 0 | vchSig[4] = 0x01; |
958 | 0 | vchSig[4 + m_r_len] = 0x02; |
959 | 0 | vchSig[5 + m_r_len] = m_s_len; |
960 | 0 | vchSig[6 + m_r_len] = 0x01; |
961 | 0 | vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL; |
962 | 0 | return true; |
963 | 0 | } |
964 | | bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override |
965 | 0 | { |
966 | 0 | sig.assign(64, '\000'); |
967 | 0 | return true; |
968 | 0 | } |
969 | | std::vector<uint8_t> CreateMuSig2Nonce(const SigningProvider& provider, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion, const SignatureData& sigdata) const override |
970 | 0 | { |
971 | 0 | std::vector<uint8_t> out; |
972 | 0 | out.assign(MUSIG2_PUBNONCE_SIZE, '\000'); |
973 | 0 | return out; |
974 | 0 | } |
975 | | bool CreateMuSig2PartialSig(const SigningProvider& provider, uint256& partial_sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const override |
976 | 0 | { |
977 | 0 | partial_sig = uint256::ONE; |
978 | 0 | return true; |
979 | 0 | } |
980 | | bool CreateMuSig2AggregateSig(const std::vector<CPubKey>& participants, std::vector<uint8_t>& sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const override |
981 | 0 | { |
982 | 0 | sig.assign(64, '\000'); |
983 | 0 | return true; |
984 | 0 | } |
985 | | }; |
986 | | |
987 | | } |
988 | | |
989 | | const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32); |
990 | | const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32); |
991 | | |
992 | | bool IsSegWitOutput(const SigningProvider& provider, const CScript& script) |
993 | 0 | { |
994 | 0 | int version; |
995 | 0 | valtype program; |
996 | 0 | if (script.IsWitnessProgram(version, program)) return true; |
997 | 0 | if (script.IsPayToScriptHash()) { |
998 | 0 | std::vector<valtype> solutions; |
999 | 0 | auto whichtype = Solver(script, solutions); |
1000 | 0 | if (whichtype == TxoutType::SCRIPTHASH) { |
1001 | 0 | auto h160 = uint160(solutions[0]); |
1002 | 0 | CScript subscript; |
1003 | 0 | if (provider.GetCScript(CScriptID{h160}, subscript)) { |
1004 | 0 | if (subscript.IsWitnessProgram(version, program)) return true; |
1005 | 0 | } |
1006 | 0 | } |
1007 | 0 | } |
1008 | 0 | return false; |
1009 | 0 | } |
1010 | | |
1011 | | bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, bilingual_str>& input_errors) |
1012 | 0 | { |
1013 | 0 | bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); |
1014 | | |
1015 | | // Use CTransaction for the constant parts of the |
1016 | | // transaction to avoid rehashing. |
1017 | 0 | const CTransaction txConst(mtx); |
1018 | |
|
1019 | 0 | PrecomputedTransactionData txdata; |
1020 | 0 | std::vector<CTxOut> spent_outputs; |
1021 | 0 | for (unsigned int i = 0; i < mtx.vin.size(); ++i) { |
1022 | 0 | CTxIn& txin = mtx.vin[i]; |
1023 | 0 | auto coin = coins.find(txin.prevout); |
1024 | 0 | if (coin == coins.end() || coin->second.IsSpent()) { |
1025 | 0 | txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true); |
1026 | 0 | break; |
1027 | 0 | } else { |
1028 | 0 | spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey); |
1029 | 0 | } |
1030 | 0 | } |
1031 | 0 | if (spent_outputs.size() == mtx.vin.size()) { |
1032 | 0 | txdata.Init(txConst, std::move(spent_outputs), true); |
1033 | 0 | } |
1034 | | |
1035 | | // Sign what we can: |
1036 | 0 | for (unsigned int i = 0; i < mtx.vin.size(); ++i) { |
1037 | 0 | CTxIn& txin = mtx.vin[i]; |
1038 | 0 | auto coin = coins.find(txin.prevout); |
1039 | 0 | if (coin == coins.end() || coin->second.IsSpent()) { |
1040 | 0 | input_errors[i] = _("Input not found or already spent"); |
1041 | 0 | continue; |
1042 | 0 | } |
1043 | 0 | const CScript& prevPubKey = coin->second.out.scriptPubKey; |
1044 | 0 | const CAmount& amount = coin->second.out.nValue; |
1045 | |
|
1046 | 0 | SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out); |
1047 | | // Only sign SIGHASH_SINGLE if there's a corresponding output: |
1048 | 0 | if (!fHashSingle || (i < mtx.vout.size())) { |
1049 | 0 | ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata); |
1050 | 0 | } |
1051 | |
|
1052 | 0 | UpdateInput(txin, sigdata); |
1053 | | |
1054 | | // amount must be specified for valid segwit signature |
1055 | 0 | if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) { |
1056 | 0 | input_errors[i] = _("Missing amount"); |
1057 | 0 | continue; |
1058 | 0 | } |
1059 | | |
1060 | 0 | ScriptError serror = SCRIPT_ERR_OK; |
1061 | 0 | if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) { |
1062 | 0 | if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) { |
1063 | | // Unable to sign input and verification failed (possible attempt to partially sign). |
1064 | 0 | input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)"); |
1065 | 0 | } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) { |
1066 | | // Verification failed (possibly due to insufficient signatures). |
1067 | 0 | input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)"); |
1068 | 0 | } else { |
1069 | 0 | input_errors[i] = Untranslated(ScriptErrorString(serror)); |
1070 | 0 | } |
1071 | 0 | } else { |
1072 | | // If this input succeeds, make sure there is no error set for it |
1073 | 0 | input_errors.erase(i); |
1074 | 0 | } |
1075 | 0 | } |
1076 | 0 | return input_errors.empty(); |
1077 | 0 | } |