LCOV - code coverage report
Current view: top level - src - bitcoin-tx.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 77.8 % 518 403
Test Date: 2025-06-01 05:54:06 Functions: 93.3 % 30 28
Branches: 47.3 % 940 445

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

Generated by: LCOV version 2.0-1