Bitcoin Core 22.99.0
P2P Digital Currency
sign.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <script/sign.h>
7
8#include <consensus/amount.h>
9#include <key.h>
10#include <policy/policy.h>
13#include <script/standard.h>
14#include <uint256.h>
15#include <util/translation.h>
16#include <util/vector.h>
17
18typedef std::vector<unsigned char> valtype;
19
20MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn)
21 : txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn, MissingDataBehavior::FAIL),
22 m_txdata(nullptr)
23{
24}
25
26MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData* txdata, int nHashTypeIn)
27 : txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn),
28 checker(txdata ? MutableTransactionSignatureChecker(txTo, nIn, amount, *txdata, MissingDataBehavior::FAIL) :
30 m_txdata(txdata)
31{
32}
33
34bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
35{
36 assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
37
38 CKey key;
39 if (!provider.GetKey(address, key))
40 return false;
41
42 // Signing with uncompressed keys is disabled in witness scripts
43 if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
44 return false;
45
46 // Signing without known amount does not work in witness scripts.
47 if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false;
48
49 // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead.
50 const int hashtype = nHashType == SIGHASH_DEFAULT ? SIGHASH_ALL : nHashType;
51
52 uint256 hash = SignatureHash(scriptCode, *txTo, nIn, hashtype, amount, sigversion, m_txdata);
53 if (!key.Sign(hash, vchSig))
54 return false;
55 vchSig.push_back((unsigned char)hashtype);
56 return true;
57}
58
59bool MutableTransactionSignatureCreator::CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion) const
60{
61 assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
62
63 CKey key;
64 if (!provider.GetKeyByXOnly(pubkey, key)) return false;
65
66 // BIP341/BIP342 signing needs lots of precomputed transaction data. While some
67 // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset
68 // of data present, for now, only support signing when everything is provided.
70
71 ScriptExecutionData execdata;
72 execdata.m_annex_init = true;
73 execdata.m_annex_present = false; // Only support annex-less signing for now.
74 if (sigversion == SigVersion::TAPSCRIPT) {
75 execdata.m_codeseparator_pos_init = true;
76 execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
77 if (!leaf_hash) return false; // BIP342 signing needs leaf hash.
78 execdata.m_tapleaf_hash_init = true;
79 execdata.m_tapleaf_hash = *leaf_hash;
80 }
81 uint256 hash;
82 if (!SignatureHashSchnorr(hash, execdata, *txTo, nIn, nHashType, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return false;
83 sig.resize(64);
84 if (!key.SignSchnorr(hash, sig, merkle_root, nullptr)) return false;
85 if (nHashType) sig.push_back(nHashType);
86 return true;
87}
88
89static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)
90{
91 if (provider.GetCScript(scriptid, script)) {
92 return true;
93 }
94 // Look for scripts in SignatureData
95 if (CScriptID(sigdata.redeem_script) == scriptid) {
96 script = sigdata.redeem_script;
97 return true;
98 } else if (CScriptID(sigdata.witness_script) == scriptid) {
99 script = sigdata.witness_script;
100 return true;
101 }
102 return false;
103}
104
105static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
106{
107 // Look for pubkey in all partial sigs
108 const auto it = sigdata.signatures.find(address);
109 if (it != sigdata.signatures.end()) {
110 pubkey = it->second.first;
111 return true;
112 }
113 // Look for pubkey in pubkey list
114 const auto& pk_it = sigdata.misc_pubkeys.find(address);
115 if (pk_it != sigdata.misc_pubkeys.end()) {
116 pubkey = pk_it->second.first;
117 return true;
118 }
119 // Query the underlying provider
120 return provider.GetPubKey(address, pubkey);
121}
122
123static bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const CPubKey& pubkey, const CScript& scriptcode, SigVersion sigversion)
124{
125 CKeyID keyid = pubkey.GetID();
126 const auto it = sigdata.signatures.find(keyid);
127 if (it != sigdata.signatures.end()) {
128 sig_out = it->second.second;
129 return true;
130 }
131 KeyOriginInfo info;
132 if (provider.GetKeyOrigin(keyid, info)) {
133 sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
134 }
135 if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
136 auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));
137 assert(i.second);
138 return true;
139 }
140 // Could not make signature or signature not found, add keyid to missing
141 sigdata.missing_sigs.push_back(keyid);
142 return false;
143}
144
145static 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)
146{
147 auto lookup_key = std::make_pair(pubkey, leaf_hash);
148 auto it = sigdata.taproot_script_sigs.find(lookup_key);
149 if (it != sigdata.taproot_script_sigs.end()) {
150 sig_out = it->second;
151 }
152 if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
153 sigdata.taproot_script_sigs[lookup_key] = sig_out;
154 return true;
155 }
156 return false;
157}
158
159static bool SignTaprootScript(const SigningProvider& provider, const BaseSignatureCreator& creator, SignatureData& sigdata, int leaf_version, const CScript& script, std::vector<valtype>& result)
160{
161 // Only BIP342 tapscript signing is supported for now.
162 if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
164
165 uint256 leaf_hash = (CHashWriter(HASHER_TAPLEAF) << uint8_t(leaf_version) << script).GetSHA256();
166
167 // <xonly pubkey> OP_CHECKSIG
168 if (script.size() == 34 && script[33] == OP_CHECKSIG && script[0] == 0x20) {
169 XOnlyPubKey pubkey(MakeSpan(script).subspan(1, 32));
170 std::vector<unsigned char> sig;
171 if (CreateTaprootScriptSig(creator, sigdata, provider, sig, pubkey, leaf_hash, sigversion)) {
172 result = Vector(std::move(sig));
173 return true;
174 }
175 }
176
177 return false;
178}
179
180static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
181{
182 TaprootSpendData spenddata;
183
184 // Gather information about this output.
185 if (provider.GetTaprootSpendData(output, spenddata)) {
186 sigdata.tr_spenddata.Merge(spenddata);
187 }
188
189 // Try key path spending.
190 {
191 std::vector<unsigned char> sig;
192 if (sigdata.taproot_key_path_sig.size() == 0) {
193 if (creator.CreateSchnorrSig(provider, sig, spenddata.internal_key, nullptr, &spenddata.merkle_root, SigVersion::TAPROOT)) {
194 sigdata.taproot_key_path_sig = sig;
195 }
196 }
197 if (sigdata.taproot_key_path_sig.size()) {
198 result = Vector(sigdata.taproot_key_path_sig);
199 return true;
200 }
201 }
202
203 // Try script path spending.
204 std::vector<std::vector<unsigned char>> smallest_result_stack;
205 for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
206 const auto& [script, leaf_ver] = key;
207 std::vector<std::vector<unsigned char>> result_stack;
208 if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
209 result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
210 result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
211 if (smallest_result_stack.size() == 0 ||
212 GetSerializeSize(result_stack, PROTOCOL_VERSION) < GetSerializeSize(smallest_result_stack, PROTOCOL_VERSION)) {
213 smallest_result_stack = std::move(result_stack);
214 }
215 }
216 }
217 if (smallest_result_stack.size() != 0) {
218 result = std::move(smallest_result_stack);
219 return true;
220 }
221
222 return false;
223}
224
231static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,
232 std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)
233{
234 CScript scriptRet;
235 uint160 h160;
236 ret.clear();
237 std::vector<unsigned char> sig;
238
239 std::vector<valtype> vSolutions;
240 whichTypeRet = Solver(scriptPubKey, vSolutions);
241
242 switch (whichTypeRet) {
246 return false;
248 if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
249 ret.push_back(std::move(sig));
250 return true;
252 CKeyID keyID = CKeyID(uint160(vSolutions[0]));
253 CPubKey pubkey;
254 if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
255 // Pubkey could not be found, add to missing
256 sigdata.missing_pubkeys.push_back(keyID);
257 return false;
258 }
259 if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;
260 ret.push_back(std::move(sig));
261 ret.push_back(ToByteVector(pubkey));
262 return true;
263 }
265 h160 = uint160(vSolutions[0]);
266 if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
267 ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
268 return true;
269 }
270 // Could not find redeemScript, add to missing
271 sigdata.missing_redeem_script = h160;
272 return false;
273
274 case TxoutType::MULTISIG: {
275 size_t required = vSolutions.front()[0];
276 ret.push_back(valtype()); // workaround CHECKMULTISIG bug
277 for (size_t i = 1; i < vSolutions.size() - 1; ++i) {
278 CPubKey pubkey = CPubKey(vSolutions[i]);
279 // We need to always call CreateSig in order to fill sigdata with all
280 // possible signatures that we can create. This will allow further PSBT
281 // processing to work as it needs all possible signature and pubkey pairs
282 if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
283 if (ret.size() < required + 1) {
284 ret.push_back(std::move(sig));
285 }
286 }
287 }
288 bool ok = ret.size() == required + 1;
289 for (size_t i = 0; i + ret.size() < required + 1; ++i) {
290 ret.push_back(valtype());
291 }
292 return ok;
293 }
295 ret.push_back(vSolutions[0]);
296 return true;
297
299 CRIPEMD160().Write(vSolutions[0].data(), vSolutions[0].size()).Finalize(h160.begin());
300 if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
301 ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
302 return true;
303 }
304 // Could not find witnessScript, add to missing
305 sigdata.missing_witness_script = uint256(vSolutions[0]);
306 return false;
307
309 return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
310 } // no default case, so the compiler can warn about missing cases
311 assert(false);
312}
313
314static CScript PushAll(const std::vector<valtype>& values)
315{
316 CScript result;
317 for (const valtype& v : values) {
318 if (v.size() == 0) {
319 result << OP_0;
320 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
321 result << CScript::EncodeOP_N(v[0]);
322 } else if (v.size() == 1 && v[0] == 0x81) {
323 result << OP_1NEGATE;
324 } else {
325 result << v;
326 }
327 }
328 return result;
329}
330
331bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
332{
333 if (sigdata.complete) return true;
334
335 std::vector<valtype> result;
336 TxoutType whichType;
337 bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
338 bool P2SH = false;
339 CScript subscript;
340
341 if (solved && whichType == TxoutType::SCRIPTHASH)
342 {
343 // Solver returns the subscript that needs to be evaluated;
344 // the final scriptSig is the signatures from that
345 // and then the serialized subscript:
346 subscript = CScript(result[0].begin(), result[0].end());
347 sigdata.redeem_script = subscript;
348 solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
349 P2SH = true;
350 }
351
352 if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
353 {
354 CScript witnessscript;
355 witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
356 TxoutType subType;
357 solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
358 sigdata.scriptWitness.stack = result;
359 sigdata.witness = true;
360 result.clear();
361 }
362 else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
363 {
364 CScript witnessscript(result[0].begin(), result[0].end());
365 sigdata.witness_script = witnessscript;
366 TxoutType subType;
367 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;
368 result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));
369 sigdata.scriptWitness.stack = result;
370 sigdata.witness = true;
371 result.clear();
372 } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
373 sigdata.witness = true;
374 if (solved) {
375 sigdata.scriptWitness.stack = std::move(result);
376 }
377 result.clear();
378 } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
379 sigdata.witness = true;
380 }
381
382 if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
383 if (P2SH) {
384 result.push_back(std::vector<unsigned char>(subscript.begin(), subscript.end()));
385 }
386 sigdata.scriptSig = PushAll(result);
387
388 // Test solution
389 sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
390 return sigdata.complete;
391}
392
393namespace {
394class SignatureExtractorChecker final : public DeferringSignatureChecker
395{
396private:
397 SignatureData& sigdata;
398
399public:
400 SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
401
402 bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
403 {
404 if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
405 CPubKey pubkey(vchPubKey);
406 sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
407 return true;
408 }
409 return false;
410 }
411};
412
413struct Stacks
414{
415 std::vector<valtype> script;
416 std::vector<valtype> witness;
417
418 Stacks() = delete;
419 Stacks(const Stacks&) = delete;
420 explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
422 }
423};
424}
425
426// Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
427SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
428{
429 SignatureData data;
430 assert(tx.vin.size() > nIn);
431 data.scriptSig = tx.vin[nIn].scriptSig;
432 data.scriptWitness = tx.vin[nIn].scriptWitness;
433 Stacks stack(data);
434
435 // Get signatures
437 SignatureExtractorChecker extractor_checker(data, tx_checker);
438 if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
439 data.complete = true;
440 return data;
441 }
442
443 // Get scripts
444 std::vector<std::vector<unsigned char>> solutions;
445 TxoutType script_type = Solver(txout.scriptPubKey, solutions);
446 SigVersion sigversion = SigVersion::BASE;
447 CScript next_script = txout.scriptPubKey;
448
449 if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
450 // Get the redeemScript
451 CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
452 data.redeem_script = redeem_script;
453 next_script = std::move(redeem_script);
454
455 // Get redeemScript type
456 script_type = Solver(next_script, solutions);
457 stack.script.pop_back();
458 }
459 if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
460 // Get the witnessScript
461 CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
462 data.witness_script = witness_script;
463 next_script = std::move(witness_script);
464
465 // Get witnessScript type
466 script_type = Solver(next_script, solutions);
467 stack.witness.pop_back();
468 stack.script = std::move(stack.witness);
469 stack.witness.clear();
470 sigversion = SigVersion::WITNESS_V0;
471 }
472 if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
473 // Build a map of pubkey -> signature by matching sigs to pubkeys:
474 assert(solutions.size() > 1);
475 unsigned int num_pubkeys = solutions.size()-2;
476 unsigned int last_success_key = 0;
477 for (const valtype& sig : stack.script) {
478 for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
479 const valtype& pubkey = solutions[i+1];
480 // We either have a signature for this pubkey, or we have found a signature and it is valid
481 if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
482 last_success_key = i + 1;
483 break;
484 }
485 }
486 }
487 }
488
489 return data;
490}
491
492void UpdateInput(CTxIn& input, const SignatureData& data)
493{
494 input.scriptSig = data.scriptSig;
495 input.scriptWitness = data.scriptWitness;
496}
497
499{
500 if (complete) return;
501 if (sigdata.complete) {
502 *this = std::move(sigdata);
503 return;
504 }
505 if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
507 }
508 if (witness_script.empty() && !sigdata.witness_script.empty()) {
510 }
511 signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
512}
513
514bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)
515{
516 assert(nIn < txTo.vin.size());
517
518 MutableTransactionSignatureCreator creator(&txTo, nIn, amount, nHashType);
519
520 SignatureData sigdata;
521 bool ret = ProduceSignature(provider, creator, fromPubKey, sigdata);
522 UpdateInput(txTo.vin.at(nIn), sigdata);
523 return ret;
524}
525
526bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
527{
528 assert(nIn < txTo.vin.size());
529 const CTxIn& txin = txTo.vin[nIn];
530 assert(txin.prevout.n < txFrom.vout.size());
531 const CTxOut& txout = txFrom.vout[txin.prevout.n];
532
533 return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
534}
535
536namespace {
538class DummySignatureChecker final : public BaseSignatureChecker
539{
540public:
541 DummySignatureChecker() {}
542 bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return true; }
543 bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, const ScriptExecutionData& execdata, ScriptError* serror) const override { return true; }
544};
545const DummySignatureChecker DUMMY_CHECKER;
546
547class DummySignatureCreator final : public BaseSignatureCreator {
548private:
549 char m_r_len = 32;
550 char m_s_len = 32;
551public:
552 DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
553 const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
554 bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
555 {
556 // Create a dummy signature that is a valid DER-encoding
557 vchSig.assign(m_r_len + m_s_len + 7, '\000');
558 vchSig[0] = 0x30;
559 vchSig[1] = m_r_len + m_s_len + 4;
560 vchSig[2] = 0x02;
561 vchSig[3] = m_r_len;
562 vchSig[4] = 0x01;
563 vchSig[4 + m_r_len] = 0x02;
564 vchSig[5 + m_r_len] = m_s_len;
565 vchSig[6 + m_r_len] = 0x01;
566 vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
567 return true;
568 }
569 bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
570 {
571 sig.assign(64, '\000');
572 return true;
573 }
574};
575
576}
577
578const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
579const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
580
581bool IsSolvable(const SigningProvider& provider, const CScript& script)
582{
583 // This check is to make sure that the script we created can actually be solved for and signed by us
584 // if we were to have the private keys. This is just to make sure that the script is valid and that,
585 // if found in a transaction, we would still accept and relay that transaction. In particular,
586 // it will reject witness outputs that require signing with an uncompressed public key.
587 SignatureData sigs;
588 // Make sure that STANDARD_SCRIPT_VERIFY_FLAGS includes SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, the most
589 // important property this function is designed to test for.
590 static_assert(STANDARD_SCRIPT_VERIFY_FLAGS & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, "IsSolvable requires standard script flags to include WITNESS_PUBKEYTYPE");
591 if (ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, script, sigs)) {
592 // VerifyScript check is just defensive, and should never fail.
593 bool verified = VerifyScript(sigs.scriptSig, script, &sigs.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, DUMMY_CHECKER);
594 assert(verified);
595 return true;
596 }
597 return false;
598}
599
600bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
601{
602 int version;
603 valtype program;
604 if (script.IsWitnessProgram(version, program)) return true;
605 if (script.IsPayToScriptHash()) {
606 std::vector<valtype> solutions;
607 auto whichtype = Solver(script, solutions);
608 if (whichtype == TxoutType::SCRIPTHASH) {
609 auto h160 = uint160(solutions[0]);
610 CScript subscript;
611 if (provider.GetCScript(CScriptID{h160}, subscript)) {
612 if (subscript.IsWitnessProgram(version, program)) return true;
613 }
614 }
615 }
616 return false;
617}
618
619bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, bilingual_str>& input_errors)
620{
621 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
622
623 // Use CTransaction for the constant parts of the
624 // transaction to avoid rehashing.
625 const CTransaction txConst(mtx);
626
628 std::vector<CTxOut> spent_outputs;
629 for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
630 CTxIn& txin = mtx.vin[i];
631 auto coin = coins.find(txin.prevout);
632 if (coin == coins.end() || coin->second.IsSpent()) {
633 txdata.Init(txConst, /* spent_outputs */ {}, /* force */ true);
634 break;
635 } else {
636 spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
637 }
638 }
639 if (spent_outputs.size() == mtx.vin.size()) {
640 txdata.Init(txConst, std::move(spent_outputs), true);
641 }
642
643 // Sign what we can:
644 for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
645 CTxIn& txin = mtx.vin[i];
646 auto coin = coins.find(txin.prevout);
647 if (coin == coins.end() || coin->second.IsSpent()) {
648 input_errors[i] = _("Input not found or already spent");
649 continue;
650 }
651 const CScript& prevPubKey = coin->second.out.scriptPubKey;
652 const CAmount& amount = coin->second.out.nValue;
653
654 SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
655 // Only sign SIGHASH_SINGLE if there's a corresponding output:
656 if (!fHashSingle || (i < mtx.vout.size())) {
657 ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata);
658 }
659
660 UpdateInput(txin, sigdata);
661
662 // amount must be specified for valid segwit signature
663 if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
664 input_errors[i] = _("Missing amount");
665 continue;
666 }
667
668 ScriptError serror = SCRIPT_ERR_OK;
669 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
671 // Unable to sign input and verification failed (possible attempt to partially sign).
672 input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
673 } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
674 // Verification failed (possibly due to insufficient signatures).
675 input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
676 } else {
677 input_errors[i] = Untranslated(ScriptErrorString(serror));
678 }
679 } else {
680 // If this input succeeds, make sure there is no error set for it
681 input_errors.erase(i);
682 }
683 }
684 return input_errors.empty();
685}
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, const ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
Definition: interpreter.h:246
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:241
Interface for signature creators.
Definition: sign.h:28
virtual const BaseSignatureChecker & Checker() const =0
virtual bool CreateSchnorrSig(const SigningProvider &provider, std::vector< unsigned char > &sig, const XOnlyPubKey &pubkey, const uint256 *leaf_hash, const uint256 *merkle_root, SigVersion sigversion) const =0
virtual bool CreateSig(const SigningProvider &provider, std::vector< unsigned char > &vchSig, const CKeyID &keyid, const CScript &scriptCode, SigVersion sigversion) const =0
Create a singular (non-script) signature.
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:101
An encapsulated private key.
Definition: key.h:27
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig, bool grind=true, uint32_t test_case=0) const
Create a DER-serialized signature.
Definition: key.cpp:213
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:96
bool SignSchnorr(const uint256 &hash, Span< unsigned char > sig, const uint256 *merkle_root=nullptr, const uint256 *aux=nullptr) const
Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this, optionally tweaked b...
Definition: key.cpp:264
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
uint32_t n
Definition: transaction.h:30
An encapsulated public key.
Definition: pubkey.h:33
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
A hasher class for RIPEMD-160.
Definition: ripemd160.h:13
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
bool IsPayToScriptHash() const
Definition: script.cpp:201
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:220
static opcodetype EncodeOP_N(int n)
Definition: script.h:505
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:26
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const std::vector< CTxOut > vout
Definition: transaction.h:271
An input of a transaction.
Definition: transaction.h:66
CScript scriptSig
Definition: transaction.h:69
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:71
COutPoint prevout
Definition: transaction.h:68
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
CAmount nValue
Definition: transaction.h:131
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
Definition: interpreter.h:310
A signature creator for transactions.
Definition: sign.h:39
bool CreateSchnorrSig(const SigningProvider &provider, std::vector< unsigned char > &sig, const XOnlyPubKey &pubkey, const uint256 *leaf_hash, const uint256 *merkle_root, SigVersion sigversion) const override
Definition: sign.cpp:59
MutableTransactionSignatureCreator(const CMutableTransaction *txToIn, unsigned int nInIn, const CAmount &amountIn, int nHashTypeIn)
Definition: sign.cpp:20
const CMutableTransaction * txTo
Definition: sign.h:40
bool CreateSig(const SigningProvider &provider, std::vector< unsigned char > &vchSig, const CKeyID &keyid, const CScript &scriptCode, SigVersion sigversion) const override
Create a singular (non-script) signature.
Definition: sign.cpp:34
const PrecomputedTransactionData * m_txdata
Definition: sign.h:45
An interface to be implemented by keystores that support signing.
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
virtual bool GetTaprootSpendData(const XOnlyPubKey &output_key, TaprootSpendData &spenddata) const
bool GetKeyByXOnly(const XOnlyPubKey &pubkey, CKey &key) const
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
virtual bool GetKey(const CKeyID &address, CKey &key) const
virtual bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:93
unsigned char * begin()
Definition: uint256.h:58
bool empty() const
Definition: prevector.h:286
size_type size() const
Definition: prevector.h:282
iterator begin()
Definition: prevector.h:290
iterator end()
Definition: prevector.h:292
160-bit opaque blob.
Definition: uint256.h:113
256-bit opaque blob.
Definition: uint256.h:124
bool SignatureHashSchnorr(uint256 &hash_out, const ScriptExecutionData &execdata, const T &tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData &cache, MissingDataBehavior mdb)
const CHashWriter HASHER_TAPLEAF
Hasher with tag "TapLeaf" pre-fed to it.
std::vector< unsigned char > valtype
Definition: interpreter.cpp:15
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
SigVersion
Definition: interpreter.h:188
@ TAPROOT
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341.
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
@ TAPSCRIPT
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, script path spending, leaf version 0xc0; see...
@ WITNESS_V0
Witness v0 (P2WPKH and P2WSH); see BIP 141.
@ SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
Definition: interpreter.h:123
@ SCRIPT_VERIFY_STRICTENC
Definition: interpreter.h:51
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:226
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:32
@ SIGHASH_ALL
Definition: interpreter.h:27
@ SIGHASH_SINGLE
Definition: interpreter.h:29
MissingDataBehavior
Enum to specify what *TransactionSignatureChecker's behavior should be when dealing with missing tran...
Definition: interpreter.h:268
@ FAIL
Just act as if the signature was invalid.
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:60
@ OP_1NEGATE
Definition: script.h:74
@ OP_CHECKSIG
Definition: script.h:183
@ OP_DUP
Definition: script.h:118
@ OP_HASH160
Definition: script.h:180
@ OP_0
Definition: script.h:69
@ OP_EQUALVERIFY
Definition: script.h:140
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:60
std::string ScriptErrorString(const ScriptError serror)
enum ScriptError_t ScriptError
@ SCRIPT_ERR_INVALID_STACK_OPERATION
Definition: script_error.h:36
@ SCRIPT_ERR_SIG_NULLFAIL
Definition: script_error.h:54
@ SCRIPT_ERR_OK
Definition: script_error.h:13
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
static bool SignStep(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &scriptPubKey, std::vector< valtype > &ret, TxoutType &whichTypeRet, SigVersion sigversion, SignatureData &sigdata)
Sign scriptPubKey using signature made with creator.
Definition: sign.cpp:231
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:331
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)
Definition: sign.cpp:145
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:492
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
Definition: sign.cpp:600
static bool SignTaprootScript(const SigningProvider &provider, const BaseSignatureCreator &creator, SignatureData &sigdata, int leaf_version, const CScript &script, std::vector< valtype > &result)
Definition: sign.cpp:159
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)
Definition: sign.cpp:123
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:581
std::vector< unsigned char > valtype
Definition: sign.cpp:18
static bool SignTaproot(const SigningProvider &provider, const BaseSignatureCreator &creator, const WitnessV1Taproot &output, SignatureData &sigdata, std::vector< valtype > &result)
Definition: sign.cpp:180
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType)
Produce a script signature for a transaction.
Definition: sign.cpp:514
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:579
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:105
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:427
bool SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, int nHashType, std::map< int, bilingual_str > &input_errors)
Sign the CMutableTransaction.
Definition: sign.cpp:619
static CScript PushAll(const std::vector< valtype > &values)
Definition: sign.cpp:314
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:578
static bool GetCScript(const SigningProvider &provider, const SignatureData &sigdata, const CScriptID &scriptid, CScript &script)
Definition: sign.cpp:89
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:60
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:222
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:144
TxoutType
Definition: standard.h:59
@ WITNESS_V1_TAPROOT
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ WITNESS_V0_SCRIPTHASH
@ NULL_DATA
unspendable OP_RETURN script that carries data
@ WITNESS_V0_KEYHASH
A mutable version of CTransaction.
Definition: transaction.h:345
std::vector< CTxOut > vout
Definition: transaction.h:347
std::vector< CTxIn > vin
Definition: transaction.h:346
std::vector< std::vector< unsigned char > > stack
Definition: script.h:561
bool IsNull() const
Definition: script.h:566
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
bool m_bip341_taproot_ready
Whether the 5 fields above are initialized.
Definition: interpreter.h:160
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:169
uint256 m_tapleaf_hash
The tapleaf hash.
Definition: interpreter.h:200
bool m_annex_present
Whether an annex is present.
Definition: interpreter.h:210
bool m_annex_init
Whether m_annex_present and (when needed) m_annex_hash are initialized.
Definition: interpreter.h:208
bool m_codeseparator_pos_init
Whether m_codeseparator_pos is initialized.
Definition: interpreter.h:203
bool m_tapleaf_hash_init
Whether m_tapleaf_hash is initialized.
Definition: interpreter.h:198
uint32_t m_codeseparator_pos
Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed).
Definition: interpreter.h:205
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:79
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:78
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:498
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:73
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:72
bool witness
Stores whether the input this SigData corresponds to is a witness input.
Definition: sign.h:67
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:74
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format.
Definition: sign.h:68
std::vector< unsigned char > taproot_key_path_sig
Definition: sign.h:75
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > taproot_script_sigs
Schnorr signature for key path spending.
Definition: sign.h:76
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:69
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:80
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:77
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:70
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition: sign.h:71
bool complete
Stores whether the scriptSig and scriptWitness are complete.
Definition: sign.h:66
uint256 merkle_root
The Merkle root of the script tree (0 if no scripts).
Definition: standard.h:212
std::map< std::pair< CScript, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > scripts
Map from (script, leaf_version) to (sets of) control blocks.
Definition: standard.h:219
void Merge(TaprootSpendData other)
Merge other TaprootSpendData (for the same scriptPubKey) into this.
Definition: standard.cpp:358
XOnlyPubKey internal_key
The BIP341 internal key.
Definition: standard.h:210
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
assert(!tx.IsCoinBase())
std::vector< typename std::common_type< Args... >::type > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition: vector.h:20
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12