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 bilingual_str;
25 struct CMutableTransaction;
26 
29 public:
30  virtual ~BaseSignatureCreator() {}
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;
42  int nHashType;
46 
47 public:
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 
60 typedef 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.
65 struct SignatureData {
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) {}
84  void MergeSignatureData(SignatureData sigdata);
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.
89 template<typename Stream, typename... X>
90 void 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
97 template<typename Stream, typename... X>
98 void 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
110 template<typename Stream>
111 void 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
145 template<typename Stream>
146 void 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 
162 bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata);
163 
165 bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType);
166 bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType);
167 
169 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout);
170 void 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. */
176 bool IsSolvable(const SigningProvider& provider, const CScript& script);
177 
179 bool IsSegWitOutput(const SigningProvider& provider, const CScript& script);
180 
182 bool 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
SigVersion
SigVersion
Definition: interpreter.h:187
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:79
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:71
streams.h
SignatureData::MergeSignatureData
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:498
bilingual_str
Bilingual messages:
Definition: translation.h:16
CPubKey::SIZE
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:38
GenericTransactionSignatureChecker
Definition: interpreter.h:277
IsSolvable
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:581
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:579
MutableTransactionSignatureCreator
A signature creator for transactions.
Definition: sign.h:39
interpreter.h
MutableTransactionSignatureCreator::nIn
unsigned int nIn
Definition: sign.h:41
BaseSignatureChecker
Definition: interpreter.h:238
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:82
ReadCompactSize
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:282
pubkey.h
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
CScriptWitness
Definition: script.h:557
SigPair
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:60
MutableTransactionSignatureCreator::MutableTransactionSignatureCreator
MutableTransactionSignatureCreator(const CMutableTransaction *txToIn, unsigned int nInIn, const CAmount &amountIn, int nHashTypeIn)
Definition: sign.cpp:20
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:34
SignatureData
Definition: sign.h:65
MutableTransactionSignatureCreator::amount
CAmount amount
Definition: sign.h:43
CTxOut
An output of a transaction.
Definition: transaction.h:128
SignTransaction
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
TaprootSpendData
Definition: standard.h:207
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:514
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:69
UnserializeFromVector
void UnserializeFromVector(Stream &s, X &... args)
Definition: sign.h:98
SignatureData::scriptSig
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format.
Definition: sign.h:68
SignatureData::witness
bool witness
Stores whether the input this SigData corresponds to is a witness input.
Definition: sign.h:67
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:45
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:73
SignatureData::missing_sigs
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:78
SignatureData::witness_script
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:70
PrecomputedTransactionData
Definition: interpreter.h:150
SignatureData::taproot_key_path_sig
std::vector< unsigned char > taproot_key_path_sig
Definition: sign.h:75
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:66
uint256
256-bit opaque blob.
Definition: uint256.h:124
MutableTransactionSignatureCreator::nHashType
int nHashType
Definition: sign.h:42
DUMMY_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:578
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
DeserializeHDKeypaths
void DeserializeHDKeypaths(Stream &s, const std::vector< unsigned char > &key, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: sign.h:111
coins.h
SignatureData::tr_spenddata
TaprootSpendData tr_spenddata
Taproot spending data.
Definition: sign.h:72
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:40
SignatureData::missing_pubkeys
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:77
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:59
UpdateInput
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:492
BaseSignatureCreator::~BaseSignatureCreator
virtual ~BaseSignatureCreator()
Definition: sign.h:30
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:26
SignatureData::misc_pubkeys
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:74
X
#define X(name)
Definition: net.cpp:555
IsSegWitOutput
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
Definition: sign.cpp:600
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:331
CPubKey::IsFullyValid
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:292
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:50
SignatureData::SignatureData
SignatureData(const CScript &script)
Definition: sign.h:83
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:427
SignatureData::missing_witness_script
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:80
SerializeToVector
void SerializeToVector(Stream &s, const X &... args)
Definition: sign.h:90
keyorigin.h
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
BaseSignatureCreator
Interface for signature creators.
Definition: sign.h:28
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:76
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:44
KeyOriginInfo
Definition: keyorigin.h:11
SerializeHDKeypaths
void SerializeHDKeypaths(Stream &s, const std::map< CPubKey, KeyOriginInfo > &hd_keypaths, uint8_t type)
Definition: sign.h:146