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