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