Bitcoin Core  0.18.99
P2P Digital Currency
standard.cpp
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 #include <script/standard.h>
7 
8 #include <crypto/sha256.h>
9 #include <pubkey.h>
10 #include <script/script.h>
11 
12 
13 typedef std::vector<unsigned char> valtype;
14 
15 bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER;
16 unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;
17 
18 CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {}
19 
20 ScriptHash::ScriptHash(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {}
21 
22 PKHash::PKHash(const CPubKey& pubkey) : uint160(pubkey.GetID()) {}
23 
25 {
26  CSHA256().Write(in.data(), in.size()).Finalize(begin());
27 }
28 
30 {
31  switch (t)
32  {
33  case TX_NONSTANDARD: return "nonstandard";
34  case TX_PUBKEY: return "pubkey";
35  case TX_PUBKEYHASH: return "pubkeyhash";
36  case TX_SCRIPTHASH: return "scripthash";
37  case TX_MULTISIG: return "multisig";
38  case TX_NULL_DATA: return "nulldata";
39  case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash";
40  case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash";
41  case TX_WITNESS_UNKNOWN: return "witness_unknown";
42  }
43  return nullptr;
44 }
45 
46 static bool MatchPayToPubkey(const CScript& script, valtype& pubkey)
47 {
48  if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) {
49  pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1);
50  return CPubKey::ValidSize(pubkey);
51  }
52  if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) {
53  pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1);
54  return CPubKey::ValidSize(pubkey);
55  }
56  return false;
57 }
58 
59 static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash)
60 {
61  if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) {
62  pubkeyhash = valtype(script.begin () + 3, script.begin() + 23);
63  return true;
64  }
65  return false;
66 }
67 
69 static constexpr bool IsSmallInteger(opcodetype opcode)
70 {
71  return opcode >= OP_1 && opcode <= OP_16;
72 }
73 
74 static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys)
75 {
76  opcodetype opcode;
77  valtype data;
78  CScript::const_iterator it = script.begin();
79  if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false;
80 
81  if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false;
82  required = CScript::DecodeOP_N(opcode);
83  while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) {
84  pubkeys.emplace_back(std::move(data));
85  }
86  if (!IsSmallInteger(opcode)) return false;
87  unsigned int keys = CScript::DecodeOP_N(opcode);
88  if (pubkeys.size() != keys || keys < required) return false;
89  return (it + 1 == script.end());
90 }
91 
92 txnouttype Solver(const CScript& scriptPubKey, std::vector<std::vector<unsigned char>>& vSolutionsRet)
93 {
94  vSolutionsRet.clear();
95 
96  // Shortcut for pay-to-script-hash, which are more constrained than the other types:
97  // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
98  if (scriptPubKey.IsPayToScriptHash())
99  {
100  std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
101  vSolutionsRet.push_back(hashBytes);
102  return TX_SCRIPTHASH;
103  }
104 
105  int witnessversion;
106  std::vector<unsigned char> witnessprogram;
107  if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
108  if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_KEYHASH_SIZE) {
109  vSolutionsRet.push_back(witnessprogram);
110  return TX_WITNESS_V0_KEYHASH;
111  }
112  if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
113  vSolutionsRet.push_back(witnessprogram);
115  }
116  if (witnessversion != 0) {
117  vSolutionsRet.push_back(std::vector<unsigned char>{(unsigned char)witnessversion});
118  vSolutionsRet.push_back(std::move(witnessprogram));
119  return TX_WITNESS_UNKNOWN;
120  }
121  return TX_NONSTANDARD;
122  }
123 
124  // Provably prunable, data-carrying output
125  //
126  // So long as script passes the IsUnspendable() test and all but the first
127  // byte passes the IsPushOnly() test we don't care what exactly is in the
128  // script.
129  if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
130  return TX_NULL_DATA;
131  }
132 
133  std::vector<unsigned char> data;
134  if (MatchPayToPubkey(scriptPubKey, data)) {
135  vSolutionsRet.push_back(std::move(data));
136  return TX_PUBKEY;
137  }
138 
139  if (MatchPayToPubkeyHash(scriptPubKey, data)) {
140  vSolutionsRet.push_back(std::move(data));
141  return TX_PUBKEYHASH;
142  }
143 
144  unsigned int required;
145  std::vector<std::vector<unsigned char>> keys;
146  if (MatchMultisig(scriptPubKey, required, keys)) {
147  vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16
148  vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end());
149  vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16
150  return TX_MULTISIG;
151  }
152 
153  vSolutionsRet.clear();
154  return TX_NONSTANDARD;
155 }
156 
157 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
158 {
159  std::vector<valtype> vSolutions;
160  txnouttype whichType = Solver(scriptPubKey, vSolutions);
161 
162  if (whichType == TX_PUBKEY) {
163  CPubKey pubKey(vSolutions[0]);
164  if (!pubKey.IsValid())
165  return false;
166 
167  addressRet = PKHash(pubKey);
168  return true;
169  }
170  else if (whichType == TX_PUBKEYHASH)
171  {
172  addressRet = PKHash(uint160(vSolutions[0]));
173  return true;
174  }
175  else if (whichType == TX_SCRIPTHASH)
176  {
177  addressRet = ScriptHash(uint160(vSolutions[0]));
178  return true;
179  } else if (whichType == TX_WITNESS_V0_KEYHASH) {
180  WitnessV0KeyHash hash;
181  std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin());
182  addressRet = hash;
183  return true;
184  } else if (whichType == TX_WITNESS_V0_SCRIPTHASH) {
185  WitnessV0ScriptHash hash;
186  std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin());
187  addressRet = hash;
188  return true;
189  } else if (whichType == TX_WITNESS_UNKNOWN) {
190  WitnessUnknown unk;
191  unk.version = vSolutions[0][0];
192  std::copy(vSolutions[1].begin(), vSolutions[1].end(), unk.program);
193  unk.length = vSolutions[1].size();
194  addressRet = unk;
195  return true;
196  }
197  // Multisig txns have more than one address...
198  return false;
199 }
200 
201 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
202 {
203  addressRet.clear();
204  std::vector<valtype> vSolutions;
205  typeRet = Solver(scriptPubKey, vSolutions);
206  if (typeRet == TX_NONSTANDARD) {
207  return false;
208  } else if (typeRet == TX_NULL_DATA) {
209  // This is data, not addresses
210  return false;
211  }
212 
213  if (typeRet == TX_MULTISIG)
214  {
215  nRequiredRet = vSolutions.front()[0];
216  for (unsigned int i = 1; i < vSolutions.size()-1; i++)
217  {
218  CPubKey pubKey(vSolutions[i]);
219  if (!pubKey.IsValid())
220  continue;
221 
222  CTxDestination address = PKHash(pubKey);
223  addressRet.push_back(address);
224  }
225 
226  if (addressRet.empty())
227  return false;
228  }
229  else
230  {
231  nRequiredRet = 1;
232  CTxDestination address;
233  if (!ExtractDestination(scriptPubKey, address))
234  return false;
235  addressRet.push_back(address);
236  }
237 
238  return true;
239 }
240 
241 namespace
242 {
243 class CScriptVisitor : public boost::static_visitor<bool>
244 {
245 private:
246  CScript *script;
247 public:
248  explicit CScriptVisitor(CScript *scriptin) { script = scriptin; }
249 
250  bool operator()(const CNoDestination &dest) const {
251  script->clear();
252  return false;
253  }
254 
255  bool operator()(const PKHash &keyID) const {
256  script->clear();
257  *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
258  return true;
259  }
260 
261  bool operator()(const ScriptHash &scriptID) const {
262  script->clear();
263  *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
264  return true;
265  }
266 
267  bool operator()(const WitnessV0KeyHash& id) const
268  {
269  script->clear();
270  *script << OP_0 << ToByteVector(id);
271  return true;
272  }
273 
274  bool operator()(const WitnessV0ScriptHash& id) const
275  {
276  script->clear();
277  *script << OP_0 << ToByteVector(id);
278  return true;
279  }
280 
281  bool operator()(const WitnessUnknown& id) const
282  {
283  script->clear();
284  *script << CScript::EncodeOP_N(id.version) << std::vector<unsigned char>(id.program, id.program + id.length);
285  return true;
286  }
287 };
288 } // namespace
289 
291 {
292  CScript script;
293 
294  boost::apply_visitor(CScriptVisitor(&script), dest);
295  return script;
296 }
297 
299 {
300  return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG;
301 }
302 
303 CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
304 {
305  CScript script;
306 
307  script << CScript::EncodeOP_N(nRequired);
308  for (const CPubKey& key : keys)
309  script << ToByteVector(key);
310  script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
311  return script;
312 }
313 
314 CScript GetScriptForWitness(const CScript& redeemscript)
315 {
316  std::vector<std::vector<unsigned char> > vSolutions;
317  txnouttype typ = Solver(redeemscript, vSolutions);
318  if (typ == TX_PUBKEY) {
319  return GetScriptForDestination(WitnessV0KeyHash(Hash160(vSolutions[0].begin(), vSolutions[0].end())));
320  } else if (typ == TX_PUBKEYHASH) {
321  return GetScriptForDestination(WitnessV0KeyHash(vSolutions[0]));
322  }
323  return GetScriptForDestination(WitnessV0ScriptHash(redeemscript));
324 }
325 
327  return dest.which() != 0;
328 }
uint8_t data[WIDTH]
Definition: uint256.h:22
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:648
static int DecodeOP_N(opcodetype opcode)
Encode/decode small integers:
Definition: script.h:509
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:157
unspendable OP_RETURN script that carries data
Definition: standard.h:64
T & back()
Definition: prevector.h:443
unsigned char program[40]
Definition: standard.h:112
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:497
ScriptHash()
Definition: standard.h:86
bool IsPayToScriptHash() const
Definition: script.cpp:196
static constexpr unsigned int PUBLIC_KEY_SIZE
secp256k1:
Definition: pubkey.h:36
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:326
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:15
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:298
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:92
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:215
unsigned int version
Definition: standard.h:110
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:94
CScriptID()
Definition: standard.h:25
unsigned int length
Definition: standard.h:111
uint160()
Definition: uint256.h:112
unsigned char * begin()
Definition: uint256.h:55
const unsigned char * begin() const
Definition: pubkey.h:111
Definition: script.h:80
unsigned char * end()
Definition: uint256.h:60
value_type * data()
Definition: prevector.h:518
static constexpr unsigned int COMPRESSED_PUBLIC_KEY_SIZE
Definition: pubkey.h:37
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Parse a standard scriptPubKey with one or more destination addresses.
Definition: standard.cpp:201
static bool ValidSize(const std::vector< unsigned char > &vch)
Definition: pubkey.h:74
iterator end()
Definition: prevector.h:287
opcodetype
Script opcodes.
Definition: script.h:54
Only for Witness versions not already defined above.
Definition: standard.h:67
const unsigned char * end() const
Definition: pubkey.h:112
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:108
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:231
bool IsValid() const
Definition: pubkey.h:171
An encapsulated public key.
Definition: pubkey.h:30
Definition: script.h:64
std::vector< unsigned char > valtype
Definition: standard.cpp:13
const char * GetTxnOutputType(txnouttype t)
Get the name of a txnouttype as a C string, or nullptr if unknown.
Definition: standard.cpp:29
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:290
txnouttype
Definition: standard.h:56
static opcodetype EncodeOP_N(int n)
Definition: script.h:516
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
160-bit opaque blob.
Definition: uint256.h:110
std::vector< unsigned char > valtype
Definition: interpreter.cpp:15
iterator begin()
Definition: prevector.h:285
size_type size() const
Definition: prevector.h:277
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: standard.cpp:303
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:139
A hasher class for SHA-256.
Definition: sha256.h:13
Definition: script.h:57
void clear()
Definition: script.h:560
CScript GetScriptForWitness(const CScript &redeemscript)
Generate a pay-to-witness script for the given redeem script.
Definition: standard.cpp:314
unsigned nMaxDatacarrierBytes
Maximum size of TX_NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:16
Definition: script.h:106
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:48
PKHash()
Definition: standard.h:78