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