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