Bitcoin Core  0.18.99
P2P Digital Currency
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or
9 #include <boost/optional.hpp>
10 #include <hash.h>
11 #include <pubkey.h>
12 #include <script/interpreter.h>
13 #include <streams.h>
15 class CKey;
16 class CKeyID;
17 class CScript;
18 class CScriptID;
19 class CTransaction;
21 struct CMutableTransaction;
24 {
25  unsigned char fingerprint[4];
26  std::vector<uint32_t> path;
28  friend bool operator==(const KeyOriginInfo& a, const KeyOriginInfo& b)
29  {
30  return std::equal(std::begin(a.fingerprint), std::end(a.fingerprint), std::begin(b.fingerprint)) && a.path == b.path;
31  }
34  template <typename Stream, typename Operation>
35  inline void SerializationOp(Stream& s, Operation ser_action)
36  {
37  READWRITE(fingerprint);
38  READWRITE(path);
39  }
41  void clear()
42  {
43  memset(fingerprint, 0, 4);
44  path.clear();
45  }
46 };
50 {
51 public:
52  virtual ~SigningProvider() {}
53  virtual bool GetCScript(const CScriptID &scriptid, CScript& script) const { return false; }
54  virtual bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const { return false; }
55  virtual bool GetKey(const CKeyID &address, CKey& key) const { return false; }
56  virtual bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const { return false; }
57 };
62 {
63 private:
64  const bool m_hide_secret;
65  const bool m_hide_origin;
68 public:
69  HidingSigningProvider(const SigningProvider* provider, bool hide_secret, bool hide_origin) : m_hide_secret(hide_secret), m_hide_origin(hide_origin), m_provider(provider) {}
70  bool GetCScript(const CScriptID& scriptid, CScript& script) const override;
71  bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;
72  bool GetKey(const CKeyID& keyid, CKey& key) const override;
73  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
74 };
76 struct FlatSigningProvider final : public SigningProvider
77 {
78  std::map<CScriptID, CScript> scripts;
79  std::map<CKeyID, CPubKey> pubkeys;
80  std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> origins;
81  std::map<CKeyID, CKey> keys;
83  bool GetCScript(const CScriptID& scriptid, CScript& script) const override;
84  bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;
85  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
86  bool GetKey(const CKeyID& keyid, CKey& key) const override;
87 };
93 public:
94  virtual ~BaseSignatureCreator() {}
95  virtual const BaseSignatureChecker& Checker() const =0;
98  virtual bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const =0;
99 };
104  unsigned int nIn;
109 public:
110  MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn = SIGHASH_ALL);
111  const BaseSignatureChecker& Checker() const override { return checker; }
112  bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override;
113 };
120 typedef std::pair<CPubKey, std::vector<unsigned char>> SigPair;
122 // This struct contains information from a transaction input and also contains signatures for that input.
123 // The information contained here can be used to create a signature and is also filled by ProduceSignature
124 // in order to construct final scriptSigs and scriptWitnesses.
126  bool complete = false;
127  bool witness = false;
132  std::map<CKeyID, SigPair> signatures;
133  std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> misc_pubkeys;
134  std::vector<CKeyID> missing_pubkeys;
135  std::vector<CKeyID> missing_sigs;
140  explicit SignatureData(const CScript& script) : scriptSig(script) {}
141  void MergeSignatureData(SignatureData sigdata);
142 };
144 // Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
145 // The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
146 template<typename Stream, typename... X>
147 void SerializeToVector(Stream& s, const X&... args)
148 {
149  WriteCompactSize(s, GetSerializeSizeMany(s.GetVersion(), args...));
150  SerializeMany(s, args...);
151 }
153 // Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
154 template<typename Stream, typename... X>
155 void UnserializeFromVector(Stream& s, X&... args)
156 {
157  size_t expected_size = ReadCompactSize(s);
158  size_t remaining_before = s.size();
159  UnserializeMany(s, args...);
160  size_t remaining_after = s.size();
161  if (remaining_after + expected_size != remaining_before) {
162  throw std::ios_base::failure("Size of value was not the stated size");
163  }
164 }
166 // Deserialize HD keypaths into a map
167 template<typename Stream>
168 void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
169 {
170  // Make sure that the key is the size of pubkey + 1
171  if (key.size() != CPubKey::PUBLIC_KEY_SIZE + 1 && key.size() != CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1) {
172  throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
173  }
174  // Read in the pubkey from key
175  CPubKey pubkey(key.begin() + 1, key.end());
176  if (!pubkey.IsFullyValid()) {
177  throw std::ios_base::failure("Invalid pubkey");
178  }
179  if (hd_keypaths.count(pubkey) > 0) {
180  throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
181  }
183  // Read in key path
184  uint64_t value_len = ReadCompactSize(s);
185  if (value_len % 4 || value_len == 0) {
186  throw std::ios_base::failure("Invalid length for HD key path");
187  }
189  KeyOriginInfo keypath;
190  s >> keypath.fingerprint;
191  for (unsigned int i = 4; i < value_len; i += sizeof(uint32_t)) {
192  uint32_t index;
193  s >> index;
194  keypath.path.push_back(index);
195  }
197  // Add to map
198  hd_keypaths.emplace(pubkey, std::move(keypath));
199 }
201 // Serialize HD keypaths to a stream from a map
202 template<typename Stream>
203 void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, uint8_t type)
204 {
205  for (auto keypath_pair : hd_keypaths) {
206  if (!keypath_pair.first.IsValid()) {
207  throw std::ios_base::failure("Invalid CPubKey being serialized");
208  }
209  SerializeToVector(s, type, MakeSpan(keypath_pair.first));
210  WriteCompactSize(s, (keypath_pair.second.path.size() + 1) * sizeof(uint32_t));
211  s << keypath_pair.second.fingerprint;
212  for (const auto& path : keypath_pair.second.path) {
213  s << path;
214  }
215  }
216 }
219 bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata);
222 bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType);
223 bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType);
226 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout);
227 void UpdateInput(CTxIn& input, const SignatureData& data);
229 /* Check whether we know how to sign for an output like this, assuming we
230  * have all private keys. While this function does not need private keys, the passed
231  * provider is used to look up public keys and redeemscripts by hash.
232  * Solvability is unrelated to whether we consider this output to be ours. */
233 bool IsSolvable(const SigningProvider& provider, const CScript& script);
virtual ~SigningProvider()
Definition: sign.h:52
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:443
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: sign.h:25
CScript witness_script
The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs.
Definition: sign.h:130
void SerializeToVector(Stream &s, const X &... args)
Definition: sign.h:147
const SigningProvider * m_provider
Definition: sign.h:66
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:289
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:986
const MutableTransactionSignatureChecker checker
Definition: sign.h:107
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:283
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format...
Definition: sign.h:128
std::map< CKeyID, CKey > keys
Definition: sign.h:81
static constexpr unsigned int PUBLIC_KEY_SIZE
Definition: pubkey.h:36
std::vector< CKeyID > missing_sigs
KeyIDs of pubkeys for signatures which could not be found.
Definition: sign.h:135
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:439
Interface for signature creators.
Definition: sign.h:92
std::vector< CKeyID > missing_pubkeys
KeyIDs of pubkeys which could not be found.
Definition: sign.h:134
const BaseSignatureChecker & Checker() const override
Definition: sign.h:111
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
Definition: sign.h:80
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > misc_pubkeys
Definition: sign.h:133
A signature creator for transactions.
Definition: sign.h:102
constexpr Span< A > MakeSpan(A(&a)[N])
Create a span to a container exposing data() and size().
Definition: span.h:55
uint256 missing_witness_script
SHA256 of the missing witnessScript (if any)
Definition: sign.h:137
void DeserializeHDKeypaths(Stream &s, const std::vector< unsigned char > &key, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: sign.h:168
void UnserializeMany(Stream &s)
Definition: serialize.h:957
void UnserializeFromVector(Stream &s, X &... args)
Definition: sign.h:155
static constexpr unsigned int COMPRESSED_PUBLIC_KEY_SIZE
Definition: pubkey.h:37
void clear()
Definition: sign.h:41
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:190
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
SignatureData(const CScript &script)
Definition: sign.h:140
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:348
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:136
const bool m_hide_origin
Definition: sign.h:65
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
Definition: sign.h:54
std::map< CScriptID, CScript > scripts
Definition: sign.h:78
An input of a transaction.
Definition: transaction.h:63
virtual bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const
Definition: sign.h:56
An encapsulated public key.
Definition: pubkey.h:30
std::map< CKeyID, CPubKey > pubkeys
Definition: sign.h:79
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:120
Definition: sign.h:33
An output of a transaction.
Definition: transaction.h:133
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:440
void SerializeMany(Stream &s)
Definition: serialize.h:945
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
Definition: sign.h:53
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition: sign.h:131
virtual bool GetKey(const CKeyID &address, CKey &key) const
Definition: sign.h:55
const SigningProvider & DUMMY_SIGNING_PROVIDER
Definition: sign.cpp:441
const bool m_hide_secret
Definition: sign.h:64
#define X(name)
Definition: net.cpp:493
friend bool operator==(const KeyOriginInfo &a, const KeyOriginInfo &b)
Definition: sign.h:28
256-bit opaque blob.
Definition: uint256.h:121
An interface to be implemented by keystores that support signing.
Definition: sign.h:49
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:370
void SerializeHDKeypaths(Stream &s, const std::map< CPubKey, KeyOriginInfo > &hd_keypaths, uint8_t type)
Definition: sign.h:203
virtual ~BaseSignatureCreator()
Definition: sign.h:94
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:998
160-bit opaque blob.
Definition: uint256.h:110
Definition: sign.h:139
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:22
A mutable version of CTransaction.
Definition: transaction.h:366
HidingSigningProvider(const SigningProvider *provider, bool hide_secret, bool hide_origin)
Definition: sign.h:69
An encapsulated private key.
Definition: key.h:27
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
#define READWRITE(...)
Definition: serialize.h:184
std::vector< uint32_t > path
Definition: sign.h:26
CScript redeem_script
The redeemScript (if any) for the input.
Definition: sign.h:129
FlatSigningProvider Merge(const FlatSigningProvider &a, const FlatSigningProvider &b)
Definition: sign.cpp:495
void SerializationOp(Stream &s, Operation ser_action)
Definition: sign.h:35
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:132
const CMutableTransaction * txTo
Definition: sign.h:103
Definition: interpreter.h:131