Bitcoin Core  0.20.99
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/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  if (try_witness) {
123  CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION);
124  try {
125  ssData >> tx;
126  // If transaction looks sane, we don't try other mode even if requested
127  if (ssData.empty() && (!try_no_witness || CheckTxScriptsSanity(tx))) {
128  return true;
129  }
130  } catch (const std::exception&) {
131  // Fall through.
132  }
133  }
134 
135  if (try_no_witness) {
137  try {
138  ssData >> tx;
139  if (ssData.empty()) {
140  return true;
141  }
142  } catch (const std::exception&) {
143  // Fall through.
144  }
145  }
146 
147  return false;
148 }
149 
150 bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
151 {
152  if (!IsHex(hex_tx)) {
153  return false;
154  }
155 
156  std::vector<unsigned char> txData(ParseHex(hex_tx));
157  return DecodeTx(tx, txData, try_no_witness, try_witness);
158 }
159 
160 bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
161 {
162  if (!IsHex(hex_header)) return false;
163 
164  const std::vector<unsigned char> header_data{ParseHex(hex_header)};
165  CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
166  try {
167  ser_header >> header;
168  } catch (const std::exception&) {
169  return false;
170  }
171  return true;
172 }
173 
174 bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
175 {
176  if (!IsHex(strHexBlk))
177  return false;
178 
179  std::vector<unsigned char> blockData(ParseHex(strHexBlk));
180  CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
181  try {
182  ssBlock >> block;
183  }
184  catch (const std::exception&) {
185  return false;
186  }
187 
188  return true;
189 }
190 
191 bool ParseHashStr(const std::string& strHex, uint256& result)
192 {
193  if ((strHex.size() != 64) || !IsHex(strHex))
194  return false;
195 
196  result.SetHex(strHex);
197  return true;
198 }
199 
200 std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
201 {
202  std::string strHex;
203  if (v.isStr())
204  strHex = v.getValStr();
205  if (!IsHex(strHex))
206  throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
207  return ParseHex(strHex);
208 }
209 
210 int ParseSighashString(const UniValue& sighash)
211 {
212  int hash_type = SIGHASH_ALL;
213  if (!sighash.isNull()) {
214  static std::map<std::string, int> map_sighash_values = {
215  {std::string("ALL"), int(SIGHASH_ALL)},
216  {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
217  {std::string("NONE"), int(SIGHASH_NONE)},
218  {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
219  {std::string("SINGLE"), int(SIGHASH_SINGLE)},
220  {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
221  };
222  std::string strHashType = sighash.get_str();
223  const auto& it = map_sighash_values.find(strHashType);
224  if (it != map_sighash_values.end()) {
225  hash_type = it->second;
226  } else {
227  throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
228  }
229  }
230  return hash_type;
231 }
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition: core_read.cpp:160
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:210
std::deque< CInv >::iterator it
std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
Definition: core_read.cpp:200
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: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
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:150
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
std::vector< CTxOut > vout
Definition: transaction.h:356
bool isNull() const
Definition: univalue.h:77
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
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:191
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
void SetHex(const char *psz)
Definition: uint256.cpp:30
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
Definition: core_read.cpp:174
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20