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