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