Bitcoin Core  0.20.99
P2P Digital Currency
core_write.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2019 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 <univalue.h>
15 #include <util/system.h>
16 #include <util/strencodings.h>
17 
19 {
20  bool sign = amount < 0;
21  int64_t n_abs = (sign ? -amount : amount);
22  int64_t quotient = n_abs / COIN;
23  int64_t remainder = n_abs % COIN;
24  return UniValue(UniValue::VNUM,
25  strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder));
26 }
27 
28 std::string FormatScript(const CScript& script)
29 {
30  std::string ret;
31  CScript::const_iterator it = script.begin();
32  opcodetype op;
33  while (it != script.end()) {
35  std::vector<unsigned char> vch;
36  if (script.GetOp(it, op, vch)) {
37  if (op == OP_0) {
38  ret += "0 ";
39  continue;
40  } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
41  ret += strprintf("%i ", op - OP_1NEGATE - 1);
42  continue;
43  } else if (op >= OP_NOP && op <= OP_NOP10) {
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  if (vch.size() > 0) {
51  ret += strprintf("0x%x 0x%x ", HexStr(std::vector<uint8_t>(it2, it - vch.size())),
52  HexStr(std::vector<uint8_t>(it - vch.size(), it)));
53  } else {
54  ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
55  }
56  continue;
57  }
58  ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
59  break;
60  }
61  return ret.substr(0, ret.size() - 1);
62 }
63 
64 const std::map<unsigned char, std::string> mapSigHashTypes = {
65  {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")},
66  {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")},
67  {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")},
68  {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")},
69  {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")},
70  {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")},
71 };
72 
73 std::string SighashToStr(unsigned char sighash_type)
74 {
75  const auto& it = mapSigHashTypes.find(sighash_type);
76  if (it == mapSigHashTypes.end()) return "";
77  return it->second;
78 }
79 
87 std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
88 {
89  std::string str;
90  opcodetype opcode;
91  std::vector<unsigned char> vch;
92  CScript::const_iterator pc = script.begin();
93  while (pc < script.end()) {
94  if (!str.empty()) {
95  str += " ";
96  }
97  if (!script.GetOp(pc, opcode, vch)) {
98  str += "[error]";
99  return str;
100  }
101  if (0 <= opcode && opcode <= OP_PUSHDATA4) {
102  if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
103  str += strprintf("%d", CScriptNum(vch, false).getint());
104  } else {
105  // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
106  if (fAttemptSighashDecode && !script.IsUnspendable()) {
107  std::string strSigHashDecode;
108  // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
109  // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
110  // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
111  // checks in CheckSignatureEncoding.
112  if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) {
113  const unsigned char chSigHashType = vch.back();
114  const auto it = mapSigHashTypes.find(chSigHashType);
115  if (it != mapSigHashTypes.end()) {
116  strSigHashDecode = "[" + it->second + "]";
117  vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
118  }
119  }
120  str += HexStr(vch) + strSigHashDecode;
121  } else {
122  str += HexStr(vch);
123  }
124  }
125  } else {
126  str += GetOpName(opcode);
127  }
128  }
129  return str;
130 }
131 
132 std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags)
133 {
134  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
135  ssTx << tx;
136  return HexStr(ssTx);
137 }
138 
139 void ScriptToUniv(const CScript& script, UniValue& out, bool include_address)
140 {
141  out.pushKV("asm", ScriptToAsmStr(script));
142  out.pushKV("hex", HexStr(script));
143 
144  std::vector<std::vector<unsigned char>> solns;
145  TxoutType type = Solver(script, solns);
146  out.pushKV("type", GetTxnOutputType(type));
147 
148  CTxDestination address;
149  if (include_address && ExtractDestination(script, address) && type != TxoutType::PUBKEY) {
150  out.pushKV("address", EncodeDestination(address));
151  }
152 }
153 
154 void ScriptPubKeyToUniv(const CScript& scriptPubKey,
155  UniValue& out, bool fIncludeHex)
156 {
157  TxoutType type;
158  std::vector<CTxDestination> addresses;
159  int nRequired;
160 
161  out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
162  if (fIncludeHex)
163  out.pushKV("hex", HexStr(scriptPubKey));
164 
165  if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) || type == TxoutType::PUBKEY) {
166  out.pushKV("type", GetTxnOutputType(type));
167  return;
168  }
169 
170  out.pushKV("reqSigs", nRequired);
171  out.pushKV("type", GetTxnOutputType(type));
172 
174  for (const CTxDestination& addr : addresses) {
175  a.push_back(EncodeDestination(addr));
176  }
177  out.pushKV("addresses", a);
178 }
179 
180 void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags)
181 {
182  entry.pushKV("txid", tx.GetHash().GetHex());
183  entry.pushKV("hash", tx.GetWitnessHash().GetHex());
184  // Transaction version is actually unsigned in consensus checks, just signed in memory,
185  // so cast to unsigned before giving it to the user.
186  entry.pushKV("version", static_cast<int64_t>(static_cast<uint32_t>(tx.nVersion)));
187  entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
189  entry.pushKV("weight", GetTransactionWeight(tx));
190  entry.pushKV("locktime", (int64_t)tx.nLockTime);
191 
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  in.pushKV("sequence", (int64_t)txin.nSequence);
214  vin.push_back(in);
215  }
216  entry.pushKV("vin", vin);
217 
218  UniValue vout(UniValue::VARR);
219  for (unsigned int i = 0; i < tx.vout.size(); i++) {
220  const CTxOut& txout = tx.vout[i];
221 
223 
224  out.pushKV("value", ValueFromAmount(txout.nValue));
225  out.pushKV("n", (int64_t)i);
226 
228  ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
229  out.pushKV("scriptPubKey", o);
230  vout.push_back(out);
231  }
232  entry.pushKV("vout", vout);
233 
234  if (!hashBlock.IsNull())
235  entry.pushKV("blockhash", hashBlock.GetHex());
236 
237  if (include_hex) {
238  entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
239  }
240 }
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)
Definition: core_write.cpp:180
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:132
#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
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:202
bool IsNull() const
Definition: uint256.h:31
bool IsCoinBase() const
Definition: transaction.h:324
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:139
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:154
Definition: script.h:91
const std::vector< CTxIn > vin
Definition: transaction.h:276
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:87
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:64
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:312
const uint256 & GetHash() const
Definition: transaction.h:311
TxoutType
Definition: standard.h:122
UniValue()
Definition: univalue.h:23
Definition: script.h:75
uint32_t n
Definition: transaction.h:30
Definition: script.h:94
const std::vector< CTxOut > vout
Definition: transaction.h:277
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:28
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:73
CScript scriptSig
Definition: transaction.h:69
256-bit opaque blob.
Definition: uint256.h:124
const int32_t nVersion
Definition: transaction.h:278
enum VType type() const
Definition: univalue.h:177
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
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:210
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:214
COutPoint prevout
Definition: transaction.h:68
Definition: script.h:68
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:18
const uint32_t nLockTime
Definition: transaction.h:279
uint256 hash
Definition: transaction.h:29