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