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