Bitcoin ABC 0.34.2
P2P Digital Currency
core_write.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2016 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 <common/system.h>
8#include <config.h>
9#include <consensus/amount.h>
10#include <key_io.h>
13#include <script/script.h>
14#include <script/script_flags.h>
15#include <script/sigencoding.h>
16#include <script/solver.h>
17#include <serialize.h>
18#include <streams.h>
19#include <undo.h>
20#include <util/check.h>
21#include <util/strencodings.h>
22
23#include <univalue.h>
24
25std::string FormatScript(const CScript &script) {
26 std::string ret;
28 opcodetype op;
29 while (it != script.end()) {
31 std::vector<uint8_t> vch;
32 if (script.GetOp(it, op, vch)) {
33 if (op == OP_0) {
34 ret += "0 ";
35 continue;
36 }
37
38 if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
39 ret += strprintf("%i ", op - OP_1NEGATE - 1);
40 continue;
41 }
42
43 if (op >= OP_NOP && op < FIRST_UNDEFINED_OP_VALUE) {
44 std::string str(GetOpName(op));
45 if (str.substr(0, 3) == std::string("OP_")) {
46 ret += str.substr(3, std::string::npos) + " ";
47 continue;
48 }
49 }
50
51 if (vch.size() > 0) {
52 ret += strprintf(
53 "0x%x 0x%x ",
54 HexStr(std::vector<uint8_t>(it2, it - vch.size())),
55 HexStr(std::vector<uint8_t>(it - vch.size(), it)));
56 } else {
57 ret +=
58 strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
59 }
60
61 continue;
62 }
63
64 ret +=
65 strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
66 break;
67 }
68
69 return ret.substr(0, ret.size() - 1);
70}
71
72const std::map<uint8_t, std::string> mapSigHashTypes = {
73 {SIGHASH_ALL, "ALL"},
74 {SIGHASH_ALL | SIGHASH_ANYONECANPAY, "ALL|ANYONECANPAY"},
75 {SIGHASH_ALL | SIGHASH_FORKID, "ALL|FORKID"},
77 "ALL|FORKID|ANYONECANPAY"},
78 {SIGHASH_NONE, "NONE"},
79 {SIGHASH_NONE | SIGHASH_ANYONECANPAY, "NONE|ANYONECANPAY"},
80 {SIGHASH_NONE | SIGHASH_FORKID, "NONE|FORKID"},
82 "NONE|FORKID|ANYONECANPAY"},
83 {SIGHASH_SINGLE, "SINGLE"},
84 {SIGHASH_SINGLE | SIGHASH_ANYONECANPAY, "SINGLE|ANYONECANPAY"},
85 {SIGHASH_SINGLE | SIGHASH_FORKID, "SINGLE|FORKID"},
87 "SINGLE|FORKID|ANYONECANPAY"},
88};
89
90std::string SighashToStr(uint8_t sighash_type) {
91 const auto &it = mapSigHashTypes.find(sighash_type);
92 if (it == mapSigHashTypes.end()) {
93 return "";
94 }
95 return it->second;
96}
97
107std::string ScriptToAsmStr(const CScript &script,
108 const bool fAttemptSighashDecode) {
109 std::string str;
110 opcodetype opcode;
111 std::vector<uint8_t> vch;
112 CScript::const_iterator pc = script.begin();
113 while (pc < script.end()) {
114 if (!str.empty()) {
115 str += " ";
116 }
117
118 if (!script.GetOp(pc, opcode, vch)) {
119 str += "[error]";
120 return str;
121 }
122
123 if (0 <= opcode && opcode <= OP_PUSHDATA4) {
125 // Only render decimal number if minimally encoded and <8 bytes.
126 // Avoids rendering legitimate byte strings as decimal number.
127 str += strprintf(
128 "%d",
129 CScriptNum(vch, false, MAX_SCRIPTNUM_BYTE_SIZE).getint());
130 } else {
131 // the IsUnspendable check makes sure not to try to decode
132 // OP_RETURN data that may match the format of a signature
133 if (fAttemptSighashDecode && !script.IsUnspendable()) {
134 std::string strSigHashDecode;
135 // goal: only attempt to decode a defined sighash type from
136 // data that looks like a signature within a scriptSig. This
137 // won't decode correctly formatted public keys in Pubkey or
138 // Multisig scripts due to the restrictions on the pubkey
139 // formats (see IsCompressedOrUncompressedPubKey) being
140 // incongruous with the checks in
141 // CheckTransactionSignatureEncoding.
143 if (vch.back() & SIGHASH_FORKID) {
144 // If the transaction is using SIGHASH_FORKID, we need
145 // to set the appropriate flag.
146 // TODO: Remove after the Hard Fork.
148 }
150 nullptr)) {
151 const uint8_t chSigHashType = vch.back();
152 const auto it = mapSigHashTypes.find(chSigHashType);
153 if (it != mapSigHashTypes.end()) {
154 strSigHashDecode = "[" + it->second + "]";
155 // remove the sighash type byte. it will be replaced
156 // by the decode.
157 vch.pop_back();
158 }
159 }
160
161 str += HexStr(vch) + strSigHashDecode;
162 } else {
163 str += HexStr(vch);
164 }
165 }
166 } else {
167 str += GetOpName(opcode);
168 }
169 }
170
171 return str;
172}
173
174std::string EncodeHexTx(const CTransaction &tx) {
175 DataStream ssTx{};
176 ssTx << tx;
177 return HexStr(ssTx);
178}
179
180void ScriptToUniv(const CScript &script, UniValue &out, bool include_address) {
181 out.pushKV("asm", ScriptToAsmStr(script));
182 out.pushKV("hex", HexStr(script));
183
184 std::vector<std::vector<uint8_t>> solns;
185 TxoutType type = Solver(script, solns);
186 out.pushKV("type", GetTxnOutputType(type));
187
188 CTxDestination address;
189 if (include_address && ExtractDestination(script, address) &&
190 type != TxoutType::PUBKEY) {
191 out.pushKV("address", EncodeDestination(address, GetConfig()));
192 }
193}
194
195void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out,
196 bool fIncludeHex) {
197 TxoutType type;
198 std::vector<CTxDestination> addresses;
199 int nRequired;
200
201 out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
202 if (fIncludeHex) {
203 out.pushKV("hex", HexStr(scriptPubKey));
204 }
205
206 if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) ||
207 type == TxoutType::PUBKEY) {
208 out.pushKV("type", GetTxnOutputType(type));
209 return;
210 }
211
212 out.pushKV("reqSigs", nRequired);
213 out.pushKV("type", GetTxnOutputType(type));
214
216 for (const CTxDestination &addr : addresses) {
218 }
219 out.pushKV("addresses", a);
220}
221
222void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock,
223 UniValue &entry, bool include_hex, const CTxUndo *txundo,
224 TxVerbosity verbosity,
225 std::function<bool(const CTxOut &)> is_change_func) {
226 entry.pushKV("txid", tx.GetId().GetHex());
227 entry.pushKV("hash", tx.GetHash().GetHex());
228 entry.pushKV("version", tx.nVersion);
229 entry.pushKV("size", (int)::GetSerializeSize(tx));
230 entry.pushKV("locktime", (int64_t)tx.nLockTime);
231
233
234 // If available, use Undo data to calculate the fee. Note that
235 // txundo == nullptr for coinbase transactions and for transactions where
236 // undo data is unavailable.
237 const bool have_undo = txundo != nullptr;
238 Amount amt_total_in = Amount::zero();
239 Amount amt_total_out = Amount::zero();
240
241 for (unsigned int i = 0; i < tx.vin.size(); i++) {
242 const CTxIn &txin = tx.vin[i];
244 if (tx.IsCoinBase()) {
245 in.pushKV("coinbase", HexStr(txin.scriptSig));
246 } else {
247 in.pushKV("txid", txin.prevout.GetTxId().GetHex());
248 in.pushKV("vout", int64_t(txin.prevout.GetN()));
250 o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
251 o.pushKV("hex", HexStr(txin.scriptSig));
252 in.pushKV("scriptSig", std::move(o));
253 }
254 if (have_undo) {
255 const Coin &prev_coin = txundo->vprevout[i];
256 const CTxOut &prev_txout = prev_coin.GetTxOut();
257
258 amt_total_in += prev_txout.nValue;
259 switch (verbosity) {
262 break;
263
265 UniValue o_script_pub_key(UniValue::VOBJ);
267 o_script_pub_key, /*fIncludeHex=*/true);
268
270 p.pushKV("generated", bool(prev_coin.IsCoinBase()));
271 p.pushKV("height", uint64_t(prev_coin.GetHeight()));
272 p.pushKV("value", prev_txout.nValue);
273 p.pushKV("scriptPubKey", std::move(o_script_pub_key));
274 in.pushKV("prevout", std::move(p));
275 break;
276 }
277 }
278 in.pushKV("sequence", (int64_t)txin.nSequence);
279 vin.push_back(std::move(in));
280 }
281
282 entry.pushKV("vin", std::move(vin));
283
285 for (unsigned int i = 0; i < tx.vout.size(); i++) {
286 const CTxOut &txout = tx.vout[i];
287
289
290 out.pushKV("value", txout.nValue);
291 out.pushKV("n", int64_t(i));
292
294 ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
295 out.pushKV("scriptPubKey", std::move(o));
296
297 if (is_change_func && is_change_func(txout)) {
298 out.pushKV("ischange", true);
299 }
300
301 vout.push_back(std::move(out));
302
303 if (have_undo) {
304 amt_total_out += txout.nValue;
305 }
306 }
307
308 entry.pushKV("vout", std::move(vout));
309
310 if (have_undo) {
311 const Amount fee = amt_total_in - amt_total_out;
313 entry.pushKV("fee", fee);
314 }
315
316 if (!hashBlock.IsNull()) {
317 entry.pushKV("blockhash", hashBlock.GetHex());
318 }
319
320 if (include_hex) {
321 // The hex-encoded transaction. Used the name "hex" to be consistent
322 // with the verbose output of "getrawtransaction".
323 entry.pushKV("hex", EncodeHexTx(tx));
324 }
325}
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: addresstype.cpp:33
bool ExtractDestinations(const CScript &scriptPubKey, TxoutType &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Parse a standard scriptPubKey with one or more destination addresses.
Definition: addresstype.cpp:59
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: addresstype.h:54
bool MoneyRange(const Amount nValue)
Definition: amount.h:177
int flags
Definition: bitcoin-tx.cpp:544
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:83
static bool IsMinimallyEncoded(const std::vector< uint8_t > &vch, const size_t nMaxNumSize)
Definition: script.cpp:302
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:61
std::vector< Coin > vprevout
Definition: undo.h:64
A UTXO entry.
Definition: coins.h:31
uint32_t GetHeight() const
Definition: coins.h:48
bool IsCoinBase() const
Definition: coins.h:49
CTxOut & GetTxOut()
Definition: coins.h:52
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:118
void push_back(UniValue val)
Definition: univalue.cpp:96
@ VOBJ
Definition: univalue.h:31
@ VARR
Definition: univalue.h:32
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
constexpr bool IsNull() const
Definition: uint256.h:44
std::string GetHex() const
Definition: uint256.cpp:10
const Config & GetConfig()
Definition: config.cpp:40
TxVerbosity
Verbose level for block's transaction.
Definition: core_io.h:29
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
@ SHOW_DETAILS
Include TXID, inputs, outputs, and other common block's transaction information.
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:180
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:174
std::string SighashToStr(uint8_t sighash_type)
Definition: core_write.cpp:90
std::string FormatScript(const CScript &script)
Definition: core_write.cpp:25
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:195
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex, const CTxUndo *txundo, TxVerbosity verbosity, std::function< bool(const CTxOut &)> is_change_func)
Definition: core_write.cpp:222
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:107
const std::map< uint8_t, std::string > mapSigHashTypes
Definition: core_write.cpp:72
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:167
std::string GetOpName(opcodetype opcode)
Definition: script.cpp:17
opcodetype
Script opcodes.
Definition: script.h:53
@ OP_PUSHDATA4
Definition: script.h:59
@ OP_1NEGATE
Definition: script.h:60
@ OP_16
Definition: script.h:78
@ FIRST_UNDEFINED_OP_VALUE
Definition: script.h:196
@ OP_NOP
Definition: script.h:81
@ OP_1
Definition: script.h:62
@ OP_0
Definition: script.h:55
constexpr size_t MAX_SCRIPTNUM_BYTE_SIZE
Definition: script.h:42
@ SCRIPT_VERIFY_STRICTENC
Definition: script_flags.h:22
@ SCRIPT_ENABLE_SIGHASH_FORKID
Definition: script_flags.h:85
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1264
bool CheckTransactionSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded.
@ SIGHASH_FORKID
Definition: sighashtype.h:18
@ SIGHASH_ANYONECANPAY
Definition: sighashtype.h:19
@ SIGHASH_ALL
Definition: sighashtype.h:15
@ SIGHASH_NONE
Definition: sighashtype.h:16
@ SIGHASH_SINGLE
Definition: sighashtype.h:17
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:93
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: solver.cpp:14
TxoutType
Definition: solver.h:15
Definition: amount.h:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1203