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