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