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