Bitcoin ABC  0.22.13
P2P Digital Currency
core_read.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2016 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 <psbt.h>
10 #include <script/script.h>
11 #include <script/sign.h>
12 #include <serialize.h>
13 #include <streams.h>
14 #include <util/strencodings.h>
15 #include <util/string.h>
16 #include <version.h>
17 
18 #include <univalue.h>
19 
20 #include <boost/algorithm/string/classification.hpp>
21 #include <boost/algorithm/string/replace.hpp>
22 #include <boost/algorithm/string/split.hpp>
23 
24 #include <algorithm>
25 
26 CScript ParseScript(const std::string &s) {
27  CScript result;
28 
29  static std::map<std::string, opcodetype> mapOpNames;
30 
31  if (mapOpNames.empty()) {
32  for (int op = 0; op < FIRST_UNDEFINED_OP_VALUE; op++) {
33  if (op < OP_PUSHDATA1) {
34  continue;
35  }
36 
37  const char *name = GetOpName(static_cast<opcodetype>(op));
38  if (strcmp(name, "OP_UNKNOWN") == 0) {
39  continue;
40  }
41 
42  std::string strName(name);
43  mapOpNames[strName] = static_cast<opcodetype>(op);
44  // Convenience: OP_ADD and just ADD are both recognized:
45  boost::algorithm::replace_first(strName, "OP_", "");
46  mapOpNames[strName] = static_cast<opcodetype>(op);
47  }
48  }
49 
50  std::vector<std::string> words;
51  boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"),
52  boost::algorithm::token_compress_on);
53 
54  size_t push_size = 0, next_push_size = 0;
55  size_t script_size = 0;
56  // Deal with PUSHDATA1 operation with some more hacks.
57  size_t push_data_size = 0;
58 
59  for (const auto &w : words) {
60  if (w.empty()) {
61  // Empty string, ignore. (boost::split given '' will return one
62  // word)
63  continue;
64  }
65 
66  // Update script size.
67  script_size = result.size();
68 
69  // Make sure we keep track of the size of push operations.
70  push_size = next_push_size;
71  next_push_size = 0;
72 
73  // Decimal numbers
74  if (std::all_of(w.begin(), w.end(), ::IsDigit) ||
75  (w.front() == '-' && w.size() > 1 &&
76  std::all_of(w.begin() + 1, w.end(), ::IsDigit))) {
77  // Number
78  int64_t n = atoi64(w);
79 
80  // limit the range of numbers ParseScript accepts in decimal
81  // since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in
82  // scripts
83  if (n > int64_t{0xffffffff} || n < -1 * int64_t{0xffffffff}) {
84  throw std::runtime_error("script parse error: decimal numeric "
85  "value only allowed in the "
86  "range -0xFFFFFFFF...0xFFFFFFFF");
87  }
88 
89  result << n;
90  goto next;
91  }
92 
93  // Hex Data
94  if (w.substr(0, 2) == "0x" && w.size() > 2) {
95  if (!IsHex(std::string(w.begin() + 2, w.end()))) {
96  // Should only arrive here for improperly formatted hex values
97  throw std::runtime_error("Hex numbers expected to be formatted "
98  "in full-byte chunks (ex: 0x00 "
99  "instead of 0x0)");
100  }
101 
102  // Raw hex data, inserted NOT pushed onto stack:
103  std::vector<uint8_t> raw =
104  ParseHex(std::string(w.begin() + 2, w.end()));
105 
106  result.insert(result.end(), raw.begin(), raw.end());
107  goto next;
108  }
109 
110  if (w.size() >= 2 && w.front() == '\'' && w.back() == '\'') {
111  // Single-quoted string, pushed as data. NOTE: this is poor-man's
112  // parsing, spaces/tabs/newlines in single-quoted strings won't
113  // work.
114  std::vector<uint8_t> value(w.begin() + 1, w.end() - 1);
115  result << value;
116  goto next;
117  }
118 
119  if (mapOpNames.count(w)) {
120  // opcode, e.g. OP_ADD or ADD:
121  opcodetype op = mapOpNames[w];
122 
123  result << op;
124  goto next;
125  }
126 
127  throw std::runtime_error("Error parsing script: " + s);
128 
129  next:
130  size_t size_change = result.size() - script_size;
131 
132  // If push_size is set, ensure have added the right amount of stuff.
133  if (push_size != 0 && size_change != push_size) {
134  throw std::runtime_error(
135  "Wrong number of bytes being pushed. Expected:" +
136  ToString(push_size) + " Pushed:" + ToString(size_change));
137  }
138 
139  // If push_size is set, and we have push_data_size set, then we have a
140  // PUSHDATAX opcode. We need to read it's push size as a LE value for
141  // the next iteration of this loop.
142  if (push_size != 0 && push_data_size != 0) {
143  auto offset = &result[script_size];
144 
145  // Push data size is not a CScriptNum (Because it is
146  // 2's-complement instead of 1's complement). We need to use
147  // ReadLE(N) instead of converting to a CScriptNum.
148  if (push_data_size == 1) {
149  next_push_size = *offset;
150  } else if (push_data_size == 2) {
151  next_push_size = ReadLE16(offset);
152  } else if (push_data_size == 4) {
153  next_push_size = ReadLE32(offset);
154  }
155 
156  push_data_size = 0;
157  }
158 
159  // If push_size is unset, but size_change is 1, that means we have an
160  // opcode in the form of `0x00` or <opcodename>. We will check to see
161  // if it is a push operation and set state accordingly
162  if (push_size == 0 && size_change == 1) {
163  opcodetype op = opcodetype(*result.rbegin());
164 
165  // If we have what looks like an immediate push, figure out its
166  // size.
167  if (op < OP_PUSHDATA1) {
168  next_push_size = op;
169  continue;
170  }
171 
172  switch (op) {
173  case OP_PUSHDATA1:
174  push_data_size = next_push_size = 1;
175  break;
176  case OP_PUSHDATA2:
177  push_data_size = next_push_size = 2;
178  break;
179  case OP_PUSHDATA4:
180  push_data_size = next_push_size = 4;
181  break;
182  default:
183  break;
184  }
185  }
186  }
187 
188  return result;
189 }
190 
191 bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx) {
192  if (!IsHex(strHexTx)) {
193  return false;
194  }
195 
196  std::vector<uint8_t> txData(ParseHex(strHexTx));
197 
198  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
199  try {
200  ssData >> tx;
201  if (ssData.eof()) {
202  return true;
203  }
204  } catch (const std::exception &e) {
205  // Fall through.
206  }
207 
208  return false;
209 }
210 
211 bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header) {
212  if (!IsHex(hex_header)) {
213  return false;
214  }
215 
216  const std::vector<uint8_t> header_data{ParseHex(hex_header)};
217  CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
218  try {
219  ser_header >> header;
220  } catch (const std::exception &) {
221  return false;
222  }
223  return true;
224 }
225 
226 bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk) {
227  if (!IsHex(strHexBlk)) {
228  return false;
229  }
230 
231  std::vector<uint8_t> blockData(ParseHex(strHexBlk));
232  CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
233  try {
234  ssBlock >> block;
235  } catch (const std::exception &) {
236  return false;
237  }
238 
239  return true;
240 }
241 
242 bool ParseHashStr(const std::string &strHex, uint256 &result) {
243  if ((strHex.size() != 64) || !IsHex(strHex)) {
244  return false;
245  }
246 
247  result.SetHex(strHex);
248  return true;
249 }
250 
251 std::vector<uint8_t> ParseHexUV(const UniValue &v, const std::string &strName) {
252  std::string strHex;
253  if (v.isStr()) {
254  strHex = v.getValStr();
255  }
256 
257  if (!IsHex(strHex)) {
258  throw std::runtime_error(
259  strName + " must be hexadecimal string (not '" + strHex + "')");
260  }
261 
262  return ParseHex(strHex);
263 }
264 
266  SigHashType sigHashType = SigHashType().withForkId();
267  if (!sighash.isNull()) {
268  static std::map<std::string, int> map_sighash_values = {
269  {"ALL", SIGHASH_ALL},
270  {"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
271  {"ALL|FORKID", SIGHASH_ALL | SIGHASH_FORKID},
272  {"ALL|FORKID|ANYONECANPAY",
274  {"NONE", SIGHASH_NONE},
275  {"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
276  {"NONE|FORKID", SIGHASH_NONE | SIGHASH_FORKID},
277  {"NONE|FORKID|ANYONECANPAY",
279  {"SINGLE", SIGHASH_SINGLE},
280  {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
281  {"SINGLE|FORKID", SIGHASH_SINGLE | SIGHASH_FORKID},
282  {"SINGLE|FORKID|ANYONECANPAY",
284  };
285  std::string strHashType = sighash.get_str();
286  const auto &it = map_sighash_values.find(strHashType);
287  if (it != map_sighash_values.end()) {
288  sigHashType = SigHashType(it->second);
289  } else {
290  throw std::runtime_error(strHashType +
291  " is not a valid sighash parameter.");
292  }
293  }
294  return sigHashType;
295 }
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition: core_read.cpp:211
static uint16_t ReadLE16(const uint8_t *ptr)
Definition: common.h:17
std::vector< uint8_t > ParseHexUV(const UniValue &v, const std::string &strName)
Definition: core_read.cpp:251
iterator insert(iterator pos, const T &value)
Definition: prevector.h:441
SigHashType ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:265
Definition: block.h:62
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:74
const std::string & get_str() const
bool isStr() const
Definition: univalue.h:93
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:196
const std::string & getValStr() const
Definition: univalue.h:77
iterator end()
Definition: prevector.h:390
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
opcodetype
Script opcodes.
Definition: script.h:46
SigHashType withForkId(bool forkId=true) const
Definition: sighashtype.h:54
const char * name
Definition: rest.cpp:43
bool IsHex(const std::string &str)
Returns true if each character in str is a hex character, and has an even number of hex digits...
reverse_iterator rbegin()
Definition: prevector.h:393
static uint32_t ReadLE32(const uint8_t *ptr)
Definition: common.h:23
bool isNull() const
Definition: univalue.h:89
const char * GetOpName(opcodetype opcode)
Definition: script.cpp:13
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:26
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:430
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
std::vector< uint8_t > ParseHex(const char *psz)
A mutable version of CTransaction.
Definition: transaction.h:295
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:191
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:242
size_type size() const
Definition: prevector.h:384
void SetHex(const char *psz)
Definition: uint256.cpp:21
bool eof() const
Definition: streams.h:379
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
Definition: core_read.cpp:226
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
Signature hash type wrapper class.
Definition: sighashtype.h:37