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