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

Generated by: LCOV version 2.0-1