19 typedef std::vector<unsigned char>
valtype;
22 : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount}, checker{&m_txto, nIn, amount,
MissingDataBehavior::FAIL},
28 : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount},
40 if (!provider.
GetKey(address, key))
54 if (!key.
Sign(hash, vchSig))
56 vchSig.push_back((
unsigned char)hashtype);
78 if (!leaf_hash)
return false;
86 if (!key.
SignSchnorr(hash, sig, merkle_root, {}))
return false;
110 const auto it = sigdata.
signatures.find(address);
112 pubkey = it->second.first;
118 pubkey = pk_it->second.first;
122 return provider.
GetPubKey(address, pubkey);
128 const auto it = sigdata.
signatures.find(keyid);
130 sig_out = it->second.second;
135 sigdata.
misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
137 if (creator.
CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
153 sigdata.
taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
155 it->second.first.insert(leaf_hash);
159 auto lookup_key = std::make_pair(pubkey, leaf_hash);
162 sig_out = it->second;
165 if (creator.
CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash,
nullptr, sigversion)) {
181 if (script.
size() == 34 && script[33] ==
OP_CHECKSIG && script[0] == 0x20) {
183 std::vector<unsigned char> sig;
185 result =
Vector(std::move(sig));
193 std::vector<std::vector<unsigned char>> sigs;
195 for (
size_t i = 0; i < match->second.size(); ++i) {
197 std::vector<unsigned char> sig;
199 if (good_sig && good_sigs < match->first) {
201 sigs.push_back(std::move(sig));
206 if (good_sigs == match->first) {
207 result = std::move(sigs);
239 std::vector<unsigned char> sig;
257 std::vector<std::vector<unsigned char>> smallest_result_stack;
259 const auto& [script, leaf_ver] = key;
260 std::vector<std::vector<unsigned char>> result_stack;
261 if (
SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
262 result_stack.emplace_back(std::begin(script), std::end(script));
263 result_stack.push_back(*control_blocks.begin());
264 if (smallest_result_stack.size() == 0 ||
266 smallest_result_stack = std::move(result_stack);
270 if (smallest_result_stack.size() != 0) {
271 result = std::move(smallest_result_stack);
290 std::vector<unsigned char> sig;
292 std::vector<valtype> vSolutions;
293 whichTypeRet =
Solver(scriptPubKey, vSolutions);
295 switch (whichTypeRet) {
301 if (!
CreateSig(creator, sigdata, provider, sig,
CPubKey(vSolutions[0]), scriptPubKey, sigversion))
return false;
302 ret.push_back(std::move(sig));
307 if (!
GetPubKey(provider, sigdata, keyID, pubkey)) {
312 if (!
CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion))
return false;
313 ret.push_back(std::move(sig));
320 ret.push_back(std::vector<unsigned char>(scriptRet.
begin(), scriptRet.
end()));
328 size_t required = vSolutions.front()[0];
330 for (
size_t i = 1; i < vSolutions.size() - 1; ++i) {
335 if (
CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
336 if (
ret.size() < required + 1) {
337 ret.push_back(std::move(sig));
341 bool ok =
ret.size() == required + 1;
342 for (
size_t i = 0; i +
ret.size() < required + 1; ++i) {
348 ret.push_back(vSolutions[0]);
354 ret.push_back(std::vector<unsigned char>(scriptRet.
begin(), scriptRet.
end()));
373 }
else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
375 }
else if (v.size() == 1 && v[0] == 0x81) {
388 std::vector<valtype> result;
399 subscript =
CScript(result[0].begin(), result[0].end());
417 CScript witnessscript(result[0].begin(), result[0].end());
421 result.push_back(std::vector<unsigned char>(witnessscript.
begin(), witnessscript.
end()));
437 result.push_back(std::vector<unsigned char>(subscript.
begin(), subscript.
end()));
455 bool CheckECDSASignature(
const std::vector<unsigned char>& scriptSig,
const std::vector<unsigned char>& vchPubKey,
const CScript& scriptCode,
SigVersion sigversion)
const override 457 if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
468 std::vector<valtype> script;
469 std::vector<valtype> witness;
472 Stacks(
const Stacks&) =
delete;
473 explicit Stacks(
const SignatureData& data) : witness(data.scriptWitness.stack) {
490 SignatureExtractorChecker extractor_checker(data, tx_checker);
497 std::vector<std::vector<unsigned char>> solutions;
504 CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
506 next_script = std::move(redeem_script);
509 script_type =
Solver(next_script, solutions);
510 stack.script.pop_back();
514 CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
516 next_script = std::move(witness_script);
519 script_type =
Solver(next_script, solutions);
520 stack.witness.pop_back();
521 stack.script = std::move(stack.witness);
522 stack.witness.clear();
527 assert(solutions.size() > 1);
528 unsigned int num_pubkeys = solutions.size()-2;
529 unsigned int last_success_key = 0;
530 for (
const valtype& sig : stack.script) {
531 for (
unsigned int i = last_success_key; i < num_pubkeys; ++i) {
532 const valtype& pubkey = solutions[i+1];
534 if (data.
signatures.count(
CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
535 last_success_key = i + 1;
555 *
this = std::move(sigdata);
584 const CTxOut& txout = txFrom.
vout[txin.prevout.n];
586 return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
594 DummySignatureChecker() =
default;
595 bool CheckECDSASignature(
const std::vector<unsigned char>& scriptSig,
const std::vector<unsigned char>& vchPubKey,
const CScript& scriptCode,
SigVersion sigversion)
const override {
return true; }
608 DummySignatureCreator(
char r_len,
char s_len) : m_r_len(r_len), m_s_len(s_len) {}
613 vchSig.assign(m_r_len + m_s_len + 7,
'\000');
615 vchSig[1] = m_r_len + m_s_len + 4;
619 vchSig[4 + m_r_len] = 0x02;
620 vchSig[5 + m_r_len] = m_s_len;
621 vchSig[6 + m_r_len] = 0x01;
627 sig.assign(64,
'\000');
643 std::vector<valtype> solutions;
644 auto whichtype =
Solver(script, solutions);
646 auto h160 =
uint160(solutions[0]);
665 std::vector<CTxOut> spent_outputs;
666 for (
unsigned int i = 0; i < mtx.
vin.size(); ++i) {
668 auto coin = coins.find(txin.
prevout);
669 if (coin == coins.end() || coin->second.IsSpent()) {
670 txdata.
Init(txConst, {},
true);
673 spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
676 if (spent_outputs.size() == mtx.
vin.size()) {
677 txdata.
Init(txConst, std::move(spent_outputs),
true);
681 for (
unsigned int i = 0; i < mtx.
vin.size(); ++i) {
683 auto coin = coins.find(txin.
prevout);
684 if (coin == coins.end() || coin->second.IsSpent()) {
685 input_errors[i] =
_(
"Input not found or already spent");
688 const CScript& prevPubKey = coin->second.out.scriptPubKey;
689 const CAmount& amount = coin->second.out.nValue;
693 if (!fHashSingle || (i < mtx.
vout.size())) {
701 input_errors[i] =
_(
"Missing amount");
709 input_errors[i] =
Untranslated(
"Unable to sign input, invalid stack size (possibly missing key)");
712 input_errors[i] =
Untranslated(
"CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
718 input_errors.erase(i);
721 return input_errors.empty();
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Witness v0 (P2WPKH and P2WSH); see BIP 141.
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341...
static bool SignTaprootScript(const SigningProvider &provider, const BaseSignatureCreator &creator, SignatureData &sigdata, int leaf_version, const CScript &script, std::vector< valtype > &result)
bool SignatureHashSchnorr(uint256 &hash_out, ScriptExecutionData &execdata, const T &tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData &cache, MissingDataBehavior mdb)
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > taproot_misc_pubkeys
Miscellaneous Taproot pubkeys involved in this input along with their leaf script hashes and key orig...
enum ScriptError_t ScriptError
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
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.
const CMutableTransaction & m_txto
bool IsPayToScriptHash() const
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...
CScriptWitness scriptWitness
Only serialized through CTransaction.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
bool m_annex_present
Whether an annex is present.
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
bool MoneyRange(const CAmount &nValue)
Interface for signature creators.
static CScript PushAll(const std::vector< valtype > &values)
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
std::vector< std::vector< unsigned char > > stack
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, script path spending, leaf version 0xc0; see...
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
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)
A signature creator for transactions.
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...
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
uint32_t m_codeseparator_pos
Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed).
unspendable OP_RETURN script that carries data
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
const BaseSignatureChecker & DUMMY_CHECKER
A signature checker that accepts all signatures.
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.
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType)
Produce a script signature for a transaction.
size_t GetSerializeSize(const T &t, int nVersion=0)
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > taproot_script_sigs
Schnorr signature for key path spending.
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.
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.
int64_t CAmount
Amount in satoshis (Can be negative)
bool Sign(const uint256 &hash, std::vector< unsigned char > &vchSig, bool grind=true, uint32_t test_case=0) const
Create a DER-serialized signature.
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.
uint256 m_tapleaf_hash
The tapleaf hash.
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
static bool SignTaproot(const SigningProvider &provider, const BaseSignatureCreator &creator, const WitnessV1Taproot &output, SignatureData &sigdata, std::vector< valtype > &result)
An input of a transaction.
virtual bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const
bilingual_str _(const char *psz)
Translation function.
virtual bool CreateSchnorrSig(const SigningProvider &provider, std::vector< unsigned char > &sig, const XOnlyPubKey &pubkey, const uint256 *leaf_hash, const uint256 *merkle_root, SigVersion sigversion) const =0
A writer stream (for serialization) that computes a 256-bit hash.
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)
An encapsulated public key.
std::optional< TaprootBuilder > tr_builder
Taproot tree used to build tr_spenddata.
std::string ScriptErrorString(const ScriptError serror)
std::pair< CPubKey, std::vector< unsigned char > > SigPair
const std::vector< CTxOut > vout
Just act as if the signature was invalid.
static bool GetCScript(const SigningProvider &provider, const SignatureData &sigdata, const CScriptID &scriptid, CScript &script)
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
An output of a transaction.
void MergeSignatureData(SignatureData sigdata)
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
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.
std::vector< CTxOut > vout
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
bool m_codeseparator_pos_init
Whether m_codeseparator_pos is initialized.
virtual bool GetKey(const CKeyID &address, CKey &key) const
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Utility class to construct Taproot outputs from internal key and script tree.
std::vector< unsigned char > ToByteVector(const T &in)
std::map< std::pair< CScript, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > scripts
Map from (script, leaf_version) to (sets of) control blocks.
An interface to be implemented by keystores that support signing.
static opcodetype EncodeOP_N(int n)
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Serialized script, used inside transaction inputs and outputs.
XOnlyPubKey internal_key
The BIP341 internal key.
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
static const int PROTOCOL_VERSION
network protocol versioning
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
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
std::optional< std::pair< int, std::vector< Span< const unsigned char > > > > MatchMultiA(const CScript &script)
A reference to a CKey: the Hash160 of its serialized public key.
void UpdateInput(CTxIn &input, const SignatureData &data)
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
Only for Witness versions not already defined above.
static bool CreateTaprootScriptSig(const BaseSignatureCreator &creator, SignatureData &sigdata, const SigningProvider &provider, std::vector< unsigned char > &sig_out, const XOnlyPubKey &pubkey, const uint256 &leaf_hash, SigVersion sigversion)
std::vector< unsigned char > valtype
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
std::vector< unsigned char > valtype
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
bool m_tapleaf_hash_init
Whether m_tapleaf_hash is initialized.
A reference to a CScript: the Hash160 of its serialization (see script.h)
A mutable version of CTransaction.
An encapsulated private key.
bool GetKeyByXOnly(const XOnlyPubKey &pubkey, CKey &key) const
A Span is an object that can refer to a contiguous sequence of objects.
The basic transaction that is broadcasted on the network and contained in blocks. ...
void Finalize(unsigned char hash[OUTPUT_SIZE])
const PrecomputedTransactionData * m_txdata
std::vector< unsigned char > taproot_key_path_sig
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.
virtual bool GetTaprootBuilder(const XOnlyPubKey &output_key, TaprootBuilder &builder) const
bool SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, int nHashType, std::map< int, bilingual_str > &input_errors)
Sign the CMutableTransaction.
CScript redeem_script
The redeemScript (if any) for the input.
bool witness
Stores whether the input this SigData corresponds to is a witness input.
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
A hasher class for RIPEMD-160.
virtual const BaseSignatureChecker & Checker() const =0
void Merge(TaprootSpendData other)
Merge other TaprootSpendData (for the same scriptPubKey) into this.
const HashWriter HASHER_TAPLEAF
Hasher with tag "TapLeaf" pre-fed to it.
TaprootSpendData tr_spenddata
Taproot spending data.