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