Bitcoin Core  0.19.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(it2, it - vch.size()), HexStr(it - vch.size(), it));
52  } else {
53  ret += strprintf("0x%x ", HexStr(it2, it));
54  }
55  continue;
56  }
57  ret += strprintf("0x%x ", HexStr(it2, script.end()));
58  break;
59  }
60  return ret.substr(0, ret.size() - 1);
61 }
62 
63 const std::map<unsigned char, std::string> mapSigHashTypes = {
64  {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")},
65  {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")},
66  {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")},
67  {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")},
68  {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")},
69  {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")},
70 };
71 
72 std::string SighashToStr(unsigned char sighash_type)
73 {
74  const auto& it = mapSigHashTypes.find(sighash_type);
75  if (it == mapSigHashTypes.end()) return "";
76  return it->second;
77 }
78 
86 std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
87 {
88  std::string str;
89  opcodetype opcode;
90  std::vector<unsigned char> vch;
91  CScript::const_iterator pc = script.begin();
92  while (pc < script.end()) {
93  if (!str.empty()) {
94  str += " ";
95  }
96  if (!script.GetOp(pc, opcode, vch)) {
97  str += "[error]";
98  return str;
99  }
100  if (0 <= opcode && opcode <= OP_PUSHDATA4) {
101  if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
102  str += strprintf("%d", CScriptNum(vch, false).getint());
103  } else {
104  // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
105  if (fAttemptSighashDecode && !script.IsUnspendable()) {
106  std::string strSigHashDecode;
107  // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
108  // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
109  // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
110  // checks in CheckSignatureEncoding.
111  if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) {
112  const unsigned char chSigHashType = vch.back();
113  if (mapSigHashTypes.count(chSigHashType)) {
114  strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]";
115  vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
116  }
117  }
118  str += HexStr(vch) + strSigHashDecode;
119  } else {
120  str += HexStr(vch);
121  }
122  }
123  } else {
124  str += GetOpName(opcode);
125  }
126  }
127  return str;
128 }
129 
130 std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags)
131 {
132  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
133  ssTx << tx;
134  return HexStr(ssTx.begin(), ssTx.end());
135 }
136 
137 void ScriptToUniv(const CScript& script, UniValue& out, bool include_address)
138 {
139  out.pushKV("asm", ScriptToAsmStr(script));
140  out.pushKV("hex", HexStr(script.begin(), script.end()));
141 
142  std::vector<std::vector<unsigned char>> solns;
143  txnouttype type = Solver(script, solns);
144  out.pushKV("type", GetTxnOutputType(type));
145 
146  CTxDestination address;
147  if (include_address && ExtractDestination(script, address) && type != TX_PUBKEY) {
148  out.pushKV("address", EncodeDestination(address));
149  }
150 }
151 
152 void ScriptPubKeyToUniv(const CScript& scriptPubKey,
153  UniValue& out, bool fIncludeHex)
154 {
156  std::vector<CTxDestination> addresses;
157  int nRequired;
158 
159  out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
160  if (fIncludeHex)
161  out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
162 
163  if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) || type == TX_PUBKEY) {
164  out.pushKV("type", GetTxnOutputType(type));
165  return;
166  }
167 
168  out.pushKV("reqSigs", nRequired);
169  out.pushKV("type", GetTxnOutputType(type));
170 
172  for (const CTxDestination& addr : addresses) {
173  a.push_back(EncodeDestination(addr));
174  }
175  out.pushKV("addresses", a);
176 }
177 
178 void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags)
179 {
180  entry.pushKV("txid", tx.GetHash().GetHex());
181  entry.pushKV("hash", tx.GetWitnessHash().GetHex());
182  entry.pushKV("version", tx.nVersion);
183  entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
185  entry.pushKV("weight", GetTransactionWeight(tx));
186  entry.pushKV("locktime", (int64_t)tx.nLockTime);
187 
189  for (unsigned int i = 0; i < tx.vin.size(); i++) {
190  const CTxIn& txin = tx.vin[i];
192  if (tx.IsCoinBase())
193  in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
194  else {
195  in.pushKV("txid", txin.prevout.hash.GetHex());
196  in.pushKV("vout", (int64_t)txin.prevout.n);
198  o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
199  o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
200  in.pushKV("scriptSig", o);
201  if (!tx.vin[i].scriptWitness.IsNull()) {
202  UniValue txinwitness(UniValue::VARR);
203  for (const auto& item : tx.vin[i].scriptWitness.stack) {
204  txinwitness.push_back(HexStr(item.begin(), item.end()));
205  }
206  in.pushKV("txinwitness", txinwitness);
207  }
208  }
209  in.pushKV("sequence", (int64_t)txin.nSequence);
210  vin.push_back(in);
211  }
212  entry.pushKV("vin", vin);
213 
214  UniValue vout(UniValue::VARR);
215  for (unsigned int i = 0; i < tx.vout.size(); i++) {
216  const CTxOut& txout = tx.vout[i];
217 
219 
220  out.pushKV("value", ValueFromAmount(txout.nValue));
221  out.pushKV("n", (int64_t)i);
222 
224  ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
225  out.pushKV("scriptPubKey", o);
226  vout.push_back(out);
227  }
228  entry.pushKV("vout", vout);
229 
230  if (!hashBlock.IsNull())
231  entry.pushKV("blockhash", hashBlock.GetHex());
232 
233  if (include_hex) {
234  entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
235  }
236 }
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:133
CAmount nValue
Definition: transaction.h:136
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex, int serialize_flags)
Definition: core_write.cpp:178
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:156
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CScript scriptPubKey
Definition: transaction.h:137
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< unsigned char > &vchRet) const
Definition: script.h:499
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags)
Definition: core_write.cpp:130
#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
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:91
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:201
bool IsNull() const
Definition: uint256.h:30
bool IsCoinBase() const
Definition: transaction.h:337
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:137
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:152
Definition: script.h:80
const std::vector< CTxIn > vin
Definition: transaction.h:287
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1139
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:86
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:557
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Parse a standard scriptPubKey with one or more destination addresses.
Definition: standard.cpp:200
const std::map< unsigned char, std::string > mapSigHashTypes
Definition: core_write.cpp:63
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:54
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
An input of a transaction.
Definition: transaction.h:63
bool CheckSignatureEncoding(const std::vector< unsigned char > &vchSig, unsigned int flags, ScriptError *serror)
const uint256 & GetWitnessHash() const
Definition: transaction.h:323
const uint256 & GetHash() const
Definition: transaction.h:322
UniValue()
Definition: univalue.h:23
Definition: script.h:64
uint32_t n
Definition: transaction.h:22
Definition: script.h:83
const std::vector< CTxOut > vout
Definition: transaction.h:288
const char * GetTxnOutputType(txnouttype t)
Get the name of a txnouttype as a C string, or nullptr if unknown.
Definition: standard.cpp:28
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
An output of a transaction.
Definition: transaction.h:133
std::string FormatScript(const CScript &script)
Definition: core_write.cpp:28
const char * GetOpName(opcodetype opcode)
Definition: script.cpp:10
std::string SighashToStr(unsigned char sighash_type)
Definition: core_write.cpp:72
CScript scriptSig
Definition: transaction.h:67
txnouttype
Definition: standard.h:55
256-bit opaque blob.
Definition: uint256.h:120
const int32_t nVersion
Definition: transaction.h:289
enum VType type() const
Definition: univalue.h:177
const_iterator end() const
Definition: streams.h:290
const_iterator begin() const
Definition: streams.h:288
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
uint32_t nSequence
Definition: transaction.h:68
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
std::string GetHex() const
Definition: uint256.cpp:20
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:123
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:270
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:143
auto it
Definition: validation.cpp:361
COutPoint prevout
Definition: transaction.h:66
Definition: script.h:57
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:18
const uint32_t nLockTime
Definition: transaction.h:290
uint256 hash
Definition: transaction.h:21