BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
core_read.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2018 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.h>
15 #include <utilstrencodings.h>
16 #include <version.h>
17 
18 #include <boost/algorithm/string/classification.hpp>
19 #include <boost/algorithm/string/replace.hpp>
20 #include <boost/algorithm/string/split.hpp>
21 
22 #include <algorithm>
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  const char* name = GetOpName(static_cast<opcodetype>(op));
39  if (strcmp(name, "OP_UNKNOWN") == 0)
40  continue;
41  std::string strName(name);
42  mapOpNames[strName] = static_cast<opcodetype>(op);
43  // Convenience: OP_ADD and just ADD are both recognized:
44  boost::algorithm::replace_first(strName, "OP_", "");
45  mapOpNames[strName] = static_cast<opcodetype>(op);
46  }
47  }
48 
49  std::vector<std::string> words;
50  boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
51 
52  for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
53  {
54  if (w->empty())
55  {
56  // Empty string, ignore. (boost::split given '' will return one word)
57  }
58  else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
59  (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
60  {
61  // Number
62  int64_t n = atoi64(*w);
63  result << n;
64  }
65  else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
66  {
67  // Raw hex data, inserted NOT pushed onto stack:
68  std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
69  result.insert(result.end(), raw.begin(), raw.end());
70  }
71  else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
72  {
73  // Single-quoted string, pushed as data. NOTE: this is poor-man's
74  // parsing, spaces/tabs/newlines in single-quoted strings won't work.
75  std::vector<unsigned char> value(w->begin()+1, w->end()-1);
76  result << value;
77  }
78  else if (mapOpNames.count(*w))
79  {
80  // opcode, e.g. OP_ADD or ADD:
81  result << mapOpNames[*w];
82  }
83  else
84  {
85  throw std::runtime_error("script parse error");
86  }
87  }
88 
89  return result;
90 }
91 
92 // Check that all of the input and output scripts of a transaction contains valid opcodes
93 static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
94 {
95  // Check input scripts for non-coinbase txs
96  if (!CTransaction(tx).IsCoinBase()) {
97  for (unsigned int i = 0; i < tx.vin.size(); i++) {
98  if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
99  return false;
100  }
101  }
102  }
103  // Check output scripts
104  for (unsigned int i = 0; i < tx.vout.size(); i++) {
105  if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
106  return false;
107  }
108  }
109 
110  return true;
111 }
112 
113 bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
114 {
115  if (!IsHex(hex_tx)) {
116  return false;
117  }
118 
119  std::vector<unsigned char> txData(ParseHex(hex_tx));
120 
121  if (try_no_witness) {
122  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
123  try {
124  ssData >> tx;
125  if (ssData.eof() && (!try_witness || CheckTxScriptsSanity(tx))) {
126  return true;
127  }
128  } catch (const std::exception&) {
129  // Fall through.
130  }
131  }
132 
133  if (try_witness) {
134  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
135  try {
136  ssData >> tx;
137  if (ssData.empty()) {
138  return true;
139  }
140  } catch (const std::exception&) {
141  // Fall through.
142  }
143  }
144 
145  return false;
146 }
147 
148 bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
149 {
150  if (!IsHex(hex_header)) return false;
151 
152  const std::vector<unsigned char> header_data{ParseHex(hex_header)};
153  CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
154  try {
155  ser_header >> header;
156  } catch (const std::exception&) {
157  return false;
158  }
159  return true;
160 }
161 
162 bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
163 {
164  if (!IsHex(strHexBlk))
165  return false;
166 
167  std::vector<unsigned char> blockData(ParseHex(strHexBlk));
168  CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
169  try {
170  ssBlock >> block;
171  }
172  catch (const std::exception&) {
173  return false;
174  }
175 
176  return true;
177 }
178 
179 bool DecodePSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
180 {
181  std::vector<unsigned char> tx_data = DecodeBase64(base64_tx.c_str());
182  CDataStream ss_data(tx_data, SER_NETWORK, PROTOCOL_VERSION);
183  try {
184  ss_data >> psbt;
185  if (!ss_data.empty()) {
186  error = "extra data after PSBT";
187  return false;
188  }
189  } catch (const std::exception& e) {
190  error = e.what();
191  return false;
192  }
193  return true;
194 }
195 
196 bool ParseHashStr(const std::string& strHex, uint256& result)
197 {
198  if ((strHex.size() != 64) || !IsHex(strHex))
199  return false;
200 
201  result.SetHex(strHex);
202  return true;
203 }
204 
205 std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
206 {
207  std::string strHex;
208  if (v.isStr())
209  strHex = v.getValStr();
210  if (!IsHex(strHex))
211  throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
212  return ParseHex(strHex);
213 }
214 
215 int ParseSighashString(const UniValue& sighash)
216 {
217  int hash_type = SIGHASH_ALL;
218  if (!sighash.isNull()) {
219  static std::map<std::string, int> map_sighash_values = {
220  {std::string("ALL"), int(SIGHASH_ALL)},
221  {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
222  {std::string("NONE"), int(SIGHASH_NONE)},
223  {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
224  {std::string("SINGLE"), int(SIGHASH_SINGLE)},
225  {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
226  };
227  std::string strHashType = sighash.get_str();
228  const auto& it = map_sighash_values.find(strHashType);
229  if (it != map_sighash_values.end()) {
230  hash_type = it->second;
231  } else {
232  throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
233  }
234  }
235  return hash_type;
236 }
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition: core_read.cpp:148
int ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:215
std::vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
Definition: core_read.cpp:205
iterator insert(iterator pos, const T &value)
Definition: prevector.h:358
Definition: block.h:74
std::vector< CTxIn > vin
Definition: transaction.h:362
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
const std::string & get_str() const
bool isStr() const
Definition: univalue.h:82
A version of CTransaction with the PSBT format.
Definition: sign.h:557
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:221
bool empty() const
Definition: streams.h:313
const std::string & getValStr() const
Definition: univalue.h:66
iterator end()
Definition: prevector.h:303
opcodetype
Script opcodes.
Definition: script.h:48
const char * name
Definition: rest.cpp:37
bool IsHex(const std::string &str)
Definition: script.h:77
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
Definition: core_read.cpp:113
std::vector< CTxOut > vout
Definition: transaction.h:363
bool isNull() const
Definition: univalue.h:78
const char * GetOpName(opcodetype opcode)
Definition: script.cpp:11
bool DecodePSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Definition: core_read.cpp:179
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:24
256-bit opaque blob.
Definition: uint256.h:122
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:384
int64_t atoi64(const char *psz)
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:196
A mutable version of CTransaction.
Definition: transaction.h:360
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:264
void SetHex(const char *psz)
Definition: uint256.cpp:27
bool eof() const
Definition: streams.h:408
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
Definition: core_read.cpp:162
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
std::vector< unsigned char > ParseHex(const char *psz)