LCOV - code coverage report
Current view: top level - src - bitcoin-tx.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 0.0 % 519 0
Test Date: 2026-11-23 06:11:08 Functions: 0.0 % 30 0
Branches: 0.0 % 1046 0

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-present 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 <bitcoin-build-config.h>
       6                 :             : 
       7                 :             : #include <chainparamsbase.h>
       8                 :             : #include <clientversion.h>
       9                 :             : #include <coins.h>
      10                 :             : #include <common/args.h>
      11                 :             : #include <common/license_info.h>
      12                 :             : #include <common/system.h>
      13                 :             : #include <compat/compat.h>
      14                 :             : #include <consensus/amount.h>
      15                 :             : #include <consensus/consensus.h>
      16                 :             : #include <core_io.h>
      17                 :             : #include <crypto/sha256.h>
      18                 :             : #include <key_io.h>
      19                 :             : #include <policy/policy.h>
      20                 :             : #include <primitives/transaction.h>
      21                 :             : #include <script/script.h>
      22                 :             : #include <script/sign.h>
      23                 :             : #include <script/signingprovider.h>
      24                 :             : #include <univalue.h>
      25                 :             : #include <util/exception.h>
      26                 :             : #include <util/fs.h>
      27                 :             : #include <util/moneystr.h>
      28                 :             : #include <util/rbf.h>
      29                 :             : #include <util/strencodings.h>
      30                 :             : #include <util/string.h>
      31                 :             : #include <util/translation.h>
      32                 :             : 
      33                 :             : #include <cstdio>
      34                 :             : #include <functional>
      35                 :             : #include <memory>
      36                 :             : 
      37                 :             : using util::SplitString;
      38                 :             : using util::ToString;
      39                 :             : using util::TrimString;
      40                 :             : using util::TrimStringView;
      41                 :             : 
      42                 :             : static bool fCreateBlank;
      43                 :             : static std::map<std::string,UniValue> registers;
      44                 :             : static const int CONTINUE_EXECUTION=-1;
      45                 :             : 
      46                 :             : const TranslateFn G_TRANSLATION_FUN{nullptr};
      47                 :             : 
      48                 :           0 : static void SetupBitcoinTxArgs(ArgsManager &argsman)
      49                 :             : {
      50                 :           0 :     SetupHelpOptions(argsman);
      51                 :             : 
      52   [ #  #  #  # ]:           0 :     argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
      53   [ #  #  #  # ]:           0 :     argsman.AddArg("-create", "Create new, empty TX.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
      54   [ #  #  #  # ]:           0 :     argsman.AddArg("-json", "Select JSON output", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
      55   [ #  #  #  # ]:           0 :     argsman.AddArg("-txid", "Output only the hex-encoded transaction id of the resultant transaction.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
      56                 :           0 :     SetupChainParamsBaseOptions(argsman);
      57                 :             : 
      58   [ #  #  #  # ]:           0 :     argsman.AddArg("delin=N", "Delete input N from TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      59   [ #  #  #  # ]:           0 :     argsman.AddArg("delout=N", "Delete output N from TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      60   [ #  #  #  # ]:           0 :     argsman.AddArg("in=TXID:VOUT[:SEQUENCE_NUMBER]", "Add input to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      61   [ #  #  #  # ]:           0 :     argsman.AddArg("locktime=N", "Set TX lock time to N", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      62   [ #  #  #  # ]:           0 :     argsman.AddArg("nversion=N", "Set TX version to N", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      63   [ #  #  #  # ]:           0 :     argsman.AddArg("outaddr=VALUE:ADDRESS", "Add address-based output to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      64   [ #  #  #  # ]:           0 :     argsman.AddArg("outdata=[VALUE:]DATA", "Add data-based output to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      65   [ #  #  #  # ]:           0 :     argsman.AddArg("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", "Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. "
      66                 :             :         "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
      67                 :           0 :         "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      68   [ #  #  #  # ]:           0 :     argsman.AddArg("outpubkey=VALUE:PUBKEY[:FLAGS]", "Add pay-to-pubkey output to TX. "
      69                 :             :         "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. "
      70                 :           0 :         "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      71   [ #  #  #  # ]:           0 :     argsman.AddArg("outscript=VALUE:SCRIPT[:FLAGS]", "Add raw script output to TX. "
      72                 :             :         "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
      73                 :           0 :         "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      74   [ #  #  #  # ]:           0 :     argsman.AddArg("replaceable(=N)", "Sets Replace-By-Fee (RBF) opt-in sequence number for input N. "
      75                 :             :         "If N is not provided, the command attempts to opt-in all available inputs for RBF. "
      76                 :           0 :         "If the transaction has no inputs, this option is ignored.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      77   [ #  #  #  # ]:           0 :     argsman.AddArg("sign=SIGHASH-FLAGS", "Add zero or more signatures to transaction. "
      78                 :             :         "This command requires JSON registers:"
      79                 :             :         "prevtxs=JSON object, "
      80                 :             :         "privatekeys=JSON object. "
      81                 :           0 :         "See signrawtransactionwithkey docs for format of sighash flags, JSON objects.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
      82                 :             : 
      83   [ #  #  #  # ]:           0 :     argsman.AddArg("load=NAME:FILENAME", "Load JSON file FILENAME into register NAME", ArgsManager::ALLOW_ANY, OptionsCategory::REGISTER_COMMANDS);
      84   [ #  #  #  # ]:           0 :     argsman.AddArg("set=NAME:JSON-STRING", "Set register NAME to given JSON-STRING", ArgsManager::ALLOW_ANY, OptionsCategory::REGISTER_COMMANDS);
      85                 :           0 : }
      86                 :             : 
      87                 :             : //
      88                 :             : // This function returns either one of EXIT_ codes when it's expected to stop the process or
      89                 :             : // CONTINUE_EXECUTION when it's expected to continue further.
      90                 :             : //
      91                 :           0 : static int AppInitRawTx(int argc, char* argv[])
      92                 :             : {
      93                 :           0 :     SetupBitcoinTxArgs(gArgs);
      94         [ #  # ]:           0 :     std::string error;
      95   [ #  #  #  # ]:           0 :     if (!gArgs.ParseParameters(argc, argv, error)) {
      96         [ #  # ]:           0 :         tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
      97                 :             :         return EXIT_FAILURE;
      98                 :             :     }
      99                 :             : 
     100                 :             :     // Check for chain settings (Params() calls are only valid after this clause)
     101                 :           0 :     try {
     102   [ #  #  #  # ]:           0 :         SelectParams(gArgs.GetChainType());
     103         [ -  - ]:           0 :     } catch (const std::exception& e) {
     104         [ -  - ]:           0 :         tfm::format(std::cerr, "Error: %s\n", e.what());
     105                 :           0 :         return EXIT_FAILURE;
     106                 :           0 :     }
     107                 :             : 
     108   [ #  #  #  # ]:           0 :     fCreateBlank = gArgs.GetBoolArg("-create", false);
     109                 :             : 
     110   [ #  #  #  #  :           0 :     if (argc < 2 || HelpRequested(gArgs) || gArgs.GetBoolArg("-version", false)) {
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     111                 :             :         // First part of help message is specific to this utility
     112   [ #  #  #  # ]:           0 :         std::string strUsage = CLIENT_NAME " bitcoin-tx utility version " + FormatFullVersion() + "\n";
     113                 :             : 
     114   [ #  #  #  #  :           0 :         if (gArgs.GetBoolArg("-version", false)) {
                   #  # ]
     115   [ #  #  #  # ]:           0 :             strUsage += FormatParagraph(LicenseInfo());
     116                 :             :         } else {
     117         [ #  # ]:           0 :             strUsage += "\n"
     118                 :             :                 "The bitcoin-tx tool is used for creating and modifying bitcoin transactions.\n\n"
     119                 :             :                 "bitcoin-tx can be used with \"<hex-tx> [commands]\" to update a hex-encoded bitcoin transaction, or with \"-create [commands]\" to create a hex-encoded bitcoin transaction.\n"
     120                 :             :                 "\n"
     121                 :             :                 "Usage: bitcoin-tx [options] <hex-tx> [commands]\n"
     122                 :             :                 "or:    bitcoin-tx [options] -create [commands]\n"
     123                 :           0 :                 "\n";
     124         [ #  # ]:           0 :             strUsage += gArgs.GetHelpMessage();
     125                 :             :         }
     126                 :             : 
     127         [ #  # ]:           0 :         tfm::format(std::cout, "%s", strUsage);
     128                 :             : 
     129         [ #  # ]:           0 :         if (argc < 2) {
     130         [ #  # ]:           0 :             tfm::format(std::cerr, "Error: too few parameters\n");
     131                 :             :             return EXIT_FAILURE;
     132                 :             :         }
     133                 :             :         return EXIT_SUCCESS;
     134                 :           0 :     }
     135                 :             :     return CONTINUE_EXECUTION;
     136                 :           0 : }
     137                 :             : 
     138                 :           0 : static void RegisterSetJson(const std::string& key, const std::string& rawJson)
     139                 :             : {
     140         [ #  # ]:           0 :     UniValue val;
     141   [ #  #  #  #  :           0 :     if (!val.read(rawJson)) {
                   #  # ]
     142         [ #  # ]:           0 :         std::string strErr = "Cannot parse JSON for key " + key;
     143         [ #  # ]:           0 :         throw std::runtime_error(strErr);
     144                 :           0 :     }
     145                 :             : 
     146   [ #  #  #  # ]:           0 :     registers[key] = val;
     147                 :           0 : }
     148                 :             : 
     149                 :           0 : static void RegisterSet(const std::string& strInput)
     150                 :             : {
     151                 :             :     // separate NAME:VALUE in string
     152                 :           0 :     size_t pos = strInput.find(':');
     153                 :           0 :     if ((pos == std::string::npos) ||
     154         [ #  # ]:           0 :         (pos == 0) ||
     155         [ #  # ]:           0 :         (pos == (strInput.size() - 1)))
     156         [ #  # ]:           0 :         throw std::runtime_error("Register input requires NAME:VALUE");
     157                 :             : 
     158                 :           0 :     std::string key = strInput.substr(0, pos);
     159         [ #  # ]:           0 :     std::string valStr = strInput.substr(pos + 1, std::string::npos);
     160                 :             : 
     161         [ #  # ]:           0 :     RegisterSetJson(key, valStr);
     162                 :           0 : }
     163                 :             : 
     164                 :           0 : static void RegisterLoad(const std::string& strInput)
     165                 :             : {
     166                 :             :     // separate NAME:FILENAME in string
     167                 :           0 :     size_t pos = strInput.find(':');
     168                 :           0 :     if ((pos == std::string::npos) ||
     169         [ #  # ]:           0 :         (pos == 0) ||
     170         [ #  # ]:           0 :         (pos == (strInput.size() - 1)))
     171         [ #  # ]:           0 :         throw std::runtime_error("Register load requires NAME:FILENAME");
     172                 :             : 
     173                 :           0 :     std::string key = strInput.substr(0, pos);
     174         [ #  # ]:           0 :     std::string filename = strInput.substr(pos + 1, std::string::npos);
     175                 :             : 
     176   [ #  #  #  # ]:           0 :     FILE *f = fsbridge::fopen(filename.c_str(), "r");
     177         [ #  # ]:           0 :     if (!f) {
     178         [ #  # ]:           0 :         std::string strErr = "Cannot open file " + filename;
     179         [ #  # ]:           0 :         throw std::runtime_error(strErr);
     180                 :           0 :     }
     181                 :             : 
     182                 :             :     // load file chunks into one big buffer
     183                 :           0 :     std::string valStr;
     184   [ #  #  #  # ]:           0 :     while ((!feof(f)) && (!ferror(f))) {
     185                 :           0 :         char buf[4096];
     186         [ #  # ]:           0 :         int bread = fread(buf, 1, sizeof(buf), f);
     187         [ #  # ]:           0 :         if (bread <= 0)
     188                 :             :             break;
     189                 :             : 
     190   [ #  #  #  # ]:           0 :         valStr.insert(valStr.size(), buf, bread);
     191                 :             :     }
     192                 :             : 
     193                 :           0 :     int error = ferror(f);
     194         [ #  # ]:           0 :     fclose(f);
     195                 :             : 
     196         [ #  # ]:           0 :     if (error) {
     197         [ #  # ]:           0 :         std::string strErr = "Error reading file " + filename;
     198         [ #  # ]:           0 :         throw std::runtime_error(strErr);
     199                 :           0 :     }
     200                 :             : 
     201                 :             :     // evaluate as JSON buffer register
     202         [ #  # ]:           0 :     RegisterSetJson(key, valStr);
     203                 :           0 : }
     204                 :             : 
     205                 :           0 : static CAmount ExtractAndValidateValue(const std::string& strValue)
     206                 :             : {
     207         [ #  # ]:           0 :     if (std::optional<CAmount> parsed = ParseMoney(strValue)) {
     208                 :           0 :         return parsed.value();
     209                 :             :     } else {
     210         [ #  # ]:           0 :         throw std::runtime_error("invalid TX output value");
     211                 :             :     }
     212                 :             : }
     213                 :             : 
     214                 :           0 : static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
     215                 :             : {
     216         [ #  # ]:           0 :     const auto ver{ToIntegral<uint32_t>(cmdVal)};
     217   [ #  #  #  #  :           0 :     if (!ver || *ver < 1 || *ver > TX_MAX_STANDARD_VERSION) {
                   #  # ]
     218   [ #  #  #  # ]:           0 :         throw std::runtime_error("Invalid TX version requested: '" + cmdVal + "'");
     219                 :             :     }
     220                 :           0 :     tx.version = *ver;
     221                 :           0 : }
     222                 :             : 
     223                 :           0 : static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
     224                 :             : {
     225         [ #  # ]:           0 :     const auto locktime{ToIntegral<uint32_t>(cmdVal)};
     226         [ #  # ]:           0 :     if (!locktime) {
     227   [ #  #  #  # ]:           0 :         throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal + "'");
     228                 :             :     }
     229                 :           0 :     tx.nLockTime = *locktime;
     230                 :           0 : }
     231                 :             : 
     232                 :           0 : static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
     233                 :             : {
     234         [ #  # ]:           0 :     const auto idx{ToIntegral<uint32_t>(strInIdx)};
     235   [ #  #  #  #  :           0 :     if (strInIdx != "" && (!idx || *idx >= tx.vin.size())) {
             #  #  #  # ]
     236   [ #  #  #  # ]:           0 :         throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
     237                 :             :     }
     238                 :             : 
     239                 :             :     // set the nSequence to MAX_INT - 2 (= RBF opt in flag)
     240                 :           0 :     uint32_t cnt{0};
     241         [ #  # ]:           0 :     for (CTxIn& txin : tx.vin) {
     242   [ #  #  #  # ]:           0 :         if (strInIdx == "" || cnt == *idx) {
     243         [ #  # ]:           0 :             if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
     244                 :           0 :                 txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
     245                 :             :             }
     246                 :             :         }
     247                 :           0 :         ++cnt;
     248                 :             :     }
     249                 :           0 : }
     250                 :             : 
     251                 :             : template <typename T>
     252                 :           0 : static T TrimAndParse(const std::string& int_str, const std::string& err)
     253                 :             : {
     254   [ #  #  #  # ]:           0 :     const auto parsed{ToIntegral<T>(TrimStringView(int_str))};
     255         [ #  # ]:           0 :     if (!parsed.has_value()) {
     256   [ #  #  #  #  :           0 :         throw std::runtime_error(err + " '" + int_str + "'");
                   #  # ]
     257                 :             :     }
     258                 :           0 :     return parsed.value();
     259                 :             : }
     260                 :             : 
     261                 :           0 : static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
     262                 :             : {
     263         [ #  # ]:           0 :     std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
     264                 :             : 
     265   [ #  #  #  #  :           0 :     if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
                   #  # ]
     266         [ #  # ]:           0 :         throw std::runtime_error("Invalid format, expected in=TXID:VOUT[:SEQUENCE_NUMBER]");
     267                 :             :     }
     268                 :             : 
     269                 :             :     // extract and validate TXID
     270   [ #  #  #  # ]:           0 :     auto txid{Txid::FromHex(vStrInputParts[0])};
     271         [ #  # ]:           0 :     if (!txid) {
     272         [ #  # ]:           0 :         throw std::runtime_error("invalid TX input txid");
     273                 :             :     }
     274                 :             : 
     275                 :           0 :     static const unsigned int minTxOutSz = 9;
     276                 :           0 :     static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz);
     277                 :             : 
     278                 :             :     // extract and validate vout
     279         [ #  # ]:           0 :     const std::string& strVout = vStrInputParts[1];
     280         [ #  # ]:           0 :     const auto vout{ToIntegral<uint32_t>(strVout)};
     281   [ #  #  #  # ]:           0 :     if (!vout || *vout > maxVout) {
     282   [ #  #  #  # ]:           0 :         throw std::runtime_error("invalid TX input vout '" + strVout + "'");
     283                 :             :     }
     284                 :             : 
     285                 :             :     // extract the optional sequence number
     286                 :           0 :     uint32_t nSequenceIn = CTxIn::SEQUENCE_FINAL;
     287   [ #  #  #  # ]:           0 :     if (vStrInputParts.size() > 2) {
     288   [ #  #  #  # ]:           0 :         nSequenceIn = TrimAndParse<uint32_t>(vStrInputParts.at(2), "invalid TX sequence id");
     289                 :             :     }
     290                 :             : 
     291                 :             :     // append to transaction input list
     292         [ #  # ]:           0 :     CTxIn txin{*txid, *vout, CScript{}, nSequenceIn};
     293         [ #  # ]:           0 :     tx.vin.push_back(txin);
     294                 :           0 : }
     295                 :             : 
     296                 :           0 : static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
     297                 :             : {
     298                 :             :     // Separate into VALUE:ADDRESS
     299         [ #  # ]:           0 :     std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
     300                 :             : 
     301   [ #  #  #  # ]:           0 :     if (vStrInputParts.size() != 2)
     302         [ #  # ]:           0 :         throw std::runtime_error("TX output missing or too many separators");
     303                 :             : 
     304                 :             :     // Extract and validate VALUE
     305         [ #  # ]:           0 :     CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
     306                 :             : 
     307                 :             :     // extract and validate ADDRESS
     308         [ #  # ]:           0 :     const std::string& strAddr = vStrInputParts[1];
     309         [ #  # ]:           0 :     CTxDestination destination = DecodeDestination(strAddr);
     310   [ #  #  #  # ]:           0 :     if (!IsValidDestination(destination)) {
     311         [ #  # ]:           0 :         throw std::runtime_error("invalid TX output address");
     312                 :             :     }
     313         [ #  # ]:           0 :     CScript scriptPubKey = GetScriptForDestination(destination);
     314                 :             : 
     315                 :             :     // construct TxOut, append to transaction output list
     316         [ #  # ]:           0 :     CTxOut txout(value, scriptPubKey);
     317         [ #  # ]:           0 :     tx.vout.push_back(txout);
     318                 :           0 : }
     319                 :             : 
     320                 :           0 : static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
     321                 :             : {
     322                 :             :     // Separate into VALUE:PUBKEY[:FLAGS]
     323         [ #  # ]:           0 :     std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
     324                 :             : 
     325   [ #  #  #  #  :           0 :     if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
                   #  # ]
     326         [ #  # ]:           0 :         throw std::runtime_error("TX output missing or too many separators");
     327                 :             : 
     328                 :             :     // Extract and validate VALUE
     329         [ #  # ]:           0 :     CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
     330                 :             : 
     331                 :             :     // Extract and validate PUBKEY
     332   [ #  #  #  # ]:           0 :     CPubKey pubkey(ParseHex(vStrInputParts[1]));
     333   [ #  #  #  # ]:           0 :     if (!pubkey.IsFullyValid())
     334         [ #  # ]:           0 :         throw std::runtime_error("invalid TX output pubkey");
     335         [ #  # ]:           0 :     CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
     336                 :             : 
     337                 :             :     // Extract and validate FLAGS
     338                 :           0 :     bool bSegWit = false;
     339                 :           0 :     bool bScriptHash = false;
     340   [ #  #  #  # ]:           0 :     if (vStrInputParts.size() == 3) {
     341         [ #  # ]:           0 :         const std::string& flags = vStrInputParts[2];
     342                 :           0 :         bSegWit = (flags.find('W') != std::string::npos);
     343                 :           0 :         bScriptHash = (flags.find('S') != std::string::npos);
     344                 :             :     }
     345                 :             : 
     346         [ #  # ]:           0 :     if (bSegWit) {
     347         [ #  # ]:           0 :         if (!pubkey.IsCompressed()) {
     348         [ #  # ]:           0 :             throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
     349                 :             :         }
     350                 :             :         // Build a P2WPKH script
     351   [ #  #  #  # ]:           0 :         scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkey));
     352                 :             :     }
     353         [ #  # ]:           0 :     if (bScriptHash) {
     354                 :             :         // Get the ID for the script, and then construct a P2SH destination for it.
     355   [ #  #  #  # ]:           0 :         scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
     356                 :             :     }
     357                 :             : 
     358                 :             :     // construct TxOut, append to transaction output list
     359         [ #  # ]:           0 :     CTxOut txout(value, scriptPubKey);
     360         [ #  # ]:           0 :     tx.vout.push_back(txout);
     361                 :           0 : }
     362                 :             : 
     363                 :           0 : static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
     364                 :             : {
     365                 :             :     // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
     366         [ #  # ]:           0 :     std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
     367                 :             : 
     368                 :             :     // Check that there are enough parameters
     369   [ #  #  #  # ]:           0 :     if (vStrInputParts.size()<3)
     370         [ #  # ]:           0 :         throw std::runtime_error("Not enough multisig parameters");
     371                 :             : 
     372                 :             :     // Extract and validate VALUE
     373         [ #  # ]:           0 :     CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
     374                 :             : 
     375                 :             :     // Extract REQUIRED
     376   [ #  #  #  # ]:           0 :     const uint32_t required{TrimAndParse<uint32_t>(vStrInputParts.at(1), "invalid multisig required number")};
     377                 :             : 
     378                 :             :     // Extract NUMKEYS
     379   [ #  #  #  # ]:           0 :     const uint32_t numkeys{TrimAndParse<uint32_t>(vStrInputParts.at(2), "invalid multisig total number")};
     380                 :             : 
     381                 :             :     // Validate there are the correct number of pubkeys
     382   [ #  #  #  # ]:           0 :     if (vStrInputParts.size() < numkeys + 3)
     383         [ #  # ]:           0 :         throw std::runtime_error("incorrect number of multisig pubkeys");
     384                 :             : 
     385   [ #  #  #  #  :           0 :     if (required < 1 || required > MAX_PUBKEYS_PER_MULTISIG || numkeys < 1 || numkeys > MAX_PUBKEYS_PER_MULTISIG || numkeys < required)
             #  #  #  # ]
     386                 :           0 :         throw std::runtime_error("multisig parameter mismatch. Required " \
     387   [ #  #  #  #  :           0 :                             + ToString(required) + " of " + ToString(numkeys) + "signatures.");
          #  #  #  #  #  
                      # ]
     388                 :             : 
     389                 :             :     // extract and validate PUBKEYs
     390                 :           0 :     std::vector<CPubKey> pubkeys;
     391         [ #  # ]:           0 :     for(int pos = 1; pos <= int(numkeys); pos++) {
     392   [ #  #  #  # ]:           0 :         CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
     393   [ #  #  #  # ]:           0 :         if (!pubkey.IsFullyValid())
     394         [ #  # ]:           0 :             throw std::runtime_error("invalid TX output pubkey");
     395         [ #  # ]:           0 :         pubkeys.push_back(pubkey);
     396                 :             :     }
     397                 :             : 
     398                 :             :     // Extract FLAGS
     399                 :           0 :     bool bSegWit = false;
     400                 :           0 :     bool bScriptHash = false;
     401   [ #  #  #  # ]:           0 :     if (vStrInputParts.size() == numkeys + 4) {
     402                 :           0 :         const std::string& flags = vStrInputParts.back();
     403                 :           0 :         bSegWit = (flags.find('W') != std::string::npos);
     404                 :           0 :         bScriptHash = (flags.find('S') != std::string::npos);
     405                 :             :     }
     406         [ #  # ]:           0 :     else if (vStrInputParts.size() > numkeys + 4) {
     407                 :             :         // Validate that there were no more parameters passed
     408         [ #  # ]:           0 :         throw std::runtime_error("Too many parameters");
     409                 :             :     }
     410                 :             : 
     411         [ #  # ]:           0 :     CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
     412                 :             : 
     413         [ #  # ]:           0 :     if (bSegWit) {
     414         [ #  # ]:           0 :         for (const CPubKey& pubkey : pubkeys) {
     415         [ #  # ]:           0 :             if (!pubkey.IsCompressed()) {
     416         [ #  # ]:           0 :                 throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
     417                 :             :             }
     418                 :             :         }
     419                 :             :         // Build a P2WSH with the multisig script
     420   [ #  #  #  # ]:           0 :         scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey));
     421                 :             :     }
     422         [ #  # ]:           0 :     if (bScriptHash) {
     423   [ #  #  #  # ]:           0 :         if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
     424                 :           0 :             throw std::runtime_error(strprintf(
     425   [ #  #  #  #  :           0 :                         "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
                   #  # ]
     426                 :             :         }
     427                 :             :         // Get the ID for the script, and then construct a P2SH destination for it.
     428   [ #  #  #  # ]:           0 :         scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
     429                 :             :     }
     430                 :             : 
     431                 :             :     // construct TxOut, append to transaction output list
     432         [ #  # ]:           0 :     CTxOut txout(value, scriptPubKey);
     433         [ #  # ]:           0 :     tx.vout.push_back(txout);
     434                 :           0 : }
     435                 :             : 
     436                 :           0 : static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
     437                 :             : {
     438                 :           0 :     CAmount value = 0;
     439                 :             : 
     440                 :             :     // separate [VALUE:]DATA in string
     441                 :           0 :     size_t pos = strInput.find(':');
     442                 :             : 
     443         [ #  # ]:           0 :     if (pos==0)
     444         [ #  # ]:           0 :         throw std::runtime_error("TX output value not specified");
     445                 :             : 
     446         [ #  # ]:           0 :     if (pos == std::string::npos) {
     447                 :             :         pos = 0;
     448                 :             :     } else {
     449                 :             :         // Extract and validate VALUE
     450         [ #  # ]:           0 :         value = ExtractAndValidateValue(strInput.substr(0, pos));
     451                 :           0 :         ++pos;
     452                 :             :     }
     453                 :             : 
     454                 :             :     // extract and validate DATA
     455                 :           0 :     const std::string strData{strInput.substr(pos, std::string::npos)};
     456                 :             : 
     457   [ #  #  #  #  :           0 :     if (!IsHex(strData))
                   #  # ]
     458         [ #  # ]:           0 :         throw std::runtime_error("invalid TX output data");
     459                 :             : 
     460   [ #  #  #  # ]:           0 :     std::vector<unsigned char> data = ParseHex(strData);
     461                 :             : 
     462   [ #  #  #  #  :           0 :     CTxOut txout(value, CScript() << OP_RETURN << data);
                   #  # ]
     463         [ #  # ]:           0 :     tx.vout.push_back(txout);
     464                 :           0 : }
     465                 :             : 
     466                 :           0 : static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
     467                 :             : {
     468         [ #  # ]:           0 :     std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
     469   [ #  #  #  #  :           0 :     if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
                   #  # ]
     470         [ #  # ]:           0 :         throw std::runtime_error("Invalid format, expected outscript=VALUE:SCRIPT[:FLAGS]");
     471                 :             :     }
     472                 :             : 
     473                 :             :     // Extract and validate VALUE
     474         [ #  # ]:           0 :     CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
     475                 :             : 
     476                 :             :     // extract and validate script
     477         [ #  # ]:           0 :     const std::string& strScript = vStrInputParts[1];
     478         [ #  # ]:           0 :     CScript scriptPubKey = ParseScript(strScript);
     479                 :             : 
     480                 :             :     // Extract FLAGS
     481                 :           0 :     bool bSegWit = false;
     482                 :           0 :     bool bScriptHash = false;
     483   [ #  #  #  # ]:           0 :     if (vStrInputParts.size() == 3) {
     484                 :           0 :         const std::string& flags = vStrInputParts.back();
     485                 :           0 :         bSegWit = (flags.find('W') != std::string::npos);
     486                 :           0 :         bScriptHash = (flags.find('S') != std::string::npos);
     487                 :             :     }
     488                 :             : 
     489   [ #  #  #  # ]:           0 :     if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
     490                 :           0 :         throw std::runtime_error(strprintf(
     491   [ #  #  #  #  :           0 :                     "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
                   #  # ]
     492                 :             :     }
     493                 :             : 
     494         [ #  # ]:           0 :     if (bSegWit) {
     495   [ #  #  #  # ]:           0 :         scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey));
     496                 :             :     }
     497         [ #  # ]:           0 :     if (bScriptHash) {
     498   [ #  #  #  # ]:           0 :         if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
     499                 :           0 :             throw std::runtime_error(strprintf(
     500   [ #  #  #  #  :           0 :                         "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
                   #  # ]
     501                 :             :         }
     502   [ #  #  #  # ]:           0 :         scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
     503                 :             :     }
     504                 :             : 
     505                 :             :     // construct TxOut, append to transaction output list
     506         [ #  # ]:           0 :     CTxOut txout(value, scriptPubKey);
     507         [ #  # ]:           0 :     tx.vout.push_back(txout);
     508                 :           0 : }
     509                 :             : 
     510                 :           0 : static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
     511                 :             : {
     512         [ #  # ]:           0 :     const auto idx{ToIntegral<uint32_t>(strInIdx)};
     513   [ #  #  #  #  :           0 :     if (!idx || idx >= tx.vin.size()) {
                   #  # ]
     514   [ #  #  #  # ]:           0 :         throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
     515                 :             :     }
     516                 :           0 :     tx.vin.erase(tx.vin.begin() + *idx);
     517                 :           0 : }
     518                 :             : 
     519                 :           0 : static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
     520                 :             : {
     521         [ #  # ]:           0 :     const auto idx{ToIntegral<uint32_t>(strOutIdx)};
     522   [ #  #  #  #  :           0 :     if (!idx || idx >= tx.vout.size()) {
                   #  # ]
     523   [ #  #  #  # ]:           0 :         throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
     524                 :             :     }
     525                 :           0 :     tx.vout.erase(tx.vout.begin() + *idx);
     526                 :           0 : }
     527                 :             : 
     528                 :             : static const unsigned int N_SIGHASH_OPTS = 7;
     529                 :             : static const struct {
     530                 :             :     const char *flagStr;
     531                 :             :     int flags;
     532                 :             : } sighashOptions[N_SIGHASH_OPTS] = {
     533                 :             :     {"DEFAULT", SIGHASH_DEFAULT},
     534                 :             :     {"ALL", SIGHASH_ALL},
     535                 :             :     {"NONE", SIGHASH_NONE},
     536                 :             :     {"SINGLE", SIGHASH_SINGLE},
     537                 :             :     {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
     538                 :             :     {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
     539                 :             :     {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
     540                 :             : };
     541                 :             : 
     542                 :           0 : static bool findSighashFlags(int& flags, const std::string& flagStr)
     543                 :             : {
     544                 :           0 :     flags = 0;
     545                 :             : 
     546         [ #  # ]:           0 :     for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
     547         [ #  # ]:           0 :         if (flagStr == sighashOptions[i].flagStr) {
     548                 :           0 :             flags = sighashOptions[i].flags;
     549                 :           0 :             return true;
     550                 :             :         }
     551                 :             :     }
     552                 :             : 
     553                 :             :     return false;
     554                 :             : }
     555                 :             : 
     556                 :           0 : static CAmount AmountFromValue(const UniValue& value)
     557                 :             : {
     558   [ #  #  #  # ]:           0 :     if (!value.isNum() && !value.isStr())
     559         [ #  # ]:           0 :         throw std::runtime_error("Amount is not a number or string");
     560                 :           0 :     int64_t amount;
     561   [ #  #  #  # ]:           0 :     if (!ParseFixedPoint(value.getValStr(), 8, &amount))
     562         [ #  # ]:           0 :         throw std::runtime_error("Invalid amount");
     563         [ #  # ]:           0 :     if (!MoneyRange(amount))
     564         [ #  # ]:           0 :         throw std::runtime_error("Amount out of range");
     565                 :           0 :     return amount;
     566                 :             : }
     567                 :             : 
     568                 :           0 : static std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
     569                 :             : {
     570         [ #  # ]:           0 :     std::string strHex;
     571         [ #  # ]:           0 :     if (v.isStr())
     572         [ #  # ]:           0 :         strHex = v.getValStr();
     573   [ #  #  #  #  :           0 :     if (!IsHex(strHex))
                   #  # ]
     574   [ #  #  #  #  :           0 :         throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
                   #  # ]
     575   [ #  #  #  # ]:           0 :     return ParseHex(strHex);
     576                 :           0 : }
     577                 :             : 
     578                 :           0 : static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
     579                 :             : {
     580                 :           0 :     int nHashType = SIGHASH_ALL;
     581                 :             : 
     582   [ #  #  #  # ]:           0 :     if (flagStr.size() > 0)
     583         [ #  # ]:           0 :         if (!findSighashFlags(nHashType, flagStr))
     584         [ #  # ]:           0 :             throw std::runtime_error("unknown sighash flag/sign option");
     585                 :             : 
     586                 :             :     // mergedTx will end up with all the signatures; it
     587                 :             :     // starts as a clone of the raw tx:
     588                 :           0 :     CMutableTransaction mergedTx{tx};
     589         [ #  # ]:           0 :     const CMutableTransaction txv{tx};
     590   [ #  #  #  # ]:           0 :     CCoinsViewCache view{&CoinsViewEmpty::Get()};
     591                 :             : 
     592   [ #  #  #  # ]:           0 :     if (!registers.contains("privatekeys"))
     593         [ #  # ]:           0 :         throw std::runtime_error("privatekeys register variable must be set.");
     594                 :           0 :     FillableSigningProvider tempKeystore;
     595   [ #  #  #  #  :           0 :     UniValue keysObj = registers["privatekeys"];
                   #  # ]
     596                 :             : 
     597   [ #  #  #  # ]:           0 :     for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
     598   [ #  #  #  # ]:           0 :         if (!keysObj[kidx].isStr())
     599         [ #  # ]:           0 :             throw std::runtime_error("privatekey not a std::string");
     600   [ #  #  #  #  :           0 :         CKey key = DecodeSecret(keysObj[kidx].getValStr());
                   #  # ]
     601         [ #  # ]:           0 :         if (!key.IsValid()) {
     602         [ #  # ]:           0 :             throw std::runtime_error("privatekey not valid");
     603                 :             :         }
     604         [ #  # ]:           0 :         tempKeystore.AddKey(key);
     605                 :           0 :     }
     606                 :             : 
     607                 :             :     // Add previous txouts given in the RPC call:
     608   [ #  #  #  # ]:           0 :     if (!registers.contains("prevtxs"))
     609         [ #  # ]:           0 :         throw std::runtime_error("prevtxs register variable must be set.");
     610   [ #  #  #  #  :           0 :     UniValue prevtxsObj = registers["prevtxs"];
                   #  # ]
     611                 :           0 :     {
     612   [ #  #  #  # ]:           0 :         for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
     613         [ #  # ]:           0 :             const UniValue& prevOut = prevtxsObj[previdx];
     614         [ #  # ]:           0 :             if (!prevOut.isObject())
     615         [ #  # ]:           0 :                 throw std::runtime_error("expected prevtxs internal object");
     616                 :             : 
     617                 :           0 :             std::map<std::string, UniValue::VType> types = {
     618         [ #  # ]:           0 :                 {"txid", UniValue::VSTR},
     619                 :           0 :                 {"vout", UniValue::VNUM},
     620                 :           0 :                 {"scriptPubKey", UniValue::VSTR},
     621   [ #  #  #  # ]:           0 :             };
     622   [ #  #  #  # ]:           0 :             if (!prevOut.checkObject(types))
     623         [ #  # ]:           0 :                 throw std::runtime_error("prevtxs internal object typecheck fail");
     624                 :             : 
     625   [ #  #  #  #  :           0 :             auto txid{Txid::FromHex(prevOut["txid"].get_str())};
          #  #  #  #  #  
                      # ]
     626         [ #  # ]:           0 :             if (!txid) {
     627   [ #  #  #  #  :           0 :                 throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')");
          #  #  #  #  #  
                      # ]
     628                 :             :             }
     629                 :             : 
     630   [ #  #  #  #  :           0 :             const int nOut = prevOut["vout"].getInt<int>();
                   #  # ]
     631         [ #  # ]:           0 :             if (nOut < 0)
     632         [ #  # ]:           0 :                 throw std::runtime_error("vout cannot be negative");
     633                 :             : 
     634         [ #  # ]:           0 :             COutPoint out(*txid, nOut);
     635   [ #  #  #  #  :           0 :             std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
             #  #  #  # ]
     636                 :           0 :             CScript scriptPubKey(pkData.begin(), pkData.end());
     637                 :             : 
     638                 :           0 :             {
     639         [ #  # ]:           0 :                 const Coin& coin = view.AccessCoin(out);
     640   [ #  #  #  # ]:           0 :                 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
     641         [ #  # ]:           0 :                     std::string err("Previous output scriptPubKey mismatch:\n");
     642   [ #  #  #  # ]:           0 :                     err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
     643   [ #  #  #  # ]:           0 :                         ScriptToAsmStr(scriptPubKey);
     644         [ #  # ]:           0 :                     throw std::runtime_error(err);
     645                 :           0 :                 }
     646                 :           0 :                 Coin newcoin;
     647                 :           0 :                 newcoin.out.scriptPubKey = scriptPubKey;
     648                 :           0 :                 newcoin.out.nValue = MAX_MONEY;
     649   [ #  #  #  # ]:           0 :                 if (prevOut.exists("amount")) {
     650   [ #  #  #  #  :           0 :                     newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
                   #  # ]
     651                 :             :                 }
     652                 :           0 :                 newcoin.nHeight = 1;
     653         [ #  # ]:           0 :                 view.AddCoin(out, std::move(newcoin), true);
     654                 :           0 :             }
     655                 :             : 
     656                 :             :             // if redeemScript given and private keys given,
     657                 :             :             // add redeemScript to the tempKeystore so it can be signed:
     658   [ #  #  #  #  :           0 :             if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
          #  #  #  #  #  
                #  #  # ]
     659   [ #  #  #  #  :           0 :                 prevOut.exists("redeemScript")) {
                   #  # ]
     660   [ #  #  #  #  :           0 :                 UniValue v = prevOut["redeemScript"];
                   #  # ]
     661   [ #  #  #  # ]:           0 :                 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
     662                 :           0 :                 CScript redeemScript(rsData.begin(), rsData.end());
     663   [ #  #  #  # ]:           0 :                 if (!tempKeystore.AddCScript(redeemScript)) {
     664   [ #  #  #  #  :           0 :                     throw std::runtime_error(strprintf("Error adding redeemscript=%s", HexStr(redeemScript)));
             #  #  #  # ]
     665                 :             :                 }
     666                 :           0 :             }
     667                 :           0 :         }
     668                 :             :     }
     669                 :             : 
     670                 :           0 :     const FillableSigningProvider& keystore = tempKeystore;
     671                 :             : 
     672                 :           0 :     bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
     673                 :             : 
     674                 :             :     // Sign what we can:
     675   [ #  #  #  # ]:           0 :     for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
     676         [ #  # ]:           0 :         CTxIn& txin = mergedTx.vin[i];
     677         [ #  # ]:           0 :         const Coin& coin = view.AccessCoin(txin.prevout);
     678         [ #  # ]:           0 :         if (coin.IsSpent()) {
     679                 :           0 :             continue;
     680                 :             :         }
     681                 :           0 :         const CScript& prevPubKey = coin.out.scriptPubKey;
     682                 :           0 :         const CAmount& amount = coin.out.nValue;
     683                 :             : 
     684         [ #  # ]:           0 :         SignatureData sigdata = DataFromTransaction(mergedTx, i, coin.out);
     685                 :             :         // Only sign SIGHASH_SINGLE if there's a corresponding output:
     686   [ #  #  #  #  :           0 :         if (!fHashSingle || (i < mergedTx.vout.size()))
                   #  # ]
     687   [ #  #  #  # ]:           0 :             ProduceSignature(keystore, MutableTransactionSignatureCreator(mergedTx, i, amount, {.sighash_type = nHashType}), prevPubKey, sigdata);
     688                 :             : 
     689   [ #  #  #  # ]:           0 :         if (amount == MAX_MONEY && !sigdata.scriptWitness.IsNull()) {
     690   [ #  #  #  #  :           0 :             throw std::runtime_error(strprintf("Missing amount for CTxOut with scriptPubKey=%s", HexStr(prevPubKey)));
             #  #  #  # ]
     691                 :             :         }
     692                 :             : 
     693         [ #  # ]:           0 :         UpdateInput(txin, sigdata);
     694                 :           0 :     }
     695                 :             : 
     696         [ #  # ]:           0 :     tx = mergedTx;
     697   [ #  #  #  #  :           0 : }
             #  #  #  # ]
     698                 :             : 
     699                 :           0 : static void MutateTx(CMutableTransaction& tx, const std::string& command,
     700                 :             :                      const std::string& commandVal)
     701                 :             : {
     702                 :           0 :     std::unique_ptr<ECC_Context> ecc;
     703                 :             : 
     704         [ #  # ]:           0 :     if (command == "nversion")
     705         [ #  # ]:           0 :         MutateTxVersion(tx, commandVal);
     706         [ #  # ]:           0 :     else if (command == "locktime")
     707         [ #  # ]:           0 :         MutateTxLocktime(tx, commandVal);
     708         [ #  # ]:           0 :     else if (command == "replaceable") {
     709         [ #  # ]:           0 :         MutateTxRBFOptIn(tx, commandVal);
     710                 :             :     }
     711                 :             : 
     712         [ #  # ]:           0 :     else if (command == "delin")
     713         [ #  # ]:           0 :         MutateTxDelInput(tx, commandVal);
     714         [ #  # ]:           0 :     else if (command == "in")
     715         [ #  # ]:           0 :         MutateTxAddInput(tx, commandVal);
     716                 :             : 
     717         [ #  # ]:           0 :     else if (command == "delout")
     718         [ #  # ]:           0 :         MutateTxDelOutput(tx, commandVal);
     719         [ #  # ]:           0 :     else if (command == "outaddr")
     720         [ #  # ]:           0 :         MutateTxAddOutAddr(tx, commandVal);
     721         [ #  # ]:           0 :     else if (command == "outpubkey") {
     722   [ #  #  #  #  :           0 :         ecc.reset(new ECC_Context());
                   #  # ]
     723         [ #  # ]:           0 :         MutateTxAddOutPubKey(tx, commandVal);
     724         [ #  # ]:           0 :     } else if (command == "outmultisig") {
     725   [ #  #  #  #  :           0 :         ecc.reset(new ECC_Context());
                   #  # ]
     726         [ #  # ]:           0 :         MutateTxAddOutMultiSig(tx, commandVal);
     727         [ #  # ]:           0 :     } else if (command == "outscript")
     728         [ #  # ]:           0 :         MutateTxAddOutScript(tx, commandVal);
     729         [ #  # ]:           0 :     else if (command == "outdata")
     730         [ #  # ]:           0 :         MutateTxAddOutData(tx, commandVal);
     731                 :             : 
     732         [ #  # ]:           0 :     else if (command == "sign") {
     733   [ #  #  #  #  :           0 :         ecc.reset(new ECC_Context());
                   #  # ]
     734         [ #  # ]:           0 :         MutateTxSign(tx, commandVal);
     735                 :             :     }
     736                 :             : 
     737         [ #  # ]:           0 :     else if (command == "load")
     738         [ #  # ]:           0 :         RegisterLoad(commandVal);
     739                 :             : 
     740         [ #  # ]:           0 :     else if (command == "set")
     741         [ #  # ]:           0 :         RegisterSet(commandVal);
     742                 :             : 
     743                 :             :     else
     744         [ #  # ]:           0 :         throw std::runtime_error("unknown command");
     745                 :           0 : }
     746                 :             : 
     747                 :           0 : static void OutputTxJSON(const CTransaction& tx)
     748                 :             : {
     749                 :           0 :     UniValue entry(UniValue::VOBJ);
     750         [ #  # ]:           0 :     TxToUniv(tx, /*block_hash=*/uint256(), entry);
     751                 :             : 
     752         [ #  # ]:           0 :     std::string jsonOutput = entry.write(4);
     753         [ #  # ]:           0 :     tfm::format(std::cout, "%s\n", jsonOutput);
     754                 :           0 : }
     755                 :             : 
     756                 :           0 : static void OutputTxHash(const CTransaction& tx)
     757                 :             : {
     758                 :           0 :     std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
     759                 :             : 
     760         [ #  # ]:           0 :     tfm::format(std::cout, "%s\n", strHexHash);
     761                 :           0 : }
     762                 :             : 
     763                 :           0 : static void OutputTxHex(const CTransaction& tx)
     764                 :             : {
     765                 :           0 :     std::string strHex = EncodeHexTx(tx);
     766                 :             : 
     767         [ #  # ]:           0 :     tfm::format(std::cout, "%s\n", strHex);
     768                 :           0 : }
     769                 :             : 
     770                 :           0 : static void OutputTx(const CTransaction& tx)
     771                 :             : {
     772   [ #  #  #  # ]:           0 :     if (gArgs.GetBoolArg("-json", false))
     773                 :           0 :         OutputTxJSON(tx);
     774   [ #  #  #  # ]:           0 :     else if (gArgs.GetBoolArg("-txid", false))
     775                 :           0 :         OutputTxHash(tx);
     776                 :             :     else
     777                 :           0 :         OutputTxHex(tx);
     778                 :           0 : }
     779                 :             : 
     780                 :           0 : static std::string readStdin()
     781                 :             : {
     782                 :           0 :     char buf[4096];
     783                 :           0 :     std::string ret;
     784                 :             : 
     785         [ #  # ]:           0 :     while (!feof(stdin)) {
     786         [ #  # ]:           0 :         size_t bread = fread(buf, 1, sizeof(buf), stdin);
     787         [ #  # ]:           0 :         ret.append(buf, bread);
     788         [ #  # ]:           0 :         if (bread < sizeof(buf))
     789                 :             :             break;
     790                 :             :     }
     791                 :             : 
     792         [ #  # ]:           0 :     if (ferror(stdin))
     793         [ #  # ]:           0 :         throw std::runtime_error("error reading stdin");
     794                 :             : 
     795   [ #  #  #  # ]:           0 :     return TrimString(ret);
     796                 :           0 : }
     797                 :             : 
     798                 :           0 : static int CommandLineRawTx(int argc, char* argv[])
     799                 :             : {
     800                 :           0 :     std::string strPrint;
     801                 :           0 :     int nRet = 0;
     802                 :           0 :     try {
     803                 :             :         // Skip switches; Permit common stdin convention "-"
     804   [ #  #  #  # ]:           0 :         while (argc > 1 && IsSwitchChar(argv[1][0]) &&
     805         [ #  # ]:           0 :                (argv[1][1] != 0)) {
     806                 :           0 :             argc--;
     807                 :           0 :             argv++;
     808                 :             :         }
     809                 :             : 
     810         [ #  # ]:           0 :         CMutableTransaction tx;
     811                 :           0 :         int startArg;
     812                 :             : 
     813         [ #  # ]:           0 :         if (!fCreateBlank) {
     814                 :             :             // require at least one param
     815         [ #  # ]:           0 :             if (argc < 2)
     816         [ #  # ]:           0 :                 throw std::runtime_error("too few parameters");
     817                 :             : 
     818                 :             :             // param: hex-encoded bitcoin transaction
     819         [ #  # ]:           0 :             std::string strHexTx(argv[1]);
     820         [ #  # ]:           0 :             if (strHexTx == "-")                 // "-" implies standard input
     821         [ #  # ]:           0 :                 strHexTx = readStdin();
     822                 :             : 
     823   [ #  #  #  # ]:           0 :             if (!DecodeHexTx(tx, strHexTx, true))
     824         [ #  # ]:           0 :                 throw std::runtime_error("invalid transaction encoding");
     825                 :             : 
     826                 :           0 :             startArg = 2;
     827                 :           0 :         } else
     828                 :             :             startArg = 1;
     829                 :             : 
     830         [ #  # ]:           0 :         for (int i = startArg; i < argc; i++) {
     831         [ #  # ]:           0 :             std::string arg = argv[i];
     832         [ #  # ]:           0 :             std::string key, value;
     833                 :           0 :             size_t eqpos = arg.find('=');
     834         [ #  # ]:           0 :             if (eqpos == std::string::npos)
     835         [ #  # ]:           0 :                 key = arg;
     836                 :             :             else {
     837         [ #  # ]:           0 :                 key = arg.substr(0, eqpos);
     838         [ #  # ]:           0 :                 value = arg.substr(eqpos + 1);
     839                 :             :             }
     840                 :             : 
     841         [ #  # ]:           0 :             MutateTx(tx, key, value);
     842                 :           0 :         }
     843                 :             : 
     844   [ #  #  #  # ]:           0 :         OutputTx(CTransaction(tx));
     845                 :           0 :     }
     846         [ -  - ]:           0 :     catch (const std::exception& e) {
     847         [ -  - ]:           0 :         strPrint = std::string("error: ") + e.what();
     848                 :           0 :         nRet = EXIT_FAILURE;
     849                 :           0 :     }
     850                 :           0 :     catch (...) {
     851         [ -  - ]:           0 :         PrintExceptionContinue(nullptr, "CommandLineRawTx()");
     852                 :           0 :         throw;
     853                 :           0 :     }
     854                 :             : 
     855         [ #  # ]:           0 :     if (strPrint != "") {
     856   [ #  #  #  # ]:           0 :         tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
     857                 :             :     }
     858                 :           0 :     return nRet;
     859                 :           0 : }
     860                 :             : 
     861                 :           0 : MAIN_FUNCTION
     862                 :             : {
     863                 :           0 :     SetupEnvironment();
     864                 :           0 :     SHA256AutoDetect();
     865                 :             : 
     866                 :           0 :     try {
     867         [ #  # ]:           0 :         int ret = AppInitRawTx(argc, argv);
     868         [ #  # ]:           0 :         if (ret != CONTINUE_EXECUTION)
     869                 :             :             return ret;
     870                 :             :     }
     871         [ -  - ]:           0 :     catch (const std::exception& e) {
     872         [ -  - ]:           0 :         PrintExceptionContinue(&e, "AppInitRawTx()");
     873                 :           0 :         return EXIT_FAILURE;
     874                 :           0 :     } catch (...) {
     875         [ -  - ]:           0 :         PrintExceptionContinue(nullptr, "AppInitRawTx()");
     876                 :           0 :         return EXIT_FAILURE;
     877                 :           0 :     }
     878                 :             : 
     879                 :           0 :     int ret = EXIT_FAILURE;
     880                 :           0 :     try {
     881         [ #  # ]:           0 :         ret = CommandLineRawTx(argc, argv);
     882                 :             :     }
     883         [ -  - ]:           0 :     catch (const std::exception& e) {
     884         [ -  - ]:           0 :         PrintExceptionContinue(&e, "CommandLineRawTx()");
     885                 :           0 :     } catch (...) {
     886         [ -  - ]:           0 :         PrintExceptionContinue(nullptr, "CommandLineRawTx()");
     887                 :           0 :     }
     888                 :             :     return ret;
     889                 :             : }
        

Generated by: LCOV version 2.0-1