Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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 <common/system.h>
8#include <config.h>
9#include <consensus/amount.h>
10#include <key_io.h>
13#include <script/script.h>
14#include <script/sigencoding.h>
15#include <script/standard.h>
16#include <serialize.h>
17#include <streams.h>
18#include <undo.h>
19#include <util/check.h>
20#include <util/strencodings.h>
21
22#include <univalue.h>
23
24std::string FormatScript(const CScript &script) {
25 std::string ret;
26 CScript::const_iterator it = script.begin();
28 while (it != script.end()) {
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
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
71const 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
89std::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
106std::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.
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
169std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags) {
171 ssTx << tx;
172 return HexStr(ssTx);
173}
174
175void 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
190void 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) {
212 a.push_back(EncodeDestination(addr, GetConfig()));
213 }
214 out.pushKV("addresses", a);
215}
216
217void 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;
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();
254 }
255 in.pushKV("sequence", (int64_t)txin.nSequence);
256 vin.push_back(in);
257 }
258
259 entry.pushKV("vin", vin);
260
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:166
int flags
#define CHECK_NONFATAL(condition)
Identity function.
Definition check.h:53
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:177
Serialized script, used inside transaction inputs and outputs.
Definition script.h:424
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition script.h:541
bool GetOp(const_iterator &pc, opcodetype &opcodeRet, std::vector< uint8_t > &vchRet) const
Definition script.h:495
The basic transaction that is broadcasted on the network and contained in blocks.
const uint32_t nLockTime
const std::vector< CTxOut > vout
bool IsCoinBase() const
const int32_t nVersion
const TxHash GetHash() const
const std::vector< CTxIn > vin
const TxId GetId() const
An input of a transaction.
Definition transaction.h:59
An output of a transaction.
CScript scriptPubKey
Amount nValue
Restore the UTXO in a Coin at a given COutPoint.
Definition undo.h:62
void push_back(UniValue val)
Definition univalue.cpp:96
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:115
bool IsNull() const
Definition uint256.h:32
std::string GetHex() const
Definition uint256.cpp:16
iterator begin()
Definition prevector.h:398
iterator end()
Definition prevector.h:400
const Config & GetConfig()
Definition config.cpp:40
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
std::string SighashToStr(uint8_t sighash_type)
std::string FormatScript(const CScript &script)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex, int serialize_flags, const CTxUndo *txundo)
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags)
const std::map< uint8_t, std::string > mapSigHashTypes
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition key_io.cpp:167
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
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
@ SCRIPT_ENABLE_SIGHASH_FORKID
@ SER_NETWORK
Definition serialize.h:152
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition serialize.h:1258
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:158
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:108
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition standard.cpp:29
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:184
TxoutType
Definition standard.h:38
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition standard.h:85
static constexpr Amount zero() noexcept
Definition amount.h:32
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...
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static const int PROTOCOL_VERSION
network protocol versioning
Definition version.h:11