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