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