16 typedef std::vector<unsigned char>
valtype;
19 : txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn,
MissingDataBehavior::
FAIL),
25 : txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn),
37 if (!provider.
GetKey(address, key))
51 if (!key.
Sign(hash, vchSig))
53 vchSig.push_back((
unsigned char)hashtype);
66 unsigned char b[33] = {0x02};
67 std::copy(pubkey.
begin(), pubkey.
end(), b + 1);
69 fullpubkey.
Set(b, b + 33);
70 CKeyID keyid = fullpubkey.GetID();
71 if (!provider.
GetKey(keyid, key)) {
73 fullpubkey.Set(b, b + 33);
74 CKeyID keyid = fullpubkey.GetID();
75 if (!provider.
GetKey(keyid, key))
return false;
90 if (!leaf_hash)
return false;
97 if (!key.
SignSchnorr(hash, sig, merkle_root,
nullptr))
return false;
121 const auto it = sigdata.
signatures.find(address);
123 pubkey = it->second.first;
129 pubkey = pk_it->second.first;
133 return provider.
GetPubKey(address, pubkey);
139 const auto it = sigdata.
signatures.find(keyid);
141 sig_out = it->second.second;
146 sigdata.
misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
148 if (creator.
CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
160 auto lookup_key = std::make_pair(pubkey, leaf_hash);
163 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));
204 std::vector<unsigned char> sig;
217 std::vector<std::vector<unsigned char>> smallest_result_stack;
219 const auto& [script, leaf_ver] = key;
220 std::vector<std::vector<unsigned char>> result_stack;
221 if (
SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
222 result_stack.emplace_back(std::begin(script), std::end(script));
223 result_stack.push_back(*control_blocks.begin());
224 if (smallest_result_stack.size() == 0 ||
226 smallest_result_stack = std::move(result_stack);
230 if (smallest_result_stack.size() != 0) {
231 result = std::move(smallest_result_stack);
250 std::vector<unsigned char> sig;
252 std::vector<valtype> vSolutions;
253 whichTypeRet =
Solver(scriptPubKey, vSolutions);
255 switch (whichTypeRet) {
261 if (!
CreateSig(creator, sigdata, provider, sig,
CPubKey(vSolutions[0]), scriptPubKey, sigversion))
return false;
262 ret.push_back(std::move(sig));
267 if (!
GetPubKey(provider, sigdata, keyID, pubkey)) {
272 if (!
CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion))
return false;
273 ret.push_back(std::move(sig));
280 ret.push_back(std::vector<unsigned char>(scriptRet.
begin(), scriptRet.
end()));
288 size_t required = vSolutions.front()[0];
290 for (
size_t i = 1; i < vSolutions.size() - 1; ++i) {
295 if (
CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
296 if (ret.size() < required + 1) {
297 ret.push_back(std::move(sig));
301 bool ok = ret.size() == required + 1;
302 for (
size_t i = 0; i + ret.size() < required + 1; ++i) {
308 ret.push_back(vSolutions[0]);
314 ret.push_back(std::vector<unsigned char>(scriptRet.
begin(), scriptRet.
end()));
330 for (
const valtype& v : values) {
333 }
else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
335 }
else if (v.size() == 1 && v[0] == 0x81) {
348 std::vector<valtype> result;
359 subscript =
CScript(result[0].begin(), result[0].end());
377 CScript witnessscript(result[0].begin(), result[0].end());
381 result.push_back(std::vector<unsigned char>(witnessscript.
begin(), witnessscript.
end()));
397 result.push_back(std::vector<unsigned char>(subscript.
begin(), subscript.
end()));
415 bool CheckECDSASignature(
const std::vector<unsigned char>& scriptSig,
const std::vector<unsigned char>& vchPubKey,
const CScript& scriptCode,
SigVersion sigversion)
const override 417 if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
428 std::vector<valtype> script;
429 std::vector<valtype> witness;
432 Stacks(
const Stacks&) =
delete;
433 explicit Stacks(
const SignatureData& data) : witness(data.scriptWitness.stack) {
450 SignatureExtractorChecker extractor_checker(data, tx_checker);
457 std::vector<std::vector<unsigned char>> solutions;
464 CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
466 next_script = std::move(redeem_script);
469 script_type =
Solver(next_script, solutions);
470 stack.script.pop_back();
474 CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
476 next_script = std::move(witness_script);
479 script_type =
Solver(next_script, solutions);
480 stack.witness.pop_back();
481 stack.script = std::move(stack.witness);
482 stack.witness.clear();
487 assert(solutions.size() > 1);
488 unsigned int num_pubkeys = solutions.size()-2;
489 unsigned int last_success_key = 0;
490 for (
const valtype& sig : stack.script) {
491 for (
unsigned int i = last_success_key; i < num_pubkeys; ++i) {
492 const valtype& pubkey = solutions[i+1];
494 if (data.
signatures.count(
CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
495 last_success_key = i + 1;
515 *
this = std::move(sigdata);
544 const CTxOut& txout = txFrom.
vout[txin.prevout.n];
546 return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
554 DummySignatureChecker() {}
555 bool CheckECDSASignature(
const std::vector<unsigned char>& scriptSig,
const std::vector<unsigned char>& vchPubKey,
const CScript& scriptCode,
SigVersion sigversion)
const override {
return true; }
558 const DummySignatureChecker DUMMY_CHECKER;
565 DummySignatureCreator(
char r_len,
char s_len) : m_r_len(r_len), m_s_len(s_len) {}
570 vchSig.assign(m_r_len + m_s_len + 7,
'\000');
572 vchSig[1] = m_r_len + m_s_len + 4;
576 vchSig[4 + m_r_len] = 0x02;
577 vchSig[5 + m_r_len] = m_s_len;
578 vchSig[6 + m_r_len] = 0x01;
584 sig.assign(64,
'\000');
619 std::vector<valtype> solutions;
620 auto whichtype =
Solver(script, solutions);
622 auto h160 =
uint160(solutions[0]);
641 std::vector<CTxOut> spent_outputs;
642 spent_outputs.resize(mtx.
vin.size());
643 bool have_all_spent_outputs =
true;
644 for (
unsigned int i = 0; i < mtx.
vin.size(); i++) {
646 auto coin = coins.find(txin.
prevout);
647 if (coin == coins.end() || coin->second.IsSpent()) {
648 have_all_spent_outputs =
false;
650 spent_outputs[i] =
CTxOut(coin->second.out.nValue, coin->second.out.scriptPubKey);
653 if (have_all_spent_outputs) {
654 txdata.
Init(txConst, std::move(spent_outputs),
true);
656 txdata.
Init(txConst, {},
true);
660 for (
unsigned int i = 0; i < mtx.
vin.size(); i++) {
662 auto coin = coins.find(txin.
prevout);
663 if (coin == coins.end() || coin->second.IsSpent()) {
664 input_errors[i] =
"Input not found or already spent";
667 const CScript& prevPubKey = coin->second.out.scriptPubKey;
668 const CAmount& amount = coin->second.out.nValue;
672 if (!fHashSingle || (i < mtx.
vout.size())) {
680 input_errors[i] =
"Missing amount";
688 input_errors[i] =
"Unable to sign input, invalid stack size (possibly missing key)";
691 input_errors[i] =
"CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)";
697 input_errors.erase(i);
700 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.
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 SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, int nHashType, std::map< int, std::string > &input_errors)
Sign the CMutableTransaction.
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.
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
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.
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.
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
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
A signature creator for transactions.
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)
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.
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)
const unsigned char * begin() const
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
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)
An encapsulated public key.
std::string ScriptErrorString(const ScriptError serror)
std::pair< CPubKey, std::vector< unsigned char > > SigPair
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, const ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
const std::vector< CTxOut > vout
const CHashWriter HASHER_TAPLEAF
Hasher with tag "TapLeaf" pre-fed to it.
Just act as if the signature was invalid.
static bool GetCScript(const SigningProvider &provider, const SignatureData &sigdata, const CScriptID &scriptid, CScript &script)
MissingDataBehavior
Enum to specify what *TransactionSignatureChecker's behavior should be when dealing with missing tran...
bool SignatureHashSchnorr(uint256 &hash_out, const ScriptExecutionData &execdata, const T &tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData &cache, MissingDataBehavior mdb)
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
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
bool IsSolvable(const SigningProvider &provider, const CScript &script)
CRIPEMD160 & Write(const unsigned char *data, size_t len)
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
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
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.
A writer stream (for serialization) that computes a 256-bit hash.
An encapsulated private key.
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. ...
MutableTransactionSignatureCreator(const CMutableTransaction *txToIn, unsigned int nInIn, const CAmount &amountIn, int nHashTypeIn=SIGHASH_ALL)
void Finalize(unsigned char hash[OUTPUT_SIZE])
const PrecomputedTransactionData * m_txdata
std::vector< unsigned char > taproot_key_path_sig
bool SignSchnorr(const uint256 &hash, Span< unsigned char > sig, const uint256 *merkle_root=nullptr, const uint256 *aux=nullptr) const
Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this, optionally tweaked b...
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.
const unsigned char * end() const
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 CMutableTransaction * txTo
std::vector< unsigned char > ToByteVector(const T &in)
Span< A > constexpr MakeSpan(A(&a)[N])
MakeSpan for arrays:
TaprootSpendData tr_spenddata
Taproot spending data.