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