Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules
core_read.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <core_io.h>
6 
7 #include <primitives/block.h>
9 #include <script/script.h>
10 #include <script/sign.h>
11 #include <serialize.h>
12 #include <streams.h>
13 #include <univalue.h>
14 #include <util/strencodings.h>
15 #include <version.h>
16 
17 #include <boost/algorithm/string/classification.hpp>
18 #include <boost/algorithm/string/replace.hpp>
19 #include <boost/algorithm/string/split.hpp>
20 
21 #include <algorithm>
22 #include <string>
23 
24 CScript ParseScript(const std::string& s)
25 {
26  CScript result;
27 
28  static std::map<std::string, opcodetype> mapOpNames;
29 
30  if (mapOpNames.empty())
31  {
32  for (unsigned int op = 0; op <= MAX_OPCODE; op++)
33  {
34  // Allow OP_RESERVED to get into mapOpNames
35  if (op < OP_NOP && op != OP_RESERVED)
36  continue;
37 
38  std::string strName = GetOpName(static_cast<opcodetype>(op));
39  if (strName == "OP_UNKNOWN")
40  continue;
41  mapOpNames[strName] = static_cast<opcodetype>(op);
42  // Convenience: OP_ADD and just ADD are both recognized:
43  boost::algorithm::replace_first(strName, "OP_", "");
44  mapOpNames[strName] = static_cast<opcodetype>(op);
45  }
46  }
47 
48  std::vector<std::string> words;
49  boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
50 
51  for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
52  {
53  if (w->empty())
54  {
55  // Empty string, ignore. (boost::split given '' will return one word)
56  }
57  else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
58  (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
59  {
60  // Number
61  int64_t n = atoi64(*w);
62 
63  //limit the range of numbers ParseScript accepts in decimal
64  //since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts
65  if (n > int64_t{0xffffffff} || n < -1 * int64_t{0xffffffff}) {
66  throw std::runtime_error("script parse error: decimal numeric value only allowed in the "
67  "range -0xFFFFFFFF...0xFFFFFFFF");
68  }
69 
70  result << n;
71  }
72  else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
73  {
74  // Raw hex data, inserted NOT pushed onto stack:
75  std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
76  result.insert(result.end(), raw.begin(), raw.end());
77  }
78  else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
79  {
80  // Single-quoted string, pushed as data. NOTE: this is poor-man's
81  // parsing, spaces/tabs/newlines in single-quoted strings won't work.
82  std::vector<unsigned char> value(w->begin()+1, w->end()-1);
83  result << value;
84  }
85  else if (mapOpNames.count(*w))
86  {
87  // opcode, e.g. OP_ADD or ADD:
88  result << mapOpNames[*w];
89  }
90  else
91  {
92  throw std::runtime_error("script parse error");
93  }
94  }
95 
96  return result;
97 }
98 
99 // Check that all of the input and output scripts of a transaction contains valid opcodes
101 {
102  // Check input scripts for non-coinbase txs
103  if (!CTransaction(tx).IsCoinBase()) {
104  for (unsigned int i = 0; i < tx.vin.size(); i++) {
105  if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
106  return false;
107  }
108  }
109  }
110  // Check output scripts
111  for (unsigned int i = 0; i < tx.vout.size(); i++) {
112  if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
113  return false;
114  }
115  }
116 
117  return true;
118 }
119 
120 static bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness)
121 {
122  // General strategy:
123  // - Decode both with extended serialization (which interprets the 0x0001 tag as a marker for
124  // the presense of witnesses) and with legacy serialization (which interprets the tag as a
125  // 0-input 1-output incomplete transaction).
126  // - Restricted by try_no_witness (which disables legacy if false) and try_witness (which
127  // disables extended if false).
128  // - Ignore serializations that do not fully consume the hex string.
129  // - If neither succeeds, fail.
130  // - If only one succeeds, return that one.
131  // - If both decode attempts succeed:
132  // - If only one passes the CheckTxScriptsSanity check, return that one.
133  // - If neither or both pass CheckTxScriptsSanity, return the extended one.
134 
135  CMutableTransaction tx_extended, tx_legacy;
136  bool ok_extended = false, ok_legacy = false;
137 
138  // Try decoding with extended serialization support, and remember if the result successfully
139  // consumes the entire input.
140  if (try_witness) {
141  CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION);
142  try {
143  ssData >> tx_extended;
144  if (ssData.empty()) ok_extended = true;
145  } catch (const std::exception&) {
146  // Fall through.
147  }
148  }
149 
150  // Optimization: if extended decoding succeeded and the result passes CheckTxScriptsSanity,
151  // don't bother decoding the other way.
152  if (ok_extended && CheckTxScriptsSanity(tx_extended)) {
153  tx = std::move(tx_extended);
154  return true;
155  }
156 
157  // Try decoding with legacy serialization, and remember if the result successfully consumes the entire input.
158  if (try_no_witness) {
160  try {
161  ssData >> tx_legacy;
162  if (ssData.empty()) ok_legacy = true;
163  } catch (const std::exception&) {
164  // Fall through.
165  }
166  }
167 
168  // If legacy decoding succeeded and passes CheckTxScriptsSanity, that's our answer, as we know
169  // at this point that extended decoding either failed or doesn't pass the sanity check.
170  if (ok_legacy && CheckTxScriptsSanity(tx_legacy)) {
171  tx = std::move(tx_legacy);
172  return true;
173  }
174 
175  // If extended decoding succeeded, and neither decoding passes sanity, return the extended one.
176  if (ok_extended) {
177  tx = std::move(tx_extended);
178  return true;
179  }
180 
181  // If legacy decoding succeeded and extended didn't, return the legacy one.
182  if (ok_legacy) {
183  tx = std::move(tx_legacy);
184  return true;
185  }
186 
187  // If none succeeded, we failed.
188  return false;
189 }
190 
191 bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
192 {
193  if (!IsHex(hex_tx)) {
194  return false;
195  }
196 
197  std::vector<unsigned char> txData(ParseHex(hex_tx));
198  return DecodeTx(tx, txData, try_no_witness, try_witness);
199 }
200 
201 bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
202 {
203  if (!IsHex(hex_header)) return false;
204 
205  const std::vector<unsigned char> header_data{ParseHex(hex_header)};
206  CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
207  try {
208  ser_header >> header;
209  } catch (const std::exception&) {
210  return false;
211  }
212  return true;
213 }
214 
215 bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
216 {
217  if (!IsHex(strHexBlk))
218  return false;
219 
220  std::vector<unsigned char> blockData(ParseHex(strHexBlk));
221  CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
222  try {
223  ssBlock >> block;
224  }
225  catch (const std::exception&) {
226  return false;
227  }
228 
229  return true;
230 }
231 
232 bool ParseHashStr(const std::string& strHex, uint256& result)
233 {
234  if ((strHex.size() != 64) || !IsHex(strHex))
235  return false;
236 
237  result.SetHex(strHex);
238  return true;
239 }
240 
241 std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
242 {
243  std::string strHex;
244  if (v.isStr())
245  strHex = v.getValStr();
246  if (!IsHex(strHex))
247  throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
248  return ParseHex(strHex);
249 }
250 
251 int ParseSighashString(const UniValue& sighash)
252 {
253  int hash_type = SIGHASH_ALL;
254  if (!sighash.isNull()) {
255  static std::map<std::string, int> map_sighash_values = {
256  {std::string("ALL"), int(SIGHASH_ALL)},
257  {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
258  {std::string("NONE"), int(SIGHASH_NONE)},
259  {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
260  {std::string("SINGLE"), int(SIGHASH_SINGLE)},
261  {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
262  };
263  std::string strHashType = sighash.get_str();
264  const auto& it = map_sighash_values.find(strHashType);
265  if (it != map_sighash_values.end()) {
266  hash_type = it->second;
267  } else {
268  throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
269  }
270  }
271  return hash_type;
272 }
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition: core_read.cpp:201
const std::string & get_str() const
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:23
int ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:251
std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
Definition: core_read.cpp:241
static const unsigned int MAX_OPCODE
Definition: script.h:208
Definition: block.h:62
std::vector< CTxIn > vin
Definition: transaction.h:355
std::vector< unsigned char > ParseHex(const char *psz)
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:79
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:202
opcodetype
Script opcodes.
Definition: script.h:65
bool IsHex(const std::string &str)
Definition: script.h:94
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
Definition: core_read.cpp:191
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
std::vector< CTxOut > vout
Definition: transaction.h:356
int64_t atoi64(const std::string &str)
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:24
256-bit opaque blob.
Definition: uint256.h:124
const std::string & getValStr() const
Definition: univalue.h:65
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
std::string GetOpName(opcodetype opcode)
Definition: script.cpp:12
static bool DecodeTx(CMutableTransaction &tx, const std::vector< unsigned char > &tx_data, bool try_no_witness, bool try_witness)
Definition: core_read.cpp:120
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:232
A mutable version of CTransaction.
Definition: transaction.h:353
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
static bool CheckTxScriptsSanity(const CMutableTransaction &tx)
Definition: core_read.cpp:100
bool isNull() const
Definition: univalue.h:77
auto it
Definition: validation.cpp:381
void SetHex(const char *psz)
Definition: uint256.cpp:30
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
Definition: core_read.cpp:215
bool isStr() const
Definition: univalue.h:81
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
bool empty() const
Definition: streams.h:294