core_write.cpp raw

   1  // Copyright (c) 2009-2022 The Limenka 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 <consensus/amount.h>
   9  #include <consensus/consensus.h>
  10  #include <consensus/validation.h>
  11  #include <key_io.h>
  12  #include <policy/feerate.h>
  13  #include <script/descriptor.h>
  14  #include <script/script.h>
  15  #include <script/solver.h>
  16  #include <serialize.h>
  17  #include <streams.h>
  18  #include <undo.h>
  19  #include <univalue.h>
  20  #include <util/check.h>
  21  #include <util/strencodings.h>
  22  
  23  #include <map>
  24  #include <string>
  25  #include <vector>
  26  
  27  UniValue ValueFromAmount(const CAmount amount)
  28  {
  29      static_assert(COIN > 1);
  30      int64_t quotient = amount / COIN;
  31      int64_t remainder = amount % COIN;
  32      if (amount < 0) {
  33          quotient = -quotient;
  34          remainder = -remainder;
  35      }
  36      return UniValue(UniValue::VNUM,
  37              strprintf("%s%d.%08d", amount < 0 ? "-" : "", quotient, remainder));
  38  }
  39  
  40  UniValue ValueFromFeeRate(const CFeeRate& fee_rate)
  41  {
  42      return UniValue(UniValue::VNUM, fee_rate.SatsToString());
  43  }
  44  
  45  std::string FormatScript(const CScript& script)
  46  {
  47      std::string ret;
  48      CScript::const_iterator it = script.begin();
  49      opcodetype op;
  50      while (it != script.end()) {
  51          CScript::const_iterator it2 = it;
  52          std::vector<unsigned char> vch;
  53          if (script.GetOp(it, op, vch)) {
  54              if (op == OP_0) {
  55                  ret += "0 ";
  56                  continue;
  57              } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
  58                  ret += strprintf("%i ", op - OP_1NEGATE - 1);
  59                  continue;
  60              } else if (op >= OP_NOP && op <= OP_NOP10) {
  61                  std::string str(GetOpName(op));
  62                  if (str.substr(0, 3) == std::string("OP_")) {
  63                      ret += str.substr(3, std::string::npos) + " ";
  64                      continue;
  65                  }
  66              }
  67              if (vch.size() > 0) {
  68                  ret += strprintf("0x%x 0x%x ", HexStr(std::vector<uint8_t>(it2, it - vch.size())),
  69                                                 HexStr(std::vector<uint8_t>(it - vch.size(), it)));
  70              } else {
  71                  ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, it)));
  72              }
  73              continue;
  74          }
  75          ret += strprintf("0x%x ", HexStr(std::vector<uint8_t>(it2, script.end())));
  76          break;
  77      }
  78      return ret.substr(0, ret.empty() ? ret.npos : ret.size() - 1);
  79  }
  80  
  81  const std::map<unsigned char, std::string> mapSigHashTypes = {
  82      {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")},
  83      {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")},
  84      {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")},
  85      {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")},
  86      {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")},
  87      {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")},
  88  };
  89  
  90  std::string SighashToStr(unsigned char sighash_type)
  91  {
  92      const auto& it = mapSigHashTypes.find(sighash_type);
  93      if (it == mapSigHashTypes.end()) return "";
  94      return it->second;
  95  }
  96  
  97  /**
  98   * Create the assembly string representation of a CScript object.
  99   * @param[in] script    CScript object to convert into the asm string representation.
 100   * @param[in] fAttemptSighashDecode    Whether to attempt to decode sighash types on data within the script that matches the format
 101   *                                     of a signature. Only pass true for scripts you believe could contain signatures. For example,
 102   *                                     pass false, or omit the this argument (defaults to false), for scriptPubKeys.
 103   */
 104  std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
 105  {
 106      std::string str;
 107      opcodetype opcode;
 108      std::vector<unsigned char> vch;
 109      CScript::const_iterator pc = script.begin();
 110      while (pc < script.end()) {
 111          if (!str.empty()) {
 112              str += " ";
 113          }
 114          if (!script.GetOp(pc, opcode, vch)) {
 115              str += "[error]";
 116              return str;
 117          }
 118          if (0 <= opcode && opcode <= OP_PUSHDATA4) {
 119              if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
 120                  str += strprintf("%d", CScriptNum(vch, false).getint());
 121              } else {
 122                  // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
 123                  if (fAttemptSighashDecode && !script.IsUnspendable()) {
 124                      std::string strSigHashDecode;
 125                      // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
 126                      // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
 127                      // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
 128                      // checks in CheckSignatureEncoding.
 129                      if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) {
 130                          const unsigned char chSigHashType = vch.back();
 131                          const auto it = mapSigHashTypes.find(chSigHashType);
 132                          if (it != mapSigHashTypes.end()) {
 133                              strSigHashDecode = "[" + it->second + "]";
 134                              vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
 135                          }
 136                      }
 137                      str += HexStr(vch) + strSigHashDecode;
 138                  } else {
 139                      str += HexStr(vch);
 140                  }
 141              }
 142          } else {
 143              str += GetOpName(opcode);
 144          }
 145      }
 146      return str;
 147  }
 148  
 149  std::string EncodeHexTx(const CTransaction& tx)
 150  {
 151      DataStream ssTx;
 152      ssTx << TX_WITH_WITNESS(tx);
 153      return HexStr(ssTx);
 154  }
 155  
 156  void ScriptToUniv(const CScript& script, UniValue& out, bool include_hex, bool include_address, const SigningProvider* provider)
 157  {
 158      CTxDestination address;
 159  
 160      out.pushKV("asm", ScriptToAsmStr(script));
 161      if (include_address) {
 162          out.pushKV("desc", InferDescriptor(script, provider ? *provider : DUMMY_SIGNING_PROVIDER)->ToString());
 163      }
 164      if (include_hex) {
 165          out.pushKV("hex", HexStr(script));
 166      }
 167  
 168      std::vector<std::vector<unsigned char>> solns;
 169      const TxoutType type{Solver(script, solns)};
 170  
 171      if (include_address && ExtractDestination(script, address) && type != TxoutType::PUBKEY) {
 172          out.pushKV("address", EncodeDestination(address));
 173      }
 174      out.pushKV("type", GetTxnOutputType(type));
 175  }
 176  
 177  void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry, bool include_hex, const CTxUndo* txundo, TxVerbosity verbosity)
 178  {
 179      CHECK_NONFATAL(verbosity >= TxVerbosity::SHOW_DETAILS);
 180  
 181      entry.pushKV("txid", tx.GetHash().GetHex());
 182      entry.pushKV("hash", tx.GetWitnessHash().GetHex());
 183      entry.pushKV("version", tx.version);
 184      entry.pushKV("size", tx.GetTotalSize());
 185      entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR);
 186      entry.pushKV("weight", GetTransactionWeight(tx));
 187      entry.pushKV("locktime", (int64_t)tx.nLockTime);
 188  
 189      UniValue vin{UniValue::VARR};
 190      vin.reserve(tx.vin.size());
 191  
 192      // If available, use Undo data to calculate the fee. Note that txundo == nullptr
 193      // for coinbase transactions and for transactions where undo data is unavailable.
 194      const bool have_undo = txundo != nullptr;
 195      CAmount amt_total_in = 0;
 196      CAmount amt_total_out = 0;
 197  
 198      for (unsigned int i = 0; i < tx.vin.size(); i++) {
 199          const CTxIn& txin = tx.vin[i];
 200          UniValue in(UniValue::VOBJ);
 201          if (tx.IsCoinBase()) {
 202              in.pushKV("coinbase", HexStr(txin.scriptSig));
 203          } else {
 204              in.pushKV("txid", txin.prevout.hash.GetHex());
 205              in.pushKV("vout", (int64_t)txin.prevout.n);
 206              UniValue o(UniValue::VOBJ);
 207              o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
 208              o.pushKV("hex", HexStr(txin.scriptSig));
 209              in.pushKV("scriptSig", std::move(o));
 210          }
 211          if (!tx.vin[i].scriptWitness.IsNull()) {
 212              UniValue txinwitness(UniValue::VARR);
 213              txinwitness.reserve(tx.vin[i].scriptWitness.stack.size());
 214              for (const auto& item : tx.vin[i].scriptWitness.stack) {
 215                  txinwitness.push_back(HexStr(item));
 216              }
 217              in.pushKV("txinwitness", std::move(txinwitness));
 218          }
 219          if (have_undo) {
 220              const Coin& prev_coin = txundo->vprevout[i];
 221              const CTxOut& prev_txout = prev_coin.out;
 222  
 223              amt_total_in += prev_txout.nValue;
 224  
 225              if (verbosity == TxVerbosity::SHOW_DETAILS_AND_PREVOUT) {
 226                  UniValue o_script_pub_key(UniValue::VOBJ);
 227                  ScriptToUniv(prev_txout.scriptPubKey, /*out=*/o_script_pub_key, /*include_hex=*/true, /*include_address=*/true);
 228  
 229                  UniValue p(UniValue::VOBJ);
 230                  p.pushKV("generated", bool(prev_coin.fCoinBase));
 231                  p.pushKV("height", uint64_t(prev_coin.nHeight));
 232                  p.pushKV("value", ValueFromAmount(prev_txout.nValue));
 233                  p.pushKV("scriptPubKey", std::move(o_script_pub_key));
 234                  in.pushKV("prevout", std::move(p));
 235              }
 236          }
 237          in.pushKV("sequence", (int64_t)txin.nSequence);
 238          vin.push_back(std::move(in));
 239      }
 240      entry.pushKV("vin", std::move(vin));
 241  
 242      UniValue vout(UniValue::VARR);
 243      vout.reserve(tx.vout.size());
 244      for (unsigned int i = 0; i < tx.vout.size(); i++) {
 245          const CTxOut& txout = tx.vout[i];
 246  
 247          UniValue out(UniValue::VOBJ);
 248  
 249          out.pushKV("value", ValueFromAmount(txout.nValue));
 250          out.pushKV("n", (int64_t)i);
 251  
 252          UniValue o(UniValue::VOBJ);
 253          ScriptToUniv(txout.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
 254          out.pushKV("scriptPubKey", std::move(o));
 255          vout.push_back(std::move(out));
 256  
 257          if (have_undo) {
 258              amt_total_out += txout.nValue;
 259          }
 260      }
 261      entry.pushKV("vout", std::move(vout));
 262  
 263      if (have_undo) {
 264          const CAmount fee = amt_total_in - amt_total_out;
 265          CHECK_NONFATAL(MoneyRange(fee));
 266          entry.pushKV("fee", ValueFromAmount(fee));
 267      }
 268  
 269      if (!block_hash.IsNull()) {
 270          entry.pushKV("blockhash", block_hash.GetHex());
 271      }
 272  
 273      if (include_hex) {
 274          entry.pushKV("hex", EncodeHexTx(tx)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
 275      }
 276  }
 277