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 bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
121 {
122  if (!IsHex(hex_tx)) {
123  return false;
124  }
125 
126  std::vector<unsigned char> txData(ParseHex(hex_tx));
127 
128  if (try_no_witness) {
130  try {
131  ssData >> tx;
132  if (ssData.eof() && (!try_witness || CheckTxScriptsSanity(tx))) {
133  return true;
134  }
135  } catch (const std::exception&) {
136  // Fall through.
137  }
138  }
139 
140  if (try_witness) {
141  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
142  try {
143  ssData >> tx;
144  if (ssData.empty()) {
145  return true;
146  }
147  } catch (const std::exception&) {
148  // Fall through.
149  }
150  }
151 
152  return false;
153 }
154 
155 bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
156 {
157  if (!IsHex(hex_header)) return false;
158 
159  const std::vector<unsigned char> header_data{ParseHex(hex_header)};
160  CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
161  try {
162  ser_header >> header;
163  } catch (const std::exception&) {
164  return false;
165  }
166  return true;
167 }
168 
169 bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
170 {
171  if (!IsHex(strHexBlk))
172  return false;
173 
174  std::vector<unsigned char> blockData(ParseHex(strHexBlk));
175  CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
176  try {
177  ssBlock >> block;
178  }
179  catch (const std::exception&) {
180  return false;
181  }
182 
183  return true;
184 }
185 
186 bool ParseHashStr(const std::string& strHex, uint256& result)
187 {
188  if ((strHex.size() != 64) || !IsHex(strHex))
189  return false;
190 
191  result.SetHex(strHex);
192  return true;
193 }
194 
195 std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
196 {
197  std::string strHex;
198  if (v.isStr())
199  strHex = v.getValStr();
200  if (!IsHex(strHex))
201  throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
202  return ParseHex(strHex);
203 }
204 
205 int ParseSighashString(const UniValue& sighash)
206 {
207  int hash_type = SIGHASH_ALL;
208  if (!sighash.isNull()) {
209  static std::map<std::string, int> map_sighash_values = {
210  {std::string("ALL"), int(SIGHASH_ALL)},
211  {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
212  {std::string("NONE"), int(SIGHASH_NONE)},
213  {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
214  {std::string("SINGLE"), int(SIGHASH_SINGLE)},
215  {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
216  };
217  std::string strHashType = sighash.get_str();
218  const auto& it = map_sighash_values.find(strHashType);
219  if (it != map_sighash_values.end()) {
220  hash_type = it->second;
221  } else {
222  throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
223  }
224  }
225  return hash_type;
226 }
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition: core_read.cpp:155
static const int SERIALIZE_TRANSACTION_NO_WITNESS
Definition: transaction.h:15
int ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:205
std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
Definition: core_read.cpp:195
iterator insert(iterator pos, const T &value)
Definition: prevector.h:347
static const unsigned int MAX_OPCODE
Definition: script.h:194
Definition: block.h:62
std::vector< CTxIn > vin
Definition: transaction.h:347
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:67
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:201
bool empty() const
Definition: streams.h:293
const std::string & getValStr() const
Definition: univalue.h:65
iterator end()
Definition: prevector.h:292
opcodetype
Script opcodes.
Definition: script.h:54
bool IsHex(const std::string &str)
Definition: script.h:83
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
Definition: core_read.cpp:120
static const int MAX_SCRIPT_SIZE
Definition: script.h:32
std::vector< CTxOut > vout
Definition: transaction.h:348
bool isNull() const
Definition: univalue.h:77
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:24
256-bit opaque blob.
Definition: uint256.h:120
int64_t atoi64(const char *psz)
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
std::string GetOpName(opcodetype opcode)
Definition: script.cpp:12
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:186
A mutable version of CTransaction.
Definition: transaction.h:345
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:251
static bool CheckTxScriptsSanity(const CMutableTransaction &tx)
Definition: core_read.cpp:100
auto it
Definition: validation.cpp:384
void SetHex(const char *psz)
Definition: uint256.cpp:26
bool eof() const
Definition: streams.h:388
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
Definition: core_read.cpp:169
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20