Bitcoin Core  29.1.0
P2P Digital Currency
sign.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-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 
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()) {
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 
479  case TxoutType::ANCHOR:
480  return true;
481  } // no default case, so the compiler can warn about missing cases
482  assert(false);
483 }
484 
485 static CScript PushAll(const std::vector<valtype>& values)
486 {
487  CScript result;
488  for (const valtype& v : values) {
489  if (v.size() == 0) {
490  result << OP_0;
491  } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
492  result << CScript::EncodeOP_N(v[0]);
493  } else if (v.size() == 1 && v[0] == 0x81) {
494  result << OP_1NEGATE;
495  } else {
496  result << v;
497  }
498  }
499  return result;
500 }
501 
502 bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
503 {
504  if (sigdata.complete) return true;
505 
506  std::vector<valtype> result;
507  TxoutType whichType;
508  bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
509  bool P2SH = false;
510  CScript subscript;
511 
512  if (solved && whichType == TxoutType::SCRIPTHASH)
513  {
514  // Solver returns the subscript that needs to be evaluated;
515  // the final scriptSig is the signatures from that
516  // and then the serialized subscript:
517  subscript = CScript(result[0].begin(), result[0].end());
518  sigdata.redeem_script = subscript;
519  solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
520  P2SH = true;
521  }
522 
523  if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
524  {
525  CScript witnessscript;
526  witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
527  TxoutType subType;
528  solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
529  sigdata.scriptWitness.stack = result;
530  sigdata.witness = true;
531  result.clear();
532  }
533  else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
534  {
535  CScript witnessscript(result[0].begin(), result[0].end());
536  sigdata.witness_script = witnessscript;
537 
539  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;
540 
541  // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript.
542  // Note we need to check if the result stack is empty before, because it might be used even if the Script
543  // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures
544  // and the extractor relies on this behaviour to combine witnesses.
545  if (!solved && result.empty()) {
546  WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
547  const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
548  solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
549  }
550  result.emplace_back(witnessscript.begin(), witnessscript.end());
551 
552  sigdata.scriptWitness.stack = result;
553  sigdata.witness = true;
554  result.clear();
555  } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
556  sigdata.witness = true;
557  if (solved) {
558  sigdata.scriptWitness.stack = std::move(result);
559  }
560  result.clear();
561  } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
562  sigdata.witness = true;
563  }
564 
565  if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
566  if (P2SH) {
567  result.emplace_back(subscript.begin(), subscript.end());
568  }
569  sigdata.scriptSig = PushAll(result);
570 
571  // Test solution
572  sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
573  return sigdata.complete;
574 }
575 
576 namespace {
577 class SignatureExtractorChecker final : public DeferringSignatureChecker
578 {
579 private:
580  SignatureData& sigdata;
581 
582 public:
583  SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
584 
585  bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
586  {
587  if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
588  CPubKey pubkey(vchPubKey);
589  sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
590  return true;
591  }
592  return false;
593  }
594 };
595 
596 struct Stacks
597 {
598  std::vector<valtype> script;
599  std::vector<valtype> witness;
600 
601  Stacks() = delete;
602  Stacks(const Stacks&) = delete;
603  explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
605  }
606 };
607 }
608 
609 // Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
610 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
611 {
613  assert(tx.vin.size() > nIn);
614  data.scriptSig = tx.vin[nIn].scriptSig;
615  data.scriptWitness = tx.vin[nIn].scriptWitness;
616  Stacks stack(data);
617 
618  // Get signatures
620  SignatureExtractorChecker extractor_checker(data, tx_checker);
621  if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
622  data.complete = true;
623  return data;
624  }
625 
626  // Get scripts
627  std::vector<std::vector<unsigned char>> solutions;
628  TxoutType script_type = Solver(txout.scriptPubKey, solutions);
629  SigVersion sigversion = SigVersion::BASE;
630  CScript next_script = txout.scriptPubKey;
631 
632  if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
633  // Get the redeemScript
634  CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
635  data.redeem_script = redeem_script;
636  next_script = std::move(redeem_script);
637 
638  // Get redeemScript type
639  script_type = Solver(next_script, solutions);
640  stack.script.pop_back();
641  }
642  if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
643  // Get the witnessScript
644  CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
645  data.witness_script = witness_script;
646  next_script = std::move(witness_script);
647 
648  // Get witnessScript type
649  script_type = Solver(next_script, solutions);
650  stack.witness.pop_back();
651  stack.script = std::move(stack.witness);
652  stack.witness.clear();
653  sigversion = SigVersion::WITNESS_V0;
654  }
655  if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
656  // Build a map of pubkey -> signature by matching sigs to pubkeys:
657  assert(solutions.size() > 1);
658  unsigned int num_pubkeys = solutions.size()-2;
659  unsigned int last_success_key = 0;
660  for (const valtype& sig : stack.script) {
661  for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
662  const valtype& pubkey = solutions[i+1];
663  // We either have a signature for this pubkey, or we have found a signature and it is valid
664  if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
665  last_success_key = i + 1;
666  break;
667  }
668  }
669  }
670  }
671 
672  return data;
673 }
674 
675 void UpdateInput(CTxIn& input, const SignatureData& data)
676 {
677  input.scriptSig = data.scriptSig;
678  input.scriptWitness = data.scriptWitness;
679 }
680 
682 {
683  if (complete) return;
684  if (sigdata.complete) {
685  *this = std::move(sigdata);
686  return;
687  }
688  if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
689  redeem_script = sigdata.redeem_script;
690  }
691  if (witness_script.empty() && !sigdata.witness_script.empty()) {
692  witness_script = sigdata.witness_script;
693  }
694  signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
695 }
696 
697 namespace {
699 class DummySignatureChecker final : public BaseSignatureChecker
700 {
701 public:
702  DummySignatureChecker() = default;
703  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; }
704  bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return sig.size() != 0; }
705  bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; }
706  bool CheckSequence(const CScriptNum& nSequence) const override { return true; }
707 };
708 }
709 
710 const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker();
711 
712 namespace {
713 class DummySignatureCreator final : public BaseSignatureCreator {
714 private:
715  char m_r_len = 32;
716  char m_s_len = 32;
717 public:
718  DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
719  const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
720  bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
721  {
722  // Create a dummy signature that is a valid DER-encoding
723  vchSig.assign(m_r_len + m_s_len + 7, '\000');
724  vchSig[0] = 0x30;
725  vchSig[1] = m_r_len + m_s_len + 4;
726  vchSig[2] = 0x02;
727  vchSig[3] = m_r_len;
728  vchSig[4] = 0x01;
729  vchSig[4 + m_r_len] = 0x02;
730  vchSig[5 + m_r_len] = m_s_len;
731  vchSig[6 + m_r_len] = 0x01;
732  vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
733  return true;
734  }
735  bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
736  {
737  sig.assign(64, '\000');
738  return true;
739  }
740 };
741 
742 }
743 
744 const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
745 const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
746 
747 bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
748 {
749  int version;
750  valtype program;
751  if (script.IsWitnessProgram(version, program)) return true;
752  if (script.IsPayToScriptHash()) {
753  std::vector<valtype> solutions;
754  auto whichtype = Solver(script, solutions);
755  if (whichtype == TxoutType::SCRIPTHASH) {
756  auto h160 = uint160(solutions[0]);
757  CScript subscript;
758  if (provider.GetCScript(CScriptID{h160}, subscript)) {
759  if (subscript.IsWitnessProgram(version, program)) return true;
760  }
761  }
762  }
763  return false;
764 }
765 
766 bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, bilingual_str>& input_errors)
767 {
768  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
769 
770  // Use CTransaction for the constant parts of the
771  // transaction to avoid rehashing.
772  const CTransaction txConst(mtx);
773 
775  std::vector<CTxOut> spent_outputs;
776  for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
777  CTxIn& txin = mtx.vin[i];
778  auto coin = coins.find(txin.prevout);
779  if (coin == coins.end() || coin->second.IsSpent()) {
780  txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
781  break;
782  } else {
783  spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
784  }
785  }
786  if (spent_outputs.size() == mtx.vin.size()) {
787  txdata.Init(txConst, std::move(spent_outputs), true);
788  }
789 
790  // Sign what we can:
791  for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
792  CTxIn& txin = mtx.vin[i];
793  auto coin = coins.find(txin.prevout);
794  if (coin == coins.end() || coin->second.IsSpent()) {
795  input_errors[i] = _("Input not found or already spent");
796  continue;
797  }
798  const CScript& prevPubKey = coin->second.out.scriptPubKey;
799  const CAmount& amount = coin->second.out.nValue;
800 
801  SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
802  // Only sign SIGHASH_SINGLE if there's a corresponding output:
803  if (!fHashSingle || (i < mtx.vout.size())) {
804  ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata);
805  }
806 
807  UpdateInput(txin, sigdata);
808 
809  // amount must be specified for valid segwit signature
810  if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
811  input_errors[i] = _("Missing amount");
812  continue;
813  }
814 
815  ScriptError serror = SCRIPT_ERR_OK;
816  if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
817  if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
818  // Unable to sign input and verification failed (possible attempt to partially sign).
819  input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
820  } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
821  // Verification failed (possibly due to insufficient signatures).
822  input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
823  } else {
824  input_errors[i] = Untranslated(ScriptErrorString(serror));
825  }
826  } else {
827  // If this input succeeds, make sure there is no error set for it
828  input_errors.erase(i);
829  }
830  }
831  return input_errors.empty();
832 }
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
CAmount nValue
Definition: transaction.h:152
Witness v0 (P2WPKH and P2WSH); see BIP 141.
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:258
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
int ret
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341...
Context for solving a Miniscript.
Definition: sign.cpp:195
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)
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::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
assert(!tx.IsCoinBase())
enum ScriptError_t ScriptError
CScript scriptPubKey
Definition: transaction.h:153
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:73
constexpr C * end() const noexcept
Definition: span.h:176
std::optional< CPubKey > FromPKBytes(I first, I last) const
Conversion from a raw compressed public key.
Definition: sign.cpp:264
virtual bool CreateSig(const SigningProvider &provider, std::vector< unsigned char > &vchSig, const CKeyID &keyid, const CScript &scriptCode, SigVersion sigversion) const =0
Create a singular (non-script) signature.
Definition: script.h:125
const CMutableTransaction & m_txto
Definition: sign.h:41
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
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:71
std::vector< CTxIn > vin
Definition: transaction.h:379
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:141
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:72
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1103
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
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
bool m_annex_present
Whether an annex is present.
Definition: interpreter.h:213
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:84
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
Interface for signature creators.
Definition: sign.h:28
constexpr std::size_t size() const noexcept
Definition: span.h:187
static CScript PushAll(const std::vector< valtype > &values)
Definition: sign.cpp:485
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:83
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:744
std::vector< std::vector< unsigned char > > stack
Definition: script.h:588
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 MsLookupHelper(const M &map, const K &key, V &value)
Definition: sign.cpp:180
miniscript::Availability SatHASH160(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Definition: sign.cpp:247
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:745
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
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:232
const uint256 & m_leaf_hash
Definition: sign.cpp:287
bool CheckAfter(uint32_t value) const
Time lock satisfactions.
Definition: sign.cpp:234
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, script path spending, leaf version 0xc0; see...
SignatureData & m_sig_data
Definition: sign.cpp:199
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:243
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:78
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
MutableTransactionSignatureCreator(const CMutableTransaction &tx LIFETIMEBOUND, unsigned int input_idx, const CAmount &amount, int hash_type)
Definition: script.h:76
A signature creator for transactions.
Definition: sign.h:39
bool IsNull() const
Definition: script.h:593
miniscript::Availability Sign(const CPubKey &key, std::vector< unsigned char > &sig) const
Satisfy an ECDSA signature check.
Definition: sign.cpp:277
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:272
uint160 RIPEMD160(Span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
Definition: hash.h:222
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:86
static int tweak(const secp256k1_context *ctx, secp256k1_xonly_pubkey *agg_pk, secp256k1_musig_keyagg_cache *cache)
Definition: musig.c:63
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:116
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
Definition: sign.cpp:747
miniscript::Availability SatSHA256(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Hash preimage satisfactions.
Definition: sign.cpp:238
uint32_t m_codeseparator_pos
Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed).
Definition: interpreter.h:208
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
const BaseSignatureChecker & DUMMY_CHECKER
A signature checker that accepts all signatures.
Definition: sign.cpp:710
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
const unsigned char * begin() const
Definition: pubkey.h:114
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
std::optional< XOnlyPubKey > FromPKBytes(I first, I last) const
Conversion from a raw xonly public key.
Definition: sign.cpp:297
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > taproot_script_sigs
Schnorr signature for key path spending.
Definition: sign.h:80
constexpr unsigned char * begin()
Definition: uint256.h:115
bool GetKeyOriginByXOnly(const XOnlyPubKey &pubkey, KeyOriginInfo &info) const
std::vector< typename std::common_type< Args... >::type > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition: vector.h:23
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
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:208
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:211
iterator end()
Definition: prevector.h:304
uint256 m_tapleaf_hash
The tapleaf hash.
Definition: interpreter.h:203
anyone can spend script
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:85
static bool KeyCompare(const Key &a, const Key &b)
Definition: sign.cpp:214
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
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
const unsigned char * begin() const
Definition: pubkey.h:295
#define LIFETIMEBOUND
Definition: attributes.h:16
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.
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
const unsigned char * end() const
Definition: pubkey.h:115
static bool SignTaproot(const SigningProvider &provider, const BaseSignatureCreator &creator, const WitnessV1Taproot &output, SignatureData &sigdata, std::vector< valtype > &result)
Definition: sign.cpp:333
An input of a transaction.
Definition: transaction.h:66
virtual bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const
std::optional< CPubKey > FromPKHBytes(I first, I last) const
Conversion from a raw compressed public key hash.
Definition: sign.cpp:272
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:132
An encapsulated public key.
Definition: pubkey.h:33
std::optional< TaprootBuilder > tr_builder
Taproot tree used to build tr_spenddata.
Definition: sign.h:76
std::string ScriptErrorString(const ScriptError serror)
miniscript::MiniscriptContext MsContext() const
Definition: sign.cpp:251
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:63
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:93
const CScript & m_witness_script
Definition: sign.cpp:201
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
An output of a transaction.
Definition: transaction.h:149
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:681
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:126
uint256 merkle_root
The Merkle root of the script tree (0 if no scripts).
bool m_bip341_taproot_ready
Whether the 5 fields above are initialized.
Definition: interpreter.h:163
std::vector< CTxOut > vout
Definition: transaction.h:380
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
uint256 ComputeTapleafHash(uint8_t leaf_version, Span< const unsigned char > script)
Compute the BIP341 tapleaf hash from leaf version & script.
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition: sign.h:74
bool m_codeseparator_pos_init
Whether m_codeseparator_pos is initialized.
Definition: interpreter.h:206
virtual bool GetKey(const CKeyID &address, CKey &key) const
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
Utility class to construct Taproot outputs from internal key and script tree.
std::vector< unsigned char > valtype
Definition: addresstype.cpp:18
Miniscript satisfier specific to P2WSH context.
Definition: sign.cpp:257
CScript scriptSig
Definition: transaction.h:70
constexpr C * begin() const noexcept
Definition: span.h:175
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:67
256-bit opaque blob.
Definition: uint256.h:201
miniscript::Availability SatRIPEMD160(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Definition: sign.cpp:241
TxoutType
Definition: solver.h:22
auto result
Definition: common-types.h:74
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
An interface to be implemented by keystores that support signing.
static opcodetype EncodeOP_N(int n)
Definition: script.h:524
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:610
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
XOnlyPubKey internal_key
The BIP341 internal key.
const miniscript::MiniscriptContext m_script_ctx
The context of the script we are satisfying (either P2WSH or Tapscript).
Definition: sign.cpp:203
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:109
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:172
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
bool empty() const
Definition: prevector.h:298
const SigningProvider & m_provider
Definition: sign.cpp:198
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int32_t nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:675
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
160-bit opaque blob.
Definition: uint256.h:189
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:263
std::vector< unsigned char > valtype
Definition: sign.cpp:21
std::optional< XOnlyPubKey > FromPKHBytes(I first, I last) const
Conversion from a raw xonly public key hash.
Definition: sign.cpp:306
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:502
iterator begin()
Definition: prevector.h:302
bool m_tapleaf_hash_init
Whether m_tapleaf_hash is initialized.
Definition: interpreter.h:201
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
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:601
A mutable version of CTransaction.
Definition: transaction.h:377
An encapsulated private key.
Definition: key.h:34
bool GetKeyByXOnly(const XOnlyPubKey &pubkey, CKey &key) const
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
bool CheckOlder(uint32_t value) const
Definition: sign.cpp:235
NodeRef< typename Ctx::Key > FromScript(const CScript &script, const Ctx &ctx)
Definition: miniscript.h:2645
const PrecomputedTransactionData * m_txdata
Definition: sign.h:46
std::vector< unsigned char > taproot_key_path_sig
Definition: sign.h:79
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:69
COutPoint prevout
Definition: transaction.h:69
std::vector< unsigned char > ToPKBytes(const Key &key) const
Conversion to raw public key.
Definition: sign.cpp:231
Only for Witness versions not already defined above.
miniscript::Availability SatHASH256(const std::vector< unsigned char > &hash, std::vector< unsigned char > &preimage) const
Definition: sign.cpp:244
virtual bool GetTaprootBuilder(const XOnlyPubKey &output_key, TaprootBuilder &builder) const
miniscript::Availability Sign(const XOnlyPubKey &key, std::vector< unsigned char > &sig) const
Satisfy a BIP340 signature check.
Definition: sign.cpp:312
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:766
const BaseSignatureCreator & m_creator
Definition: sign.cpp:200
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:72
bool witness
Stores whether the input this SigData corresponds to is a witness input.
Definition: sign.h:70
WshSatisfier(const SigningProvider &provider LIFETIMEBOUND, SignatureData &sig_data LIFETIMEBOUND, const BaseSignatureCreator &creator LIFETIMEBOUND, const CScript &witscript LIFETIMEBOUND)
Definition: sign.cpp:258
Miniscript satisfier specific to Tapscript context.
Definition: sign.cpp:286
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
virtual const BaseSignatureChecker & Checker() const =0
void Merge(TaprootSpendData other)
Merge other TaprootSpendData (for the same scriptPubKey) into this.
SigVersion
Definition: interpreter.h:190
unspendable OP_RETURN script that carries data
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:75