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