LCOV - code coverage report
Current view: top level - src - bitcoin-tx.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 77.9 % 521 406
Test Date: 2024-08-28 04:44:32 Functions: 93.3 % 30 28
Branches: 47.4 % 960 455

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

Generated by: LCOV version 2.0-1