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 
ValueFromAmount(const CAmount & amount)18 UniValue ValueFromAmount(const CAmount& amount)
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 
FormatScript(const CScript & script)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()) {
34         CScript::const_iterator it2 = it;
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 
SighashToStr(unsigned char sighash_type)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 
79 /**
80  * Create the assembly string representation of a CScript object.
81  * @param[in] script    CScript object to convert into the asm string representation.
82  * @param[in] fAttemptSighashDecode    Whether to attempt to decode sighash types on data within the script that matches the format
83  *                                     of a signature. Only pass true for scripts you believe could contain signatures. For example,
84  *                                     pass false, or omit the this argument (defaults to false), for scriptPubKeys.
85  */
ScriptToAsmStr(const CScript & script,const bool fAttemptSighashDecode)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 
EncodeHexTx(const CTransaction & tx,const int serializeFlags)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 
ScriptToUniv(const CScript & script,UniValue & out,bool include_address)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 
ScriptPubKeyToUniv(const CScript & scriptPubKey,UniValue & out,bool fIncludeHex)152 void ScriptPubKeyToUniv(const CScript& scriptPubKey,
153                         UniValue& out, bool fIncludeHex)
154 {
155     txnouttype type;
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, true) || 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 
171     UniValue a(UniValue::VARR);
172     for (const CTxDestination& addr : addresses) {
173         a.push_back(EncodeDestination(addr));
174     }
175     out.pushKV("addresses", a);
176 }
177 
TxToUniv(const CTransaction & tx,const uint256 & hashBlock,UniValue & entry,bool include_hex,int serialize_flags)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));
184     entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR);
185     entry.pushKV("weight", GetTransactionWeight(tx));
186     entry.pushKV("locktime", (int64_t)tx.nLockTime);
187 
188     UniValue vin(UniValue::VARR);
189     for (unsigned int i = 0; i < tx.vin.size(); i++) {
190         const CTxIn& txin = tx.vin[i];
191         UniValue in(UniValue::VOBJ);
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);
197             UniValue o(UniValue::VOBJ);
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 
218         UniValue out(UniValue::VOBJ);
219 
220         out.pushKV("value", ValueFromAmount(txout.nValue));
221         out.pushKV("n", (int64_t)i);
222 
223         UniValue o(UniValue::VOBJ);
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 }
237