Bitcoin Core 22.99.0
P2P Digital Currency
sign.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_SCRIPT_SIGN_H
7#define BITCOIN_SCRIPT_SIGN_H
8
9#include <coins.h>
10#include <hash.h>
11#include <pubkey.h>
12#include <script/interpreter.h>
13#include <script/keyorigin.h>
14#include <script/standard.h>
15#include <span.h>
16#include <streams.h>
17
18class CKey;
19class CKeyID;
20class CScript;
21class CTransaction;
22class SigningProvider;
23
24struct bilingual_str;
26
29public:
31 virtual const BaseSignatureChecker& Checker() const =0;
32
34 virtual bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const =0;
35 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;
36};
37
41 unsigned int nIn;
46
47public:
48 MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn);
49 MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData* txdata, int nHashTypeIn);
50 const BaseSignatureChecker& Checker() const override { return checker; }
51 bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override;
52 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;
53};
54
59
60typedef std::pair<CPubKey, std::vector<unsigned char>> SigPair;
61
62// This struct contains information from a transaction input and also contains signatures for that input.
63// The information contained here can be used to create a signature and is also filled by ProduceSignature
64// in order to construct final scriptSigs and scriptWitnesses.
66 bool complete = false;
67 bool witness = false;
73 std::map<CKeyID, SigPair> signatures;
74 std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> misc_pubkeys;
75 std::vector<unsigned char> taproot_key_path_sig;
76 std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> taproot_script_sigs;
77 std::vector<CKeyID> missing_pubkeys;
78 std::vector<CKeyID> missing_sigs;
81
83 explicit SignatureData(const CScript& script) : scriptSig(script) {}
85};
86
87// Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
88// The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
89template<typename Stream, typename... X>
90void SerializeToVector(Stream& s, const X&... args)
91{
92 WriteCompactSize(s, GetSerializeSizeMany(s.GetVersion(), args...));
93 SerializeMany(s, args...);
94}
95
96// Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
97template<typename Stream, typename... X>
98void UnserializeFromVector(Stream& s, X&... args)
99{
100 size_t expected_size = ReadCompactSize(s);
101 size_t remaining_before = s.size();
102 UnserializeMany(s, args...);
103 size_t remaining_after = s.size();
104 if (remaining_after + expected_size != remaining_before) {
105 throw std::ios_base::failure("Size of value was not the stated size");
106 }
107}
108
109// Deserialize HD keypaths into a map
110template<typename Stream>
111void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
112{
113 // Make sure that the key is the size of pubkey + 1
114 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
115 throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
116 }
117 // Read in the pubkey from key
118 CPubKey pubkey(key.begin() + 1, key.end());
119 if (!pubkey.IsFullyValid()) {
120 throw std::ios_base::failure("Invalid pubkey");
121 }
122 if (hd_keypaths.count(pubkey) > 0) {
123 throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
124 }
125
126 // Read in key path
127 uint64_t value_len = ReadCompactSize(s);
128 if (value_len % 4 || value_len == 0) {
129 throw std::ios_base::failure("Invalid length for HD key path");
130 }
131
132 KeyOriginInfo keypath;
133 s >> keypath.fingerprint;
134 for (unsigned int i = 4; i < value_len; i += sizeof(uint32_t)) {
135 uint32_t index;
136 s >> index;
137 keypath.path.push_back(index);
138 }
139
140 // Add to map
141 hd_keypaths.emplace(pubkey, std::move(keypath));
142}
143
144// Serialize HD keypaths to a stream from a map
145template<typename Stream>
146void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, uint8_t type)
147{
148 for (auto keypath_pair : hd_keypaths) {
149 if (!keypath_pair.first.IsValid()) {
150 throw std::ios_base::failure("Invalid CPubKey being serialized");
151 }
152 SerializeToVector(s, type, MakeSpan(keypath_pair.first));
153 WriteCompactSize(s, (keypath_pair.second.path.size() + 1) * sizeof(uint32_t));
154 s << keypath_pair.second.fingerprint;
155 for (const auto& path : keypath_pair.second.path) {
156 s << path;
157 }
158 }
159}
160
162bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata);
163
165bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType);
166bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType);
167
169SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout);
170void UpdateInput(CTxIn& input, const SignatureData& data);
171
172/* Check whether we know how to sign for an output like this, assuming we
173 * have all private keys. While this function does not need private keys, the passed
174 * provider is used to look up public keys and redeemscripts by hash.
175 * Solvability is unrelated to whether we consider this output to be ours. */
176bool IsSolvable(const SigningProvider& provider, const CScript& script);
177
179bool IsSegWitOutput(const SigningProvider& provider, const CScript& script);
180
182bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* provider, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors);
183
184#endif // BITCOIN_SCRIPT_SIGN_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Interface for signature creators.
Definition: sign.h:28
virtual const BaseSignatureChecker & Checker() const =0
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 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.
virtual ~BaseSignatureCreator()
Definition: sign.h:30
An encapsulated private key.
Definition: key.h:27
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
An encapsulated public key.
Definition: pubkey.h:33
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:39
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:38
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:292
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
An input of a transaction.
Definition: transaction.h:66
An output of a transaction.
Definition: transaction.h:129
A signature creator for transactions.
Definition: sign.h:39
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:59
const BaseSignatureChecker & Checker() const override
Definition: sign.h:50
MutableTransactionSignatureCreator(const CMutableTransaction *txToIn, unsigned int nInIn, const CAmount &amountIn, int nHashTypeIn)
Definition: sign.cpp:20
const CMutableTransaction * txTo
Definition: sign.h:40
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:34
const PrecomputedTransactionData * m_txdata
Definition: sign.h:45
const MutableTransactionSignatureChecker checker
Definition: sign.h:44
An interface to be implemented by keystores that support signing.
160-bit opaque blob.
Definition: uint256.h:113
256-bit opaque blob.
Definition: uint256.h:124
SigVersion
Definition: interpreter.h:188
static unsigned const char sighash[]
Definition: sighash.json.h:2
#define X(name)
Definition: net.cpp:574
void SerializeMany(Stream &s)
Definition: serialize.h:1011
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:282
void UnserializeMany(Stream &s)
Definition: serialize.h:1023
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:1086
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1074
void SerializeToVector(Stream &s, const X &... args)
Definition: sign.h:90
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:492
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
Definition: sign.cpp:600
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:60
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:581
bool SignSignature(const SigningProvider &provider, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType)
Produce a script signature for a transaction.
Definition: sign.cpp:514
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:579
void SerializeHDKeypaths(Stream &s, const std::map< CPubKey, KeyOriginInfo > &hd_keypaths, uint8_t type)
Definition: sign.h:146
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:427
void UnserializeFromVector(Stream &s, X &... args)
Definition: sign.h:98
void DeserializeHDKeypaths(Stream &s, const std::vector< unsigned char > &key, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: sign.h:111
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:578
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &scriptPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:331
bool SignTransaction(CMutableTransaction &mtx, const SigningProvider *provider, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors)
Sign the CMutableTransaction.
Definition: sign.cpp:619
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:222
A mutable version of CTransaction.
Definition: transaction.h:345
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
std::vector< uint32_t > path
Definition: keyorigin.h:14
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:79
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:78
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:498
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:73
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:72
SignatureData()
Definition: sign.h:82
bool witness
Stores whether the input this SigData corresponds to is a witness input.
Definition: sign.h:67
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:74
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format.
Definition: sign.h:68
std::vector< unsigned char > taproot_key_path_sig
Definition: sign.h:75
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > taproot_script_sigs
Schnorr signature for key path spending.
Definition: sign.h:76
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:69
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:80
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:77
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:70
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition: sign.h:71
SignatureData(const CScript &script)
Definition: sign.h:83
bool complete
Stores whether the scriptSig and scriptWitness are complete.
Definition: sign.h:66
Bilingual messages:
Definition: translation.h:16