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