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