Bitcoin Core 22.99.0
P2P Digital Currency
core_write.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 <consensus/amount.h>
10#include <key_io.h>
11#include <script/script.h>
12#include <script/standard.h>
13#include <serialize.h>
14#include <streams.h>
15#include <undo.h>
16#include <univalue.h>
17#include <util/check.h>
18#include <util/strencodings.h>
19#include <util/system.h>
20
22{
23 static_assert(COIN > 1);
24 int64_t quotient = amount / COIN;
25 int64_t remainder = amount % COIN;
26 if (amount < 0) {
27 quotient = -quotient;
28 remainder = -remainder;
29 }
31 strprintf("%s%d.%08d", amount < 0 ? "-" : "", quotient, remainder));
32}
33
34std::string FormatScript(const CScript& script)
35{
36 std::string ret;
37 CScript::const_iterator it = script.begin();
38 opcodetype op;
39 while (it != script.end()) {
41 std::vector<unsigned char> vch;
42 if (script.GetOp(it, op, vch)) {
43 if (op == OP_0) {
44 ret += "0 ";
45 continue;
46 } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
47 ret += strprintf("%i ", op - OP_1NEGATE - 1);
48 continue;
49 } else if (op >= OP_NOP && op <= OP_NOP10) {
50 std::string str(GetOpName(op));
51 if (str.substr(0, 3) == std::string("OP_")) {
52 ret += str.substr(3, std::string::npos) + " ";
53 continue;
54 }
55 }
56 if (vch.size() > 0) {
57 ret += strprintf("0x%x 0x%x ", HexStr(std::vector<uint8_t>(it2, it - vch.size())),
58 HexStr(std::vector<uint8_t>(it - vch.size(), it)));
59 } else {
60 ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
61 }
62 continue;
63 }
64 ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
65 break;
66 }
67 return ret.substr(0, ret.size() - 1);
68}
69
70const std::map<unsigned char, std::string> mapSigHashTypes = {
71 {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")},
72 {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")},
73 {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")},
74 {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")},
75 {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")},
76 {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")},
77};
78
79std::string SighashToStr(unsigned char sighash_type)
80{
81 const auto& it = mapSigHashTypes.find(sighash_type);
82 if (it == mapSigHashTypes.end()) return "";
83 return it->second;
84}
85
93std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
94{
95 std::string str;
96 opcodetype opcode;
97 std::vector<unsigned char> vch;
98 CScript::const_iterator pc = script.begin();
99 while (pc < script.end()) {
100 if (!str.empty()) {
101 str += " ";
102 }
103 if (!script.GetOp(pc, opcode, vch)) {
104 str += "[error]";
105 return str;
106 }
107 if (0 <= opcode && opcode <= OP_PUSHDATA4) {
108 if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
109 str += strprintf("%d", CScriptNum(vch, false).getint());
110 } else {
111 // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
112 if (fAttemptSighashDecode && !script.IsUnspendable()) {
113 std::string strSigHashDecode;
114 // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
115 // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
116 // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
117 // checks in CheckSignatureEncoding.
119 const unsigned char chSigHashType = vch.back();
120 const auto it = mapSigHashTypes.find(chSigHashType);
121 if (it != mapSigHashTypes.end()) {
122 strSigHashDecode = "[" + it->second + "]";
123 vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
124 }
125 }
126 str += HexStr(vch) + strSigHashDecode;
127 } else {
128 str += HexStr(vch);
129 }
130 }
131 } else {
132 str += GetOpName(opcode);
133 }
134 }
135 return str;
136}
137
138std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags)
139{
140 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
141 ssTx << tx;
142 return HexStr(ssTx);
143}
144
145void ScriptToUniv(const CScript& script, UniValue& out)
146{
147 ScriptPubKeyToUniv(script, out, /* include_hex */ true, /* include_address */ false);
148}
149
150void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool include_hex, bool include_address)
151{
152 CTxDestination address;
153
154 out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
155 if (include_hex) out.pushKV("hex", HexStr(scriptPubKey));
156
157 std::vector<std::vector<unsigned char>> solns;
158 const TxoutType type{Solver(scriptPubKey, solns)};
159
160 if (include_address && ExtractDestination(scriptPubKey, address) && type != TxoutType::PUBKEY) {
161 out.pushKV("address", EncodeDestination(address));
162 }
163 out.pushKV("type", GetTxnOutputType(type));
164}
165
166void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags, const CTxUndo* txundo, TxVerbosity verbosity)
167{
168 entry.pushKV("txid", tx.GetHash().GetHex());
169 entry.pushKV("hash", tx.GetWitnessHash().GetHex());
170 // Transaction version is actually unsigned in consensus checks, just signed in memory,
171 // so cast to unsigned before giving it to the user.
172 entry.pushKV("version", static_cast<int64_t>(static_cast<uint32_t>(tx.nVersion)));
173 entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
175 entry.pushKV("weight", GetTransactionWeight(tx));
176 entry.pushKV("locktime", (int64_t)tx.nLockTime);
177
179
180 // If available, use Undo data to calculate the fee. Note that txundo == nullptr
181 // for coinbase transactions and for transactions where undo data is unavailable.
182 const bool have_undo = txundo != nullptr;
183 CAmount amt_total_in = 0;
184 CAmount amt_total_out = 0;
185
186 for (unsigned int i = 0; i < tx.vin.size(); i++) {
187 const CTxIn& txin = tx.vin[i];
189 if (tx.IsCoinBase()) {
190 in.pushKV("coinbase", HexStr(txin.scriptSig));
191 } else {
192 in.pushKV("txid", txin.prevout.hash.GetHex());
193 in.pushKV("vout", (int64_t)txin.prevout.n);
195 o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
196 o.pushKV("hex", HexStr(txin.scriptSig));
197 in.pushKV("scriptSig", o);
198 }
199 if (!tx.vin[i].scriptWitness.IsNull()) {
200 UniValue txinwitness(UniValue::VARR);
201 for (const auto& item : tx.vin[i].scriptWitness.stack) {
202 txinwitness.push_back(HexStr(item));
203 }
204 in.pushKV("txinwitness", txinwitness);
205 }
206 if (have_undo) {
207 const Coin& prev_coin = txundo->vprevout[i];
208 const CTxOut& prev_txout = prev_coin.out;
209
210 amt_total_in += prev_txout.nValue;
211 switch (verbosity) {
214 break;
215
217 UniValue o_script_pub_key(UniValue::VOBJ);
218 ScriptPubKeyToUniv(prev_txout.scriptPubKey, o_script_pub_key, /* includeHex */ true);
219
221 p.pushKV("generated", bool(prev_coin.fCoinBase));
222 p.pushKV("height", uint64_t(prev_coin.nHeight));
223 p.pushKV("value", ValueFromAmount(prev_txout.nValue));
224 p.pushKV("scriptPubKey", o_script_pub_key);
225 in.pushKV("prevout", p);
226 break;
227 }
228 }
229 in.pushKV("sequence", (int64_t)txin.nSequence);
230 vin.push_back(in);
231 }
232 entry.pushKV("vin", vin);
233
235 for (unsigned int i = 0; i < tx.vout.size(); i++) {
236 const CTxOut& txout = tx.vout[i];
237
239
240 out.pushKV("value", ValueFromAmount(txout.nValue));
241 out.pushKV("n", (int64_t)i);
242
244 ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
245 out.pushKV("scriptPubKey", o);
246 vout.push_back(out);
247
248 if (have_undo) {
249 amt_total_out += txout.nValue;
250 }
251 }
252 entry.pushKV("vout", vout);
253
254 if (have_undo) {
255 const CAmount fee = amt_total_in - amt_total_out;
257 entry.pushKV("fee", ValueFromAmount(fee));
258 }
259
260 if (!hashBlock.IsNull())
261 entry.pushKV("blockhash", hashBlock.GetHex());
262
263 if (include_hex) {
264 entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
265 }
266}
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:205
uint32_t n
Definition: transaction.h:30
uint256 hash
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:544
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:487
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const uint256 & GetWitnessHash() const
Definition: transaction.h:303
const uint256 & GetHash() const
Definition: transaction.h:302
const uint32_t nLockTime
Definition: transaction.h:273
const std::vector< CTxOut > vout
Definition: transaction.h:271
bool IsCoinBase() const
Definition: transaction.h:315
const int32_t nVersion
Definition: transaction.h:272
const std::vector< CTxIn > vin
Definition: transaction.h:270
An input of a transaction.
Definition: transaction.h:66
uint32_t nSequence
Definition: transaction.h:70
CScript scriptSig
Definition: transaction.h:69
COutPoint prevout
Definition: transaction.h:68
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
CAmount nValue
Definition: transaction.h:131
Undo information for a CTransaction.
Definition: undo.h:54
std::vector< Coin > vprevout
Definition: undo.h:57
A UTXO entry.
Definition: coins.h:31
CTxOut out
unspent transaction output
Definition: coins.h:34
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
@ VOBJ
Definition: univalue.h:19
@ VARR
Definition: univalue.h:19
@ VNUM
Definition: univalue.h:19
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
bool IsNull() const
Definition: uint256.h:31
std::string GetHex() const
Definition: uint256.cpp:20
iterator begin()
Definition: prevector.h:290
iterator end()
Definition: prevector.h:292
256-bit opaque blob.
Definition: uint256.h:124
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
TxVerbosity
Verbose level for block's transaction.
Definition: core_io.h:26
@ 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 ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool include_hex, bool include_address)
Definition: core_write.cpp:150
std::string SighashToStr(unsigned char sighash_type)
Definition: core_write.cpp:79
std::string FormatScript(const CScript &script)
Definition: core_write.cpp:34
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:93
void ScriptToUniv(const CScript &script, UniValue &out)
Definition: core_write.cpp:145
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags)
Definition: core_write.cpp:138
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex, int serialize_flags, const CTxUndo *txundo, TxVerbosity verbosity)
Definition: core_write.cpp:166
const std::map< unsigned char, std::string > mapSigHashTypes
Definition: core_write.cpp:70
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:21
bool CheckSignatureEncoding(const std::vector< unsigned char > &vchSig, unsigned int flags, ScriptError *serror)
@ SCRIPT_VERIFY_STRICTENC
Definition: interpreter.h:51
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:30
@ SIGHASH_ALL
Definition: interpreter.h:27
@ SIGHASH_NONE
Definition: interpreter.h:28
@ SIGHASH_SINGLE
Definition: interpreter.h:29
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:256
std::string GetOpName(opcodetype opcode)
Definition: script.cpp:12
opcodetype
Script opcodes.
Definition: script.h:67
@ OP_PUSHDATA4
Definition: script.h:73
@ OP_1NEGATE
Definition: script.h:74
@ OP_16
Definition: script.h:92
@ OP_NOP10
Definition: script.h:200
@ OP_NOP
Definition: script.h:95
@ OP_1
Definition: script.h:76
@ OP_0
Definition: script.h:69
@ SER_NETWORK
Definition: serialize.h:138
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:144
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:213
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: standard.cpp:49
TxoutType
Definition: standard.h:59
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12