Bitcoin ABC  0.26.3
P2P Digital Currency
core_write.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2016 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 <config.h>
8 #include <consensus/amount.h>
9 #include <key_io.h>
10 #include <primitives/blockhash.h>
11 #include <primitives/transaction.h>
12 #include <script/script.h>
13 #include <script/sigencoding.h>
14 #include <script/standard.h>
15 #include <serialize.h>
16 #include <streams.h>
17 #include <undo.h>
18 #include <util/check.h>
19 #include <util/strencodings.h>
20 #include <util/system.h>
21 
22 #include <univalue.h>
23 
24 std::string FormatScript(const CScript &script) {
25  std::string ret;
26  CScript::const_iterator it = script.begin();
27  opcodetype op;
28  while (it != script.end()) {
29  CScript::const_iterator it2 = it;
30  std::vector<uint8_t> vch;
31  if (script.GetOp(it, op, vch)) {
32  if (op == OP_0) {
33  ret += "0 ";
34  continue;
35  }
36 
37  if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
38  ret += strprintf("%i ", op - OP_1NEGATE - 1);
39  continue;
40  }
41 
42  if (op >= OP_NOP && op < FIRST_UNDEFINED_OP_VALUE) {
43  std::string str(GetOpName(op));
44  if (str.substr(0, 3) == std::string("OP_")) {
45  ret += str.substr(3, std::string::npos) + " ";
46  continue;
47  }
48  }
49 
50  if (vch.size() > 0) {
51  ret += strprintf(
52  "0x%x 0x%x ",
53  HexStr(std::vector<uint8_t>(it2, it - vch.size())),
54  HexStr(std::vector<uint8_t>(it - vch.size(), it)));
55  } else {
56  ret +=
57  strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
58  }
59 
60  continue;
61  }
62 
63  ret +=
64  strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
65  break;
66  }
67 
68  return ret.substr(0, ret.size() - 1);
69 }
70 
71 const std::map<uint8_t, std::string> mapSigHashTypes = {
72  {SIGHASH_ALL, "ALL"},
73  {SIGHASH_ALL | SIGHASH_ANYONECANPAY, "ALL|ANYONECANPAY"},
74  {SIGHASH_ALL | SIGHASH_FORKID, "ALL|FORKID"},
76  "ALL|FORKID|ANYONECANPAY"},
77  {SIGHASH_NONE, "NONE"},
78  {SIGHASH_NONE | SIGHASH_ANYONECANPAY, "NONE|ANYONECANPAY"},
79  {SIGHASH_NONE | SIGHASH_FORKID, "NONE|FORKID"},
81  "NONE|FORKID|ANYONECANPAY"},
82  {SIGHASH_SINGLE, "SINGLE"},
83  {SIGHASH_SINGLE | SIGHASH_ANYONECANPAY, "SINGLE|ANYONECANPAY"},
84  {SIGHASH_SINGLE | SIGHASH_FORKID, "SINGLE|FORKID"},
86  "SINGLE|FORKID|ANYONECANPAY"},
87 };
88 
89 std::string SighashToStr(uint8_t sighash_type) {
90  const auto &it = mapSigHashTypes.find(sighash_type);
91  if (it == mapSigHashTypes.end()) {
92  return "";
93  }
94  return it->second;
95 }
96 
106 std::string ScriptToAsmStr(const CScript &script,
107  const bool fAttemptSighashDecode) {
108  std::string str;
109  opcodetype opcode;
110  std::vector<uint8_t> vch;
111  CScript::const_iterator pc = script.begin();
112  while (pc < script.end()) {
113  if (!str.empty()) {
114  str += " ";
115  }
116 
117  if (!script.GetOp(pc, opcode, vch)) {
118  str += "[error]";
119  return str;
120  }
121 
122  if (0 <= opcode && opcode <= OP_PUSHDATA4) {
123  if (vch.size() <= static_cast<std::vector<uint8_t>::size_type>(4)) {
124  str += strprintf("%d", CScriptNum(vch, false).getint());
125  } else {
126  // the IsUnspendable check makes sure not to try to decode
127  // OP_RETURN data that may match the format of a signature
128  if (fAttemptSighashDecode && !script.IsUnspendable()) {
129  std::string strSigHashDecode;
130  // goal: only attempt to decode a defined sighash type from
131  // data that looks like a signature within a scriptSig. This
132  // won't decode correctly formatted public keys in Pubkey or
133  // Multisig scripts due to the restrictions on the pubkey
134  // formats (see IsCompressedOrUncompressedPubKey) being
135  // incongruous with the checks in
136  // CheckTransactionSignatureEncoding.
137  uint32_t flags = SCRIPT_VERIFY_STRICTENC;
138  if (vch.back() & SIGHASH_FORKID) {
139  // If the transaction is using SIGHASH_FORKID, we need
140  // to set the appropriate flag.
141  // TODO: Remove after the Hard Fork.
143  }
145  nullptr)) {
146  const uint8_t chSigHashType = vch.back();
147  const auto it = mapSigHashTypes.find(chSigHashType);
148  if (it != mapSigHashTypes.end()) {
149  strSigHashDecode = "[" + it->second + "]";
150  // remove the sighash type byte. it will be replaced
151  // by the decode.
152  vch.pop_back();
153  }
154  }
155 
156  str += HexStr(vch) + strSigHashDecode;
157  } else {
158  str += HexStr(vch);
159  }
160  }
161  } else {
162  str += GetOpName(opcode);
163  }
164  }
165 
166  return str;
167 }
168 
169 std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags) {
170  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags);
171  ssTx << tx;
172  return HexStr(ssTx);
173 }
174 
175 void ScriptToUniv(const CScript &script, UniValue &out, bool include_address) {
176  out.pushKV("asm", ScriptToAsmStr(script));
177  out.pushKV("hex", HexStr(script));
178 
179  std::vector<std::vector<uint8_t>> solns;
180  TxoutType type = Solver(script, solns);
181  out.pushKV("type", GetTxnOutputType(type));
182 
183  CTxDestination address;
184  if (include_address && ExtractDestination(script, address) &&
185  type != TxoutType::PUBKEY) {
186  out.pushKV("address", EncodeDestination(address, GetConfig()));
187  }
188 }
189 
190 void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out,
191  bool fIncludeHex) {
192  TxoutType type;
193  std::vector<CTxDestination> addresses;
194  int nRequired;
195 
196  out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
197  if (fIncludeHex) {
198  out.pushKV("hex", HexStr(scriptPubKey));
199  }
200 
201  if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) ||
202  type == TxoutType::PUBKEY) {
203  out.pushKV("type", GetTxnOutputType(type));
204  return;
205  }
206 
207  out.pushKV("reqSigs", nRequired);
208  out.pushKV("type", GetTxnOutputType(type));
209 
211  for (const CTxDestination &addr : addresses) {
213  }
214  out.pushKV("addresses", a);
215 }
216 
217 void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock,
218  UniValue &entry, bool include_hex, int serialize_flags,
219  const CTxUndo *txundo) {
220  entry.pushKV("txid", tx.GetId().GetHex());
221  entry.pushKV("hash", tx.GetHash().GetHex());
222  // Transaction version is actually unsigned in consensus checks, just
223  // signed in memory, so cast to unsigned before giving it to the user.
224  entry.pushKV("version",
225  static_cast<int64_t>(static_cast<uint32_t>(tx.nVersion)));
226  entry.pushKV("size", (int)::GetSerializeSize(tx, PROTOCOL_VERSION));
227  entry.pushKV("locktime", (int64_t)tx.nLockTime);
228 
230 
231  // If available, use Undo data to calculate the fee. Note that
232  // txundo == nullptr for coinbase transactions and for transactions where
233  // undo data is unavailable.
234  const bool calculate_fee = txundo != nullptr;
235  Amount amt_total_in = Amount::zero();
236  Amount amt_total_out = Amount::zero();
237 
238  for (unsigned int i = 0; i < tx.vin.size(); i++) {
239  const CTxIn &txin = tx.vin[i];
241  if (tx.IsCoinBase()) {
242  in.pushKV("coinbase", HexStr(txin.scriptSig));
243  } else {
244  in.pushKV("txid", txin.prevout.GetTxId().GetHex());
245  in.pushKV("vout", int64_t(txin.prevout.GetN()));
247  o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
248  o.pushKV("hex", HexStr(txin.scriptSig));
249  in.pushKV("scriptSig", o);
250  }
251  if (calculate_fee) {
252  const CTxOut &prev_txout = txundo->vprevout[i].GetTxOut();
253  amt_total_in += prev_txout.nValue;
254  }
255  in.pushKV("sequence", (int64_t)txin.nSequence);
256  vin.push_back(in);
257  }
258 
259  entry.pushKV("vin", vin);
260 
261  UniValue vout(UniValue::VARR);
262  for (unsigned int i = 0; i < tx.vout.size(); i++) {
263  const CTxOut &txout = tx.vout[i];
264 
266 
267  out.pushKV("value", txout.nValue);
268  out.pushKV("n", int64_t(i));
269 
271  ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
272  out.pushKV("scriptPubKey", o);
273  vout.push_back(out);
274 
275  if (calculate_fee) {
276  amt_total_out += txout.nValue;
277  }
278  }
279 
280  entry.pushKV("vout", vout);
281 
282  if (calculate_fee) {
283  const Amount fee = amt_total_in - amt_total_out;
285  entry.pushKV("fee", fee);
286  }
287 
288  if (!hashBlock.IsNull()) {
289  entry.pushKV("blockhash", hashBlock.GetHex());
290  }
291 
292  if (include_hex) {
293  // The hex-encoded transaction. Used the name "hex" to be consistent
294  // with the verbose output of "getrawtransaction".
295  entry.pushKV("hex", EncodeHexTx(tx, serialize_flags));
296  }
297 }
bool MoneyRange(const Amount nValue)
Definition: amount.h:176
int flags
Definition: bitcoin-tx.cpp:534
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:197
uint32_t GetN() const
Definition: transaction.h:38
const TxId & GetTxId() const
Definition: transaction.h:37
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:549
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< uint8_t > &vchRet) const
Definition: script.h:502
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
const uint32_t nLockTime
Definition: transaction.h:213
const std::vector< CTxOut > vout
Definition: transaction.h:211
bool IsCoinBase() const
Definition: transaction.h:256
const int32_t nVersion
Definition: transaction.h:212
const TxHash GetHash() const
Definition: transaction.h:245
const std::vector< CTxIn > vin
Definition: transaction.h:210
const TxId GetId() const
Definition: transaction.h:244
An input of a transaction.
Definition: transaction.h:61
uint32_t nSequence
Definition: transaction.h:65
CScript scriptSig
Definition: transaction.h:64
COutPoint prevout
Definition: transaction.h:63
An output of a transaction.
Definition: transaction.h:130
CScript scriptPubKey
Definition: transaction.h:133
Amount nValue
Definition: transaction.h:132
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
std::vector< Coin > vprevout
Definition: undo.h:65
@ VOBJ
Definition: univalue.h:27
@ VARR
Definition: univalue.h:27
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
bool IsNull() const
Definition: uint256.h:30
std::string GetHex() const
Definition: uint256.cpp:16
iterator begin()
Definition: prevector.h:390
iterator end()
Definition: prevector.h:392
const Config & GetConfig()
Definition: config.cpp:34
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:175
std::string SighashToStr(uint8_t sighash_type)
Definition: core_write.cpp:89
std::string FormatScript(const CScript &script)
Definition: core_write.cpp:24
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:190
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:106
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex, int serialize_flags, const CTxUndo *txundo)
Definition: core_write.cpp:217
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags)
Definition: core_write.cpp:169
const std::map< uint8_t, std::string > mapSigHashTypes
Definition: core_write.cpp:71
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:170
std::string GetOpName(opcodetype opcode)
Definition: script.cpp:14
opcodetype
Script opcodes.
Definition: script.h:47
@ OP_PUSHDATA4
Definition: script.h:53
@ OP_1NEGATE
Definition: script.h:54
@ OP_16
Definition: script.h:72
@ FIRST_UNDEFINED_OP_VALUE
Definition: script.h:190
@ OP_NOP
Definition: script.h:75
@ OP_1
Definition: script.h:56
@ OP_0
Definition: script.h:49
@ SCRIPT_VERIFY_STRICTENC
Definition: script_flags.h:22
@ SCRIPT_ENABLE_SIGHASH_FORKID
Definition: script_flags.h:85
@ SER_NETWORK
Definition: serialize.h:166
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1259
bool CheckTransactionSignatureEncoding(const valtype &vchSig, uint32_t flags, ScriptError *serror)
Check that the signature provided to authentify a transaction is properly encoded.
@ SIGHASH_FORKID
Definition: sighashtype.h:18
@ SIGHASH_ANYONECANPAY
Definition: sighashtype.h:19
@ SIGHASH_ALL
Definition: sighashtype.h:15
@ SIGHASH_NONE
Definition: sighashtype.h:16
@ SIGHASH_SINGLE
Definition: sighashtype.h:17
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:161
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: standard.cpp:32
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:111
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:187
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:93
TxoutType
Definition: standard.h:46
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: amount.h:19
static constexpr Amount zero()
Definition: amount.h:42
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11