Bitcoin Core  0.19.99
P2P Digital Currency
sign.h
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 http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_SCRIPT_SIGN_H
7 #define BITCOIN_SCRIPT_SIGN_H
8 
9 #include <boost/optional.hpp>
10 #include <hash.h>
11 #include <pubkey.h>
12 #include <script/interpreter.h>
13 #include <script/keyorigin.h>
14 #include <streams.h>
15 
16 class CKey;
17 class CKeyID;
18 class CScript;
19 class CScriptID;
20 class CTransaction;
21 class SigningProvider;
22 
23 struct CMutableTransaction;
24 
27 public:
28  virtual ~BaseSignatureCreator() {}
29  virtual const BaseSignatureChecker& Checker() const =0;
30 
32  virtual bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const =0;
33 };
34 
38  unsigned int nIn;
39  int nHashType;
42 
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 };
48 
53 
54 typedef std::pair<CPubKey, std::vector<unsigned char>> SigPair;
55 
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;
72 
74  explicit SignatureData(const CScript& script) : scriptSig(script) {}
75  void MergeSignatureData(SignatureData sigdata);
76 };
77 
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 }
86 
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 }
99 
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::PUBLIC_KEY_SIZE + 1 && key.size() != CPubKey::COMPRESSED_PUBLIC_KEY_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  }
116 
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  }
122 
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  }
130 
131  // Add to map
132  hd_keypaths.emplace(pubkey, std::move(keypath));
133 }
134 
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 }
151 
153 bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata);
154 
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);
158 
160 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout);
161 void UpdateInput(CTxIn& input, const SignatureData& data);
162 
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);
168 
170 bool IsSegWitOutput(const SigningProvider& provider, const CScript& script);
171 
172 #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:448
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:429
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:14
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:289
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:999
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:281
CScript scriptSig
The scriptSig of an input. Contains complete signatures or the traditional partial signatures format...
Definition: sign.h:62
static constexpr unsigned int PUBLIC_KEY_SIZE
secp256k1:
Definition: pubkey.h:36
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:426
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
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: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:970
void UnserializeFromVector(Stream &s, X &... args)
Definition: sign.h:89
static constexpr unsigned int COMPRESSED_PUBLIC_KEY_SIZE
Definition: pubkey.h:37
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:191
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:346
uint160 missing_redeem_script
ScriptID of the missing redeemScript (if any)
Definition: sign.h:70
An input of a transaction.
Definition: transaction.h:63
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:133
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:427
void SerializeMany(Stream &s)
Definition: serialize.h:958
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:498
256-bit opaque blob.
Definition: uint256.h:121
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:368
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:1011
160-bit opaque blob.
Definition: uint256.h:110
SignatureData()
Definition: sign.h:73
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
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
std::vector< uint32_t > path
Definition: keyorigin.h:15
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
SigVersion
Definition: interpreter.h:131