Bitcoin Core  27.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-2022 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/miniscript.h>
14 #include <script/script.h>
15 #include <script/signingprovider.h>
16 #include <script/solver.h>
17 #include <uint256.h>
18 #include <util/translation.h>
19 #include <util/vector.h>
20 
21 typedef std::vector<unsigned char> valtype;
22 
23 MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, int hash_type)
24  : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount}, checker{&m_txto, nIn, amount, MissingDataBehavior::FAIL},
25  m_txdata(nullptr)
26 {
27 }
28 
29 MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const PrecomputedTransactionData* txdata, int hash_type)
30  : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount},
31  checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} :
33  m_txdata(txdata)
34 {
35 }
36 
37 bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
38 {
39  assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
40 
41  CKey key;
42  if (!provider.GetKey(address, key))
43  return false;
44 
45  // Signing with uncompressed keys is disabled in witness scripts
46  if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
47  return false;
48 
49  // Signing without known amount does not work in witness scripts.
50  if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false;
51 
52  // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead.
53  const int hashtype = nHashType == SIGHASH_DEFAULT ? SIGHASH_ALL : nHashType;
54 
55  uint256 hash = SignatureHash(scriptCode, m_txto, nIn, hashtype, amount, sigversion, m_txdata);
56  if (!key.Sign(hash, vchSig))
57  return false;
58  vchSig.push_back((unsigned char)hashtype);
59  return true;
60 }
61 
62 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
63 {
64  assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
65 
66  CKey key;
67  if (!provider.GetKeyByXOnly(pubkey, key)) return false;
68 
69  // BIP341/BIP342 signing needs lots of precomputed transaction data. While some
70  // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset
71  // of data present, for now, only support signing when everything is provided.
73 
74  ScriptExecutionData execdata;
75  execdata.m_annex_init = true;
76  execdata.m_annex_present = false; // Only support annex-less signing for now.
77  if (sigversion == SigVersion::TAPSCRIPT) {
78  execdata.m_codeseparator_pos_init = true;
79  execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
80  if (!leaf_hash) return false; // BIP342 signing needs leaf hash.
81  execdata.m_tapleaf_hash_init = true;
82  execdata.m_tapleaf_hash = *leaf_hash;
83  }
84  uint256 hash;
85  if (!SignatureHashSchnorr(hash, execdata, m_txto, nIn, nHashType, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return false;
86  sig.resize(64);
87  // Use uint256{} as aux_rnd for now.
88  if (!key.SignSchnorr(hash, sig, merkle_root, {})) return false;
89  if (nHashType) sig.push_back(nHashType);
90  return true;
91 }
92 
93 static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)
94 {
95  if (provider.GetCScript(scriptid, script)) {
96  return true;
97  }
98  // Look for scripts in SignatureData
99  if (CScriptID(sigdata.redeem_script) == scriptid) {
100  script = sigdata.redeem_script;
101  return true;
102  } else if (CScriptID(sigdata.witness_script) == scriptid) {
103  script = sigdata.witness_script;
104  return true;
105  }
106  return false;
107 }
108 
109 static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
110 {
111  // Look for pubkey in all partial sigs
112  const auto it = sigdata.signatures.find(address);
113  if (it != sigdata.signatures.end()) {
114  pubkey = it->second.first;
115  return true;
116  }
117  // Look for pubkey in pubkey lists
118  const auto& pk_it = sigdata.misc_pubkeys.find(address);
119  if (pk_it != sigdata.misc_pubkeys.end()) {
120  pubkey = pk_it->second.first;
121  return true;
122  }
123  const auto& tap_pk_it = sigdata.tap_pubkeys.find(address);
124  if (tap_pk_it != sigdata.tap_pubkeys.end()) {
125  pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey();
126  return true;
127  }
128  // Query the underlying provider
129  return provider.GetPubKey(address, pubkey);
130 }
131 
132 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)
133 {
134  CKeyID keyid = pubkey.GetID();
135  const auto it = sigdata.signatures.find(keyid);
136  if (it != sigdata.signatures.end()) {
137  sig_out = it->second.second;
138  return true;
139  }
140  KeyOriginInfo info;
141  if (provider.GetKeyOrigin(keyid, info)) {
142  sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
143  }
144  if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
145  auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));
146  assert(i.second);
147  return true;
148  }
149  // Could not make signature or signature not found, add keyid to missing
150  sigdata.missing_sigs.push_back(keyid);
151  return false;
152 }
153 
154 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)
155 {
156  KeyOriginInfo info;
157  if (provider.GetKeyOriginByXOnly(pubkey, info)) {
158  auto it = sigdata.taproot_misc_pubkeys.find(pubkey);
159  if (it == sigdata.taproot_misc_pubkeys.end()) {
160  sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
161  } else {
162  it->second.first.insert(leaf_hash);
163  }
164  }
165 
166  auto lookup_key = std::make_pair(pubkey, leaf_hash);
167  auto it = sigdata.taproot_script_sigs.find(lookup_key);
168  if (it != sigdata.taproot_script_sigs.end()) {
169  sig_out = it->second;
170  return true;
171  }
172  if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
173  sigdata.taproot_script_sigs[lookup_key] = sig_out;
174  return true;
175  }
176  return false;
177 }
178 
179 template<typename M, typename K, typename V>
180 miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value)
181 {
182  auto it = map.find(key);
183  if (it != map.end()) {
184  value = it->second;
186  }
188 }
189 
194 template<typename Pk>
195 struct Satisfier {
196  using Key = Pk;
197 
204 
206  const BaseSignatureCreator& creator LIFETIMEBOUND,
207  const CScript& witscript LIFETIMEBOUND,
208  miniscript::MiniscriptContext script_ctx) : m_provider(provider),
209  m_sig_data(sig_data),
210  m_creator(creator),
211  m_witness_script(witscript),
212  m_script_ctx(script_ctx) {}
213 
214  static bool KeyCompare(const Key& a, const Key& b) {
215  return a < b;
216  }
217 
219  template<typename I>
220  std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
221  assert(last - first == 20);
222  CPubKey pubkey;
223  CKeyID key_id;
224  std::copy(first, last, key_id.begin());
225  if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
226  m_sig_data.missing_pubkeys.push_back(key_id);
227  return {};
228  }
229 
231  std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
232 
234  bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
235  bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
236 
238  miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
239  return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
240  }
241  miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
242  return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage);
243  }
244  miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
245  return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
246  }
247  miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
248  return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage);
249  }
250 
252  return m_script_ctx;
253  }
254 };
255 
257 struct WshSatisfier: Satisfier<CPubKey> {
259  const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& witscript LIFETIMEBOUND)
260  : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {}
261 
263  template <typename I>
264  std::optional<CPubKey> FromPKBytes(I first, I last) const {
265  CPubKey pubkey{first, last};
266  if (pubkey.IsValid()) return pubkey;
267  return {};
268  }
269 
271  template<typename I>
272  std::optional<CPubKey> FromPKHBytes(I first, I last) const {
273  return Satisfier::CPubFromPKHBytes(first, last);
274  }
275 
277  miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
280  }
282  }
283 };
284 
286 struct TapSatisfier: Satisfier<XOnlyPubKey> {
288 
290  const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& script LIFETIMEBOUND,
291  const uint256& leaf_hash LIFETIMEBOUND)
292  : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT),
293  m_leaf_hash(leaf_hash) {}
294 
296  template <typename I>
297  std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const {
298  if (last - first != 32) return {};
299  XOnlyPubKey pubkey;
300  std::copy(first, last, pubkey.begin());
301  return pubkey;
302  }
303 
305  template<typename I>
306  std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
307  if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
308  return {};
309  }
310 
312  miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const {
315  }
317  }
318 };
319 
320 static bool SignTaprootScript(const SigningProvider& provider, const BaseSignatureCreator& creator, SignatureData& sigdata, int leaf_version, Span<const unsigned char> script_bytes, std::vector<valtype>& result)
321 {
322  // Only BIP342 tapscript signing is supported for now.
323  if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
324 
325  uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes);
326  CScript script = CScript(script_bytes.begin(), script_bytes.end());
327 
328  TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash};
329  const auto ms = miniscript::FromScript(script, ms_satisfier);
330  return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
331 }
332 
333 static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
334 {
335  TaprootSpendData spenddata;
336  TaprootBuilder builder;
337 
338  // Gather information about this output.
339  if (provider.GetTaprootSpendData(output, spenddata)) {
340  sigdata.tr_spenddata.Merge(spenddata);
341  }
342  if (provider.GetTaprootBuilder(output, builder)) {
343  sigdata.tr_builder = builder;
344  }
345 
346  // Try key path spending.
347  {
348  KeyOriginInfo info;
349  if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, info)) {
350  auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key);
351  if (it == sigdata.taproot_misc_pubkeys.end()) {
352  sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), info));
353  }
354  }
355 
356  std::vector<unsigned char> sig;
357  if (sigdata.taproot_key_path_sig.size() == 0) {
358  if (creator.CreateSchnorrSig(provider, sig, sigdata.tr_spenddata.internal_key, nullptr, &sigdata.tr_spenddata.merkle_root, SigVersion::TAPROOT)) {
359  sigdata.taproot_key_path_sig = sig;
360  }
361  }
362  if (sigdata.taproot_key_path_sig.size() == 0) {
363  if (creator.CreateSchnorrSig(provider, sig, output, nullptr, nullptr, SigVersion::TAPROOT)) {
364  sigdata.taproot_key_path_sig = sig;
365  }
366  }
367  if (sigdata.taproot_key_path_sig.size()) {
368  result = Vector(sigdata.taproot_key_path_sig);
369  return true;
370  }
371  }
372 
373  // Try script path spending.
374  std::vector<std::vector<unsigned char>> smallest_result_stack;
375  for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
376  const auto& [script, leaf_ver] = key;
377  std::vector<std::vector<unsigned char>> result_stack;
378  if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
379  result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
380  result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
381  if (smallest_result_stack.size() == 0 ||
382  GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) {
383  smallest_result_stack = std::move(result_stack);
384  }
385  }
386  }
387  if (smallest_result_stack.size() != 0) {
388  result = std::move(smallest_result_stack);
389  return true;
390  }
391 
392  return false;
393 }
394 
401 static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,
402  std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)
403 {
404  CScript scriptRet;
405  ret.clear();
406  std::vector<unsigned char> sig;
407 
408  std::vector<valtype> vSolutions;
409  whichTypeRet = Solver(scriptPubKey, vSolutions);
410 
411  switch (whichTypeRet) {
415  return false;
416  case TxoutType::PUBKEY:
417  if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
418  ret.push_back(std::move(sig));
419  return true;
420  case TxoutType::PUBKEYHASH: {
421  CKeyID keyID = CKeyID(uint160(vSolutions[0]));
422  CPubKey pubkey;
423  if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
424  // Pubkey could not be found, add to missing
425  sigdata.missing_pubkeys.push_back(keyID);
426  return false;
427  }
428  if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;
429  ret.push_back(std::move(sig));
430  ret.push_back(ToByteVector(pubkey));
431  return true;
432  }
433  case TxoutType::SCRIPTHASH: {
434  uint160 h160{vSolutions[0]};
435  if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
436  ret.emplace_back(scriptRet.begin(), scriptRet.end());
437  return true;
438  }
439  // Could not find redeemScript, add to missing
440  sigdata.missing_redeem_script = h160;
441  return false;
442  }
443  case TxoutType::MULTISIG: {
444  size_t required = vSolutions.front()[0];
445  ret.emplace_back(); // workaround CHECKMULTISIG bug
446  for (size_t i = 1; i < vSolutions.size() - 1; ++i) {
447  CPubKey pubkey = CPubKey(vSolutions[i]);
448  // We need to always call CreateSig in order to fill sigdata with all
449  // possible signatures that we can create. This will allow further PSBT
450  // processing to work as it needs all possible signature and pubkey pairs
451  if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
452  if (ret.size() < required + 1) {
453  ret.push_back(std::move(sig));
454  }
455  }
456  }
457  bool ok = ret.size() == required + 1;
458  for (size_t i = 0; i + ret.size() < required + 1; ++i) {
459  ret.emplace_back();
460  }
461  return ok;
462  }
464  ret.push_back(vSolutions[0]);
465  return true;
466 
468  if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) {
469  ret.emplace_back(scriptRet.begin(), scriptRet.end());
470  return true;
471  }
472  // Could not find witnessScript, add to missing
473  sigdata.missing_witness_script = uint256(vSolutions[0]);
474  return false;
475 
477  return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
478  } // no default case, so the compiler can warn about missing cases
479  assert(false);
480 }
481 
482 static CScript PushAll(const std::vector<valtype>& values)
483 {
484  CScript result;
485  for (const valtype& v : values) {
486  if (v.size() == 0) {
487  result << OP_0;
488  } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
489  result << CScript::EncodeOP_N(v[0]);
490  } else if (v.size() == 1 && v[0] == 0x81) {
491  result << OP_1NEGATE;
492  } else {
493  result << v;
494  }
495  }
496  return result;
497 }
498 
499 bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
500 {
501  if (sigdata.complete) return true;
502 
503  std::vector<valtype> result;
504  TxoutType whichType;
505  bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
506  bool P2SH = false;
507  CScript subscript;
508 
509  if (solved && whichType == TxoutType::SCRIPTHASH)
510  {
511  // Solver returns the subscript that needs to be evaluated;
512  // the final scriptSig is the signatures from that
513  // and then the serialized subscript:
514  subscript = CScript(result[0].begin(), result[0].end());
515  sigdata.redeem_script = subscript;
516  solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
517  P2SH = true;
518  }
519 
520  if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
521  {
522  CScript witnessscript;
523  witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
524  TxoutType subType;
525  solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
526  sigdata.scriptWitness.stack = result;
527  sigdata.witness = true;
528  result.clear();
529  }
530  else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
531  {
532  CScript witnessscript(result[0].begin(), result[0].end());
533  sigdata.witness_script = witnessscript;
534 
536  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;
537 
538  // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript.
539  // Note we need to check if the result stack is empty before, because it might be used even if the Script
540  // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures
541  // and the extractor relies on this behaviour to combine witnesses.
542  if (!solved && result.empty()) {
543  WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
544  const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
545  solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
546  }
547  result.emplace_back(witnessscript.begin(), witnessscript.end());
548 
549  sigdata.scriptWitness.stack = result;
550  sigdata.witness = true;
551  result.clear();
552  } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
553  sigdata.witness = true;
554  if (solved) {
555  sigdata.scriptWitness.stack = std::move(result);
556  }
557  result.clear();
558  } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
559  sigdata.witness = true;
560  }
561 
562  if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
563  if (P2SH) {
564  result.emplace_back(subscript.begin(), subscript.end());
565  }
566  sigdata.scriptSig = PushAll(result);
567 
568  // Test solution
569  sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
570  return sigdata.complete;
571 }
572 
573 namespace {
574 class SignatureExtractorChecker final : public DeferringSignatureChecker
575 {
576 private:
577  SignatureData& sigdata;
578 
579 public:
580  SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
581 
582  bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
583  {
584  if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
585  CPubKey pubkey(vchPubKey);
586  sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
587  return true;
588  }
589  return false;
590  }
591 };
592 
593 struct Stacks
594 {
595  std::vector<valtype> script;
596  std::vector<valtype> witness;
597 
598  Stacks() = delete;
599  Stacks(const Stacks&) = delete;
600  explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
602  }
603 };
604 }
605 
606 // Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
607 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
608 {
609  SignatureData data;
610  assert(tx.vin.size() > nIn);
611  data.scriptSig = tx.vin[nIn].scriptSig;
612  data.scriptWitness = tx.vin[nIn].scriptWitness;
613  Stacks stack(data);
614 
615  // Get signatures
617  SignatureExtractorChecker extractor_checker(data, tx_checker);
618  if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
619  data.complete = true;
620  return data;
621  }
622 
623  // Get scripts
624  std::vector<std::vector<unsigned char>> solutions;
625  TxoutType script_type = Solver(txout.scriptPubKey, solutions);
626  SigVersion sigversion = SigVersion::BASE;
627  CScript next_script = txout.scriptPubKey;
628 
629  if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
630  // Get the redeemScript
631  CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
632  data.redeem_script = redeem_script;
633  next_script = std::move(redeem_script);
634 
635  // Get redeemScript type
636  script_type = Solver(next_script, solutions);
637  stack.script.pop_back();
638  }
639  if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
640  // Get the witnessScript
641  CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
642  data.witness_script = witness_script;
643  next_script = std::move(witness_script);
644 
645  // Get witnessScript type
646  script_type = Solver(next_script, solutions);
647  stack.witness.pop_back();
648  stack.script = std::move(stack.witness);
649  stack.witness.clear();
650  sigversion = SigVersion::WITNESS_V0;
651  }
652  if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
653  // Build a map of pubkey -> signature by matching sigs to pubkeys:
654  assert(solutions.size() > 1);
655  unsigned int num_pubkeys = solutions.size()-2;
656  unsigned int last_success_key = 0;
657  for (const valtype& sig : stack.script) {
658  for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
659  const valtype& pubkey = solutions[i+1];
660  // We either have a signature for this pubkey, or we have found a signature and it is valid
661  if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
662  last_success_key = i + 1;
663  break;
664  }
665  }
666  }
667  }
668 
669  return data;
670 }
671 
672 void UpdateInput(CTxIn& input, const SignatureData& data)
673 {
674  input.scriptSig = data.scriptSig;
675  input.scriptWitness = data.scriptWitness;
676 }
677 
679 {
680  if (complete) return;
681  if (sigdata.complete) {
682  *this = std::move(sigdata);
683  return;
684  }
685  if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
686  redeem_script = sigdata.redeem_script;
687  }
688  if (witness_script.empty() && !sigdata.witness_script.empty()) {
689  witness_script = sigdata.witness_script;
690  }
691  signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
692 }
693 
694 bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType, SignatureData& sig_data)
695 {
696  assert(nIn < txTo.vin.size());
697 
698  MutableTransactionSignatureCreator creator(txTo, nIn, amount, nHashType);
699 
700  bool ret = ProduceSignature(provider, creator, fromPubKey, sig_data);
701  UpdateInput(txTo.vin.at(nIn), sig_data);
702  return ret;
703 }
704 
705 bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType, SignatureData& sig_data)
706 {
707  assert(nIn < txTo.vin.size());
708  const CTxIn& txin = txTo.vin[nIn];
709  assert(txin.prevout.n < txFrom.vout.size());
710  const CTxOut& txout = txFrom.vout[txin.prevout.n];
711 
712  return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType, sig_data);
713 }
714 
715 namespace {
717 class DummySignatureChecker final : public BaseSignatureChecker
718 {
719 public:
720  DummySignatureChecker() = default;
721  bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return sig.size() != 0; }
722  bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return sig.size() != 0; }
723  bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; }
724  bool CheckSequence(const CScriptNum& nSequence) const override { return true; }
725 };
726 }
727 
728 const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker();
729 
730 namespace {
731 class DummySignatureCreator final : public BaseSignatureCreator {
732 private:
733  char m_r_len = 32;
734  char m_s_len = 32;
735 public:
736  DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
737  const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
738  bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
739  {
740  // Create a dummy signature that is a valid DER-encoding
741  vchSig.assign(m_r_len + m_s_len + 7, '\000');
742  vchSig[0] = 0x30;
743  vchSig[1] = m_r_len + m_s_len + 4;
744  vchSig[2] = 0x02;
745  vchSig[3] = m_r_len;
746  vchSig[4] = 0x01;
747  vchSig[4 + m_r_len] = 0x02;
748  vchSig[5 + m_r_len] = m_s_len;
749  vchSig[6 + m_r_len] = 0x01;
750  vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
751  return true;
752  }
753  bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
754  {
755  sig.assign(64, '\000');
756  return true;
757  }
758 };
759 
760 }
761 
762 const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
763 const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
764 
765 bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
766 {
767  int version;
768  valtype program;
769  if (script.IsWitnessProgram(version, program)) return true;
770  if (script.IsPayToScriptHash()) {
771  std::vector<valtype> solutions;
772  auto whichtype = Solver(script, solutions);
773  if (whichtype == TxoutType::SCRIPTHASH) {
774  auto h160 = uint160(solutions[0]);
775  CScript subscript;
776  if (provider.GetCScript(CScriptID{h160}, subscript)) {
777  if (subscript.IsWitnessProgram(version, program)) return true;
778  }
779  }
780  }
781  return false;
782 }
783 
784 bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, bilingual_str>& input_errors)
785 {
786  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
787 
788  // Use CTransaction for the constant parts of the
789  // transaction to avoid rehashing.
790  const CTransaction txConst(mtx);
791 
793  std::vector<CTxOut> spent_outputs;
794  for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
795  CTxIn& txin = mtx.vin[i];
796  auto coin = coins.find(txin.prevout);
797  if (coin == coins.end() || coin->second.IsSpent()) {
798  txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
799  break;
800  } else {
801  spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
802  }
803  }
804  if (spent_outputs.size() == mtx.vin.size()) {
805  txdata.Init(txConst, std::move(spent_outputs), true);
806  }
807 
808  // Sign what we can:
809  for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
810  CTxIn& txin = mtx.vin[i];
811  auto coin = coins.find(txin.prevout);
812  if (coin == coins.end() || coin->second.IsSpent()) {
813  input_errors[i] = _("Input not found or already spent");
814  continue;
815  }
816  const CScript& prevPubKey = coin->second.out.scriptPubKey;
817  const CAmount& amount = coin->second.out.nValue;
818 
819  SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
820  // Only sign SIGHASH_SINGLE if there's a corresponding output:
821  if (!fHashSingle || (i < mtx.vout.size())) {
822  ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata);
823  }
824 
825  UpdateInput(txin, sigdata);
826 
827  // amount must be specified for valid segwit signature
828  if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
829  input_errors[i] = _("Missing amount");
830  continue;
831  }
832 
833  ScriptError serror = SCRIPT_ERR_OK;
834  if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
835  if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
836  // Unable to sign input and verification failed (possible attempt to partially sign).
837  input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
838  } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
839  // Verification failed (possibly due to insufficient signatures).
840  input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
841  } else {
842  input_errors[i] = Untranslated(ScriptErrorString(serror));
843  }
844  } else {
845  // If this input succeeds, make sure there is no error set for it
846  input_errors.erase(i);
847  }
848  }
849  return input_errors.empty();
850 }
std::vector< unsigned char > valtype
Definition: addresstype.cpp:18
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
#define LIFETIMEBOUND
Definition: attributes.h:16
int ret
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:258
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
Definition: interpreter.h:253
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:263
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:248
Interface for signature creators.
Definition: sign.h:28
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 const BaseSignatureChecker & Checker() 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.
An encapsulated private key.
Definition: key.h:33
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
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:214
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:122
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
uint32_t n
Definition: transaction.h:32
An encapsulated public key.
Definition: pubkey.h:34
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
bool IsPayToScriptHash() const
Definition: script.cpp:207
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:226
static opcodetype EncodeOP_N(int n)
Definition: script.h:513
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:583
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const std::vector< CTxOut > vout
Definition: transaction.h:307
An input of a transaction.
Definition: transaction.h:67
CScript scriptSig
Definition: transaction.h:70
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:72
COutPoint prevout
Definition: transaction.h:69
An output of a transaction.
Definition: transaction.h:150
CScript scriptPubKey
Definition: transaction.h:153
CAmount nValue
Definition: transaction.h:152
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
Definition: interpreter.h:317
A signature creator for transactions.
Definition: sign.h:40
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:62
MutableTransactionSignatureCreator(const CMutableTransaction &tx LIFETIMEBOUND, unsigned int input_idx, const CAmount &amount, int hash_type)
const CMutableTransaction & m_txto
Definition: sign.h:41
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:37
const PrecomputedTransactionData * m_txdata
Definition: sign.h:46
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
bool GetKeyOriginByXOnly(const XOnlyPubKey &pubkey, KeyOriginInfo &info) const
virtual bool GetTaprootBuilder(const XOnlyPubKey &output_key, TaprootBuilder &builder) const
virtual bool GetKey(const CKeyID &address, CKey &key) const
virtual bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const
constexpr std::size_t size() const noexcept
Definition: span.h:187
constexpr C * end() const noexcept
Definition: span.h:176
constexpr C * begin() const noexcept
Definition: span.h:175
Utility class to construct Taproot outputs from internal key and script tree.
const unsigned char * begin() const
Definition: pubkey.h:290
constexpr unsigned char * begin()
Definition: uint256.h:68
bool empty() const
Definition: prevector.h:300
iterator begin()
Definition: prevector.h:304
iterator end()
Definition: prevector.h:306
160-bit opaque blob.
Definition: uint256.h:95
256-bit opaque blob.
Definition: uint256.h:106
uint160 RIPEMD160(Span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
Definition: hash.h:222
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)
uint256 ComputeTapleafHash(uint8_t leaf_version, Span< const unsigned char > script)
Compute the BIP341 tapleaf hash from leaf version & script.
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:191
@ 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_STRICTENC
Definition: interpreter.h:54
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:232
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:33
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
@ SIGHASH_ALL
Definition: interpreter.h:30
@ SIGHASH_SINGLE
Definition: interpreter.h:32
MissingDataBehavior
Enum to specify what *TransactionSignatureChecker's behavior should be when dealing with missing tran...
Definition: interpreter.h:275
@ FAIL
Just act as if the signature was invalid.
NodeRef< typename Ctx::Key > FromScript(const CScript &script, const Ctx &ctx)
Definition: miniscript.h:2616
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:103
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:66
@ OP_1NEGATE
Definition: script.h:80
@ OP_CHECKSIG
Definition: script.h:189
@ OP_DUP
Definition: script.h:124
@ OP_HASH160
Definition: script.h:186
@ OP_0
Definition: script.h:75
@ OP_EQUALVERIFY
Definition: script.h:146
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)
Definition: serialize.h:1116
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:401
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:499
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:154
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:672
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
Definition: sign.cpp:765
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:132
static bool SignTaprootScript(const SigningProvider &provider, const BaseSignatureCreator &creator, SignatureData &sigdata, int leaf_version, Span< const unsigned char > script_bytes, std::vector< valtype > &result)
Definition: sign.cpp:320
std::vector< unsigned char > valtype
Definition: sign.cpp:21
static bool SignTaproot(const SigningProvider &provider, const BaseSignatureCreator &creator, const WitnessV1Taproot &output, SignatureData &sigdata, std::vector< valtype > &result)
Definition: sign.cpp:333
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:763
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:109
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:607
const BaseSignatureChecker & DUMMY_CHECKER
A signature checker that accepts all signatures.
Definition: sign.cpp:728
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:784
static CScript PushAll(const std::vector< valtype > &values)
Definition: sign.cpp:482
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:762
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType, SignatureData &sig_data)
Produce a satisfying script (scriptSig or witness).
Definition: sign.cpp:694
miniscript::Availability MsLookupHelper(const M &map, const K &key, V &value)
Definition: sign.cpp:180
static bool GetCScript(const SigningProvider &provider, const SignatureData &sigdata, const CScriptID &scriptid, CScript &script)
Definition: sign.cpp:93
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:63
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:140
TxoutType
Definition: solver.h:22
@ 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:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
std::vector< std::vector< unsigned char > > stack
Definition: script.h:569
bool IsNull() const
Definition: script.h:574
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:163
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:172
Context for solving a Miniscript.
Definition: sign.cpp:195
const BaseSignatureCreator & m_creator
Definition: sign.cpp:200
miniscript::Availability SatRIPEMD160(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Definition: sign.cpp:241
std::vector< unsigned char > ToPKBytes(const Key &key) const
Conversion to raw public key.
Definition: sign.cpp:231
bool CheckAfter(uint32_t value) const
Time lock satisfactions.
Definition: sign.cpp:234
const miniscript::MiniscriptContext m_script_ctx
The context of the script we are satisfying (either P2WSH or Tapscript).
Definition: sign.cpp:203
miniscript::Availability SatSHA256(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Hash preimage satisfactions.
Definition: sign.cpp:238
Pk Key
Definition: sign.cpp:196
miniscript::Availability SatHASH256(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Definition: sign.cpp:244
const SigningProvider & m_provider
Definition: sign.cpp:198
Satisfier(const SigningProvider &provider LIFETIMEBOUND, SignatureData &sig_data LIFETIMEBOUND, const BaseSignatureCreator &creator LIFETIMEBOUND, const CScript &witscript LIFETIMEBOUND, miniscript::MiniscriptContext script_ctx)
Definition: sign.cpp:205
miniscript::Availability SatHASH160(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Definition: sign.cpp:247
SignatureData & m_sig_data
Definition: sign.cpp:199
bool CheckOlder(uint32_t value) const
Definition: sign.cpp:235
std::optional< CPubKey > CPubFromPKHBytes(I first, I last) const
Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey.
Definition: sign.cpp:220
static bool KeyCompare(const Key &a, const Key &b)
Definition: sign.cpp:214
miniscript::MiniscriptContext MsContext() const
Definition: sign.cpp:251
const CScript & m_witness_script
Definition: sign.cpp:201
uint256 m_tapleaf_hash
The tapleaf hash.
Definition: interpreter.h:203
bool m_annex_present
Whether an annex is present.
Definition: interpreter.h:213
bool m_annex_init
Whether m_annex_present and (when needed) m_annex_hash are initialized.
Definition: interpreter.h:211
bool m_codeseparator_pos_init
Whether m_codeseparator_pos is initialized.
Definition: interpreter.h:206
bool m_tapleaf_hash_init
Whether m_tapleaf_hash is initialized.
Definition: interpreter.h:201
uint32_t m_codeseparator_pos
Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed).
Definition: interpreter.h:208
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:85
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:84
std::map< std::vector< uint8_t >, std::vector< uint8_t > > ripemd160_preimages
Mapping from a RIPEMD160 hash to its preimage provided to solve a Script.
Definition: sign.h:89
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:678
std::map< CKeyID, XOnlyPubKey > tap_pubkeys
Misc Taproot pubkeys involved in this input, by hash. (Equivalent of misc_pubkeys but for Taproot....
Definition: sign.h:82
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:77
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:75
bool witness
Stores whether the input this SigData corresponds to is a witness input.
Definition: sign.h:70
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:78
std::optional< TaprootBuilder > tr_builder
Taproot tree used to build tr_spenddata.
Definition: sign.h:76
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format.
Definition: sign.h:71
std::map< std::vector< uint8_t >, std::vector< uint8_t > > sha256_preimages
Mapping from a SHA256 hash to its preimage provided to solve a Script.
Definition: sign.h:87
std::vector< unsigned char > taproot_key_path_sig
Definition: sign.h:79
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > taproot_script_sigs
Schnorr signature for key path spending.
Definition: sign.h:80
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:81
std::map< std::vector< uint8_t >, std::vector< uint8_t > > hash256_preimages
Mapping from a HASH256 hash to its preimage provided to solve a Script.
Definition: sign.h:88
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:72
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:86
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:83
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:73
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition: sign.h:74
bool complete
Stores whether the scriptSig and scriptWitness are complete.
Definition: sign.h:69
std::map< std::vector< uint8_t >, std::vector< uint8_t > > hash160_preimages
Mapping from a HASH160 hash to its preimage provided to solve a Script.
Definition: sign.h:90
Miniscript satisfier specific to Tapscript context.
Definition: sign.cpp:286
std::optional< XOnlyPubKey > FromPKBytes(I first, I last) const
Conversion from a raw xonly public key.
Definition: sign.cpp:297
const uint256 & m_leaf_hash
Definition: sign.cpp:287
miniscript::Availability Sign(const XOnlyPubKey &key, std::vector< unsigned char > &sig) const
Satisfy a BIP340 signature check.
Definition: sign.cpp:312
TapSatisfier(const SigningProvider &provider LIFETIMEBOUND, SignatureData &sig_data LIFETIMEBOUND, const BaseSignatureCreator &creator LIFETIMEBOUND, const CScript &script LIFETIMEBOUND, const uint256 &leaf_hash LIFETIMEBOUND)
Definition: sign.cpp:289
std::optional< XOnlyPubKey > FromPKHBytes(I first, I last) const
Conversion from a raw xonly public key hash.
Definition: sign.cpp:306
uint256 merkle_root
The Merkle root of the script tree (0 if no scripts).
std::map< std::pair< std::vector< unsigned char >, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > scripts
Map from (script, leaf_version) to (sets of) control blocks.
void Merge(TaprootSpendData other)
Merge other TaprootSpendData (for the same scriptPubKey) into this.
XOnlyPubKey internal_key
The BIP341 internal key.
Miniscript satisfier specific to P2WSH context.
Definition: sign.cpp:257
WshSatisfier(const SigningProvider &provider LIFETIMEBOUND, SignatureData &sig_data LIFETIMEBOUND, const BaseSignatureCreator &creator LIFETIMEBOUND, const CScript &witscript LIFETIMEBOUND)
Definition: sign.cpp:258
std::optional< CPubKey > FromPKBytes(I first, I last) const
Conversion from a raw compressed public key.
Definition: sign.cpp:264
std::optional< CPubKey > FromPKHBytes(I first, I last) const
Conversion from a raw compressed public key hash.
Definition: sign.cpp:272
miniscript::Availability Sign(const CPubKey &key, std::vector< unsigned char > &sig) const
Satisfy an ECDSA signature check.
Definition: sign.cpp:277
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
assert(!tx.IsCoinBase())
std::vector< typename std::common_type< Args... >::type > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition: vector.h:23