Document assumptions that are being made to avoid NULL pointer dereferences
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blobcff90d13affc0d247742fe3111b60884388ce856
1 // Copyright (c) 2009-2016 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.
5 #if defined(HAVE_CONFIG_H)
6 #include "config/bitcoin-config.h"
7 #endif
9 #include "base58.h"
10 #include "clientversion.h"
11 #include "coins.h"
12 #include "consensus/consensus.h"
13 #include "core_io.h"
14 #include "keystore.h"
15 #include "policy/policy.h"
16 #include "policy/rbf.h"
17 #include "primitives/transaction.h"
18 #include "script/script.h"
19 #include "script/sign.h"
20 #include <univalue.h>
21 #include "util.h"
22 #include "utilmoneystr.h"
23 #include "utilstrencodings.h"
25 #include <stdio.h>
27 #include <boost/algorithm/string.hpp>
29 static bool fCreateBlank;
30 static std::map<std::string,UniValue> registers;
31 static const int CONTINUE_EXECUTION=-1;
34 // This function returns either one of EXIT_ codes when it's expected to stop the process or
35 // CONTINUE_EXECUTION when it's expected to continue further.
37 static int AppInitRawTx(int argc, char* argv[])
40 // Parameters
42 gArgs.ParseParameters(argc, argv);
44 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
45 try {
46 SelectParams(ChainNameFromCommandLine());
47 } catch (const std::exception& e) {
48 fprintf(stderr, "Error: %s\n", e.what());
49 return EXIT_FAILURE;
52 fCreateBlank = gArgs.GetBoolArg("-create", false);
54 if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help"))
56 // First part of help message is specific to this utility
57 std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
58 _("Usage:") + "\n" +
59 " bitcoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded bitcoin transaction") + "\n" +
60 " bitcoin-tx [options] -create [commands] " + _("Create hex-encoded bitcoin transaction") + "\n" +
61 "\n";
63 fprintf(stdout, "%s", strUsage.c_str());
65 strUsage = HelpMessageGroup(_("Options:"));
66 strUsage += HelpMessageOpt("-?", _("This help message"));
67 strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
68 strUsage += HelpMessageOpt("-json", _("Select JSON output"));
69 strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
70 AppendParamsHelpMessages(strUsage);
72 fprintf(stdout, "%s", strUsage.c_str());
74 strUsage = HelpMessageGroup(_("Commands:"));
75 strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
76 strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
77 strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
78 strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
79 strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
80 strUsage += HelpMessageOpt("replaceable(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)"));
81 strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
82 strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
83 _("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
84 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
85 strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
86 strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
87 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
88 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
89 strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
90 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
91 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
92 strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
93 _("This command requires JSON registers:") +
94 _("prevtxs=JSON object") + ", " +
95 _("privatekeys=JSON object") + ". " +
96 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
97 fprintf(stdout, "%s", strUsage.c_str());
99 strUsage = HelpMessageGroup(_("Register Commands:"));
100 strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
101 strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
102 fprintf(stdout, "%s", strUsage.c_str());
104 if (argc < 2) {
105 fprintf(stderr, "Error: too few parameters\n");
106 return EXIT_FAILURE;
108 return EXIT_SUCCESS;
110 return CONTINUE_EXECUTION;
113 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
115 UniValue val;
116 if (!val.read(rawJson)) {
117 std::string strErr = "Cannot parse JSON for key " + key;
118 throw std::runtime_error(strErr);
121 registers[key] = val;
124 static void RegisterSet(const std::string& strInput)
126 // separate NAME:VALUE in string
127 size_t pos = strInput.find(':');
128 if ((pos == std::string::npos) ||
129 (pos == 0) ||
130 (pos == (strInput.size() - 1)))
131 throw std::runtime_error("Register input requires NAME:VALUE");
133 std::string key = strInput.substr(0, pos);
134 std::string valStr = strInput.substr(pos + 1, std::string::npos);
136 RegisterSetJson(key, valStr);
139 static void RegisterLoad(const std::string& strInput)
141 // separate NAME:FILENAME in string
142 size_t pos = strInput.find(':');
143 if ((pos == std::string::npos) ||
144 (pos == 0) ||
145 (pos == (strInput.size() - 1)))
146 throw std::runtime_error("Register load requires NAME:FILENAME");
148 std::string key = strInput.substr(0, pos);
149 std::string filename = strInput.substr(pos + 1, std::string::npos);
151 FILE *f = fopen(filename.c_str(), "r");
152 if (!f) {
153 std::string strErr = "Cannot open file " + filename;
154 throw std::runtime_error(strErr);
157 // load file chunks into one big buffer
158 std::string valStr;
159 while ((!feof(f)) && (!ferror(f))) {
160 char buf[4096];
161 int bread = fread(buf, 1, sizeof(buf), f);
162 if (bread <= 0)
163 break;
165 valStr.insert(valStr.size(), buf, bread);
168 int error = ferror(f);
169 fclose(f);
171 if (error) {
172 std::string strErr = "Error reading file " + filename;
173 throw std::runtime_error(strErr);
176 // evaluate as JSON buffer register
177 RegisterSetJson(key, valStr);
180 static CAmount ExtractAndValidateValue(const std::string& strValue)
182 CAmount value;
183 if (!ParseMoney(strValue, value))
184 throw std::runtime_error("invalid TX output value");
185 return value;
188 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
190 int64_t newVersion = atoi64(cmdVal);
191 if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
192 throw std::runtime_error("Invalid TX version requested");
194 tx.nVersion = (int) newVersion;
197 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
199 int64_t newLocktime = atoi64(cmdVal);
200 if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
201 throw std::runtime_error("Invalid TX locktime requested");
203 tx.nLockTime = (unsigned int) newLocktime;
206 static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
208 // parse requested index
209 int inIdx = atoi(strInIdx);
210 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
211 throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
214 // set the nSequence to MAX_INT - 2 (= RBF opt in flag)
215 int cnt = 0;
216 for (CTxIn& txin : tx.vin) {
217 if (strInIdx == "" || cnt == inIdx) {
218 if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
219 txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
222 ++cnt;
226 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
228 std::vector<std::string> vStrInputParts;
229 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
231 // separate TXID:VOUT in string
232 if (vStrInputParts.size()<2)
233 throw std::runtime_error("TX input missing separator");
235 // extract and validate TXID
236 std::string strTxid = vStrInputParts[0];
237 if ((strTxid.size() != 64) || !IsHex(strTxid))
238 throw std::runtime_error("invalid TX input txid");
239 uint256 txid(uint256S(strTxid));
241 static const unsigned int minTxOutSz = 9;
242 static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz);
244 // extract and validate vout
245 std::string strVout = vStrInputParts[1];
246 int vout = atoi(strVout);
247 if ((vout < 0) || (vout > (int)maxVout))
248 throw std::runtime_error("invalid TX input vout");
250 // extract the optional sequence number
251 uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
252 if (vStrInputParts.size() > 2)
253 nSequenceIn = std::stoul(vStrInputParts[2]);
255 // append to transaction input list
256 CTxIn txin(txid, vout, CScript(), nSequenceIn);
257 tx.vin.push_back(txin);
260 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
262 // Separate into VALUE:ADDRESS
263 std::vector<std::string> vStrInputParts;
264 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
266 if (vStrInputParts.size() != 2)
267 throw std::runtime_error("TX output missing or too many separators");
269 // Extract and validate VALUE
270 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
272 // extract and validate ADDRESS
273 std::string strAddr = vStrInputParts[1];
274 CBitcoinAddress addr(strAddr);
275 if (!addr.IsValid())
276 throw std::runtime_error("invalid TX output address");
277 // build standard output script via GetScriptForDestination()
278 CScript scriptPubKey = GetScriptForDestination(addr.Get());
280 // construct TxOut, append to transaction output list
281 CTxOut txout(value, scriptPubKey);
282 tx.vout.push_back(txout);
285 static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
287 // Separate into VALUE:PUBKEY[:FLAGS]
288 std::vector<std::string> vStrInputParts;
289 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
291 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
292 throw std::runtime_error("TX output missing or too many separators");
294 // Extract and validate VALUE
295 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
297 // Extract and validate PUBKEY
298 CPubKey pubkey(ParseHex(vStrInputParts[1]));
299 if (!pubkey.IsFullyValid())
300 throw std::runtime_error("invalid TX output pubkey");
301 CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
303 // Extract and validate FLAGS
304 bool bSegWit = false;
305 bool bScriptHash = false;
306 if (vStrInputParts.size() == 3) {
307 std::string flags = vStrInputParts[2];
308 bSegWit = (flags.find("W") != std::string::npos);
309 bScriptHash = (flags.find("S") != std::string::npos);
312 if (bSegWit) {
313 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
314 scriptPubKey = GetScriptForWitness(scriptPubKey);
316 if (bScriptHash) {
317 // Get the address for the redeem script, then call
318 // GetScriptForDestination() to construct a P2SH scriptPubKey.
319 CBitcoinAddress redeemScriptAddr(scriptPubKey);
320 scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get());
323 // construct TxOut, append to transaction output list
324 CTxOut txout(value, scriptPubKey);
325 tx.vout.push_back(txout);
328 static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
330 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
331 std::vector<std::string> vStrInputParts;
332 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
334 // Check that there are enough parameters
335 if (vStrInputParts.size()<3)
336 throw std::runtime_error("Not enough multisig parameters");
338 // Extract and validate VALUE
339 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
341 // Extract REQUIRED
342 uint32_t required = stoul(vStrInputParts[1]);
344 // Extract NUMKEYS
345 uint32_t numkeys = stoul(vStrInputParts[2]);
347 // Validate there are the correct number of pubkeys
348 if (vStrInputParts.size() < numkeys + 3)
349 throw std::runtime_error("incorrect number of multisig pubkeys");
351 if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
352 throw std::runtime_error("multisig parameter mismatch. Required " \
353 + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
355 // extract and validate PUBKEYs
356 std::vector<CPubKey> pubkeys;
357 for(int pos = 1; pos <= int(numkeys); pos++) {
358 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
359 if (!pubkey.IsFullyValid())
360 throw std::runtime_error("invalid TX output pubkey");
361 pubkeys.push_back(pubkey);
364 // Extract FLAGS
365 bool bSegWit = false;
366 bool bScriptHash = false;
367 if (vStrInputParts.size() == numkeys + 4) {
368 std::string flags = vStrInputParts.back();
369 bSegWit = (flags.find("W") != std::string::npos);
370 bScriptHash = (flags.find("S") != std::string::npos);
372 else if (vStrInputParts.size() > numkeys + 4) {
373 // Validate that there were no more parameters passed
374 throw std::runtime_error("Too many parameters");
377 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
379 if (bSegWit) {
380 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
381 scriptPubKey = GetScriptForWitness(scriptPubKey);
383 if (bScriptHash) {
384 // Get the address for the redeem script, then call
385 // GetScriptForDestination() to construct a P2SH scriptPubKey.
386 CBitcoinAddress addr(scriptPubKey);
387 scriptPubKey = GetScriptForDestination(addr.Get());
390 // construct TxOut, append to transaction output list
391 CTxOut txout(value, scriptPubKey);
392 tx.vout.push_back(txout);
395 static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
397 CAmount value = 0;
399 // separate [VALUE:]DATA in string
400 size_t pos = strInput.find(':');
402 if (pos==0)
403 throw std::runtime_error("TX output value not specified");
405 if (pos != std::string::npos) {
406 // Extract and validate VALUE
407 value = ExtractAndValidateValue(strInput.substr(0, pos));
410 // extract and validate DATA
411 std::string strData = strInput.substr(pos + 1, std::string::npos);
413 if (!IsHex(strData))
414 throw std::runtime_error("invalid TX output data");
416 std::vector<unsigned char> data = ParseHex(strData);
418 CTxOut txout(value, CScript() << OP_RETURN << data);
419 tx.vout.push_back(txout);
422 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
424 // separate VALUE:SCRIPT[:FLAGS]
425 std::vector<std::string> vStrInputParts;
426 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
427 if (vStrInputParts.size() < 2)
428 throw std::runtime_error("TX output missing separator");
430 // Extract and validate VALUE
431 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
433 // extract and validate script
434 std::string strScript = vStrInputParts[1];
435 CScript scriptPubKey = ParseScript(strScript);
437 // Extract FLAGS
438 bool bSegWit = false;
439 bool bScriptHash = false;
440 if (vStrInputParts.size() == 3) {
441 std::string flags = vStrInputParts.back();
442 bSegWit = (flags.find("W") != std::string::npos);
443 bScriptHash = (flags.find("S") != std::string::npos);
446 if (bSegWit) {
447 scriptPubKey = GetScriptForWitness(scriptPubKey);
449 if (bScriptHash) {
450 CBitcoinAddress addr(scriptPubKey);
451 scriptPubKey = GetScriptForDestination(addr.Get());
454 // construct TxOut, append to transaction output list
455 CTxOut txout(value, scriptPubKey);
456 tx.vout.push_back(txout);
459 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
461 // parse requested deletion index
462 int inIdx = atoi(strInIdx);
463 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
464 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
465 throw std::runtime_error(strErr.c_str());
468 // delete input from transaction
469 tx.vin.erase(tx.vin.begin() + inIdx);
472 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
474 // parse requested deletion index
475 int outIdx = atoi(strOutIdx);
476 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
477 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
478 throw std::runtime_error(strErr.c_str());
481 // delete output from transaction
482 tx.vout.erase(tx.vout.begin() + outIdx);
485 static const unsigned int N_SIGHASH_OPTS = 6;
486 static const struct {
487 const char *flagStr;
488 int flags;
489 } sighashOptions[N_SIGHASH_OPTS] = {
490 {"ALL", SIGHASH_ALL},
491 {"NONE", SIGHASH_NONE},
492 {"SINGLE", SIGHASH_SINGLE},
493 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
494 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
495 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
498 static bool findSighashFlags(int& flags, const std::string& flagStr)
500 flags = 0;
502 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
503 if (flagStr == sighashOptions[i].flagStr) {
504 flags = sighashOptions[i].flags;
505 return true;
509 return false;
512 static CAmount AmountFromValue(const UniValue& value)
514 if (!value.isNum() && !value.isStr())
515 throw std::runtime_error("Amount is not a number or string");
516 CAmount amount;
517 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
518 throw std::runtime_error("Invalid amount");
519 if (!MoneyRange(amount))
520 throw std::runtime_error("Amount out of range");
521 return amount;
524 static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
526 int nHashType = SIGHASH_ALL;
528 if (flagStr.size() > 0)
529 if (!findSighashFlags(nHashType, flagStr))
530 throw std::runtime_error("unknown sighash flag/sign option");
532 std::vector<CTransaction> txVariants;
533 txVariants.push_back(tx);
535 // mergedTx will end up with all the signatures; it
536 // starts as a clone of the raw tx:
537 CMutableTransaction mergedTx(txVariants[0]);
538 bool fComplete = true;
539 CCoinsView viewDummy;
540 CCoinsViewCache view(&viewDummy);
542 if (!registers.count("privatekeys"))
543 throw std::runtime_error("privatekeys register variable must be set.");
544 CBasicKeyStore tempKeystore;
545 UniValue keysObj = registers["privatekeys"];
547 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
548 if (!keysObj[kidx].isStr())
549 throw std::runtime_error("privatekey not a std::string");
550 CBitcoinSecret vchSecret;
551 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
552 if (!fGood)
553 throw std::runtime_error("privatekey not valid");
555 CKey key = vchSecret.GetKey();
556 tempKeystore.AddKey(key);
559 // Add previous txouts given in the RPC call:
560 if (!registers.count("prevtxs"))
561 throw std::runtime_error("prevtxs register variable must be set.");
562 UniValue prevtxsObj = registers["prevtxs"];
564 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
565 UniValue prevOut = prevtxsObj[previdx];
566 if (!prevOut.isObject())
567 throw std::runtime_error("expected prevtxs internal object");
569 std::map<std::string, UniValue::VType> types = {
570 {"txid", UniValue::VSTR},
571 {"vout", UniValue::VNUM},
572 {"scriptPubKey", UniValue::VSTR},
574 if (!prevOut.checkObject(types))
575 throw std::runtime_error("prevtxs internal object typecheck fail");
577 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
579 int nOut = atoi(prevOut["vout"].getValStr());
580 if (nOut < 0)
581 throw std::runtime_error("vout must be positive");
583 COutPoint out(txid, nOut);
584 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
585 CScript scriptPubKey(pkData.begin(), pkData.end());
588 const Coin& coin = view.AccessCoin(out);
589 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
590 std::string err("Previous output scriptPubKey mismatch:\n");
591 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
592 ScriptToAsmStr(scriptPubKey);
593 throw std::runtime_error(err);
595 Coin newcoin;
596 newcoin.out.scriptPubKey = scriptPubKey;
597 newcoin.out.nValue = 0;
598 if (prevOut.exists("amount")) {
599 newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
601 newcoin.nHeight = 1;
602 view.AddCoin(out, std::move(newcoin), true);
605 // if redeemScript given and private keys given,
606 // add redeemScript to the tempKeystore so it can be signed:
607 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
608 prevOut.exists("redeemScript")) {
609 UniValue v = prevOut["redeemScript"];
610 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
611 CScript redeemScript(rsData.begin(), rsData.end());
612 tempKeystore.AddCScript(redeemScript);
617 const CKeyStore& keystore = tempKeystore;
619 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
621 // Sign what we can:
622 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
623 CTxIn& txin = mergedTx.vin[i];
624 const Coin& coin = view.AccessCoin(txin.prevout);
625 if (coin.IsSpent()) {
626 fComplete = false;
627 continue;
629 const CScript& prevPubKey = coin.out.scriptPubKey;
630 const CAmount& amount = coin.out.nValue;
632 SignatureData sigdata;
633 // Only sign SIGHASH_SINGLE if there's a corresponding output:
634 if (!fHashSingle || (i < mergedTx.vout.size()))
635 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
637 // ... and merge in other signatures:
638 for (const CTransaction& txv : txVariants)
639 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
640 UpdateTransaction(mergedTx, i, sigdata);
642 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
643 fComplete = false;
646 if (fComplete) {
647 // do nothing... for now
648 // perhaps store this for later optional JSON output
651 tx = mergedTx;
654 class Secp256k1Init
656 ECCVerifyHandle globalVerifyHandle;
658 public:
659 Secp256k1Init() {
660 ECC_Start();
662 ~Secp256k1Init() {
663 ECC_Stop();
667 static void MutateTx(CMutableTransaction& tx, const std::string& command,
668 const std::string& commandVal)
670 std::unique_ptr<Secp256k1Init> ecc;
672 if (command == "nversion")
673 MutateTxVersion(tx, commandVal);
674 else if (command == "locktime")
675 MutateTxLocktime(tx, commandVal);
676 else if (command == "replaceable") {
677 MutateTxRBFOptIn(tx, commandVal);
680 else if (command == "delin")
681 MutateTxDelInput(tx, commandVal);
682 else if (command == "in")
683 MutateTxAddInput(tx, commandVal);
685 else if (command == "delout")
686 MutateTxDelOutput(tx, commandVal);
687 else if (command == "outaddr")
688 MutateTxAddOutAddr(tx, commandVal);
689 else if (command == "outpubkey") {
690 if (!ecc) { ecc.reset(new Secp256k1Init()); }
691 MutateTxAddOutPubKey(tx, commandVal);
692 } else if (command == "outmultisig") {
693 if (!ecc) { ecc.reset(new Secp256k1Init()); }
694 MutateTxAddOutMultiSig(tx, commandVal);
695 } else if (command == "outscript")
696 MutateTxAddOutScript(tx, commandVal);
697 else if (command == "outdata")
698 MutateTxAddOutData(tx, commandVal);
700 else if (command == "sign") {
701 if (!ecc) { ecc.reset(new Secp256k1Init()); }
702 MutateTxSign(tx, commandVal);
705 else if (command == "load")
706 RegisterLoad(commandVal);
708 else if (command == "set")
709 RegisterSet(commandVal);
711 else
712 throw std::runtime_error("unknown command");
715 static void OutputTxJSON(const CTransaction& tx)
717 UniValue entry(UniValue::VOBJ);
718 TxToUniv(tx, uint256(), entry);
720 std::string jsonOutput = entry.write(4);
721 fprintf(stdout, "%s\n", jsonOutput.c_str());
724 static void OutputTxHash(const CTransaction& tx)
726 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
728 fprintf(stdout, "%s\n", strHexHash.c_str());
731 static void OutputTxHex(const CTransaction& tx)
733 std::string strHex = EncodeHexTx(tx);
735 fprintf(stdout, "%s\n", strHex.c_str());
738 static void OutputTx(const CTransaction& tx)
740 if (gArgs.GetBoolArg("-json", false))
741 OutputTxJSON(tx);
742 else if (gArgs.GetBoolArg("-txid", false))
743 OutputTxHash(tx);
744 else
745 OutputTxHex(tx);
748 static std::string readStdin()
750 char buf[4096];
751 std::string ret;
753 while (!feof(stdin)) {
754 size_t bread = fread(buf, 1, sizeof(buf), stdin);
755 ret.append(buf, bread);
756 if (bread < sizeof(buf))
757 break;
760 if (ferror(stdin))
761 throw std::runtime_error("error reading stdin");
763 boost::algorithm::trim_right(ret);
765 return ret;
768 static int CommandLineRawTx(int argc, char* argv[])
770 std::string strPrint;
771 int nRet = 0;
772 try {
773 // Skip switches; Permit common stdin convention "-"
774 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
775 (argv[1][1] != 0)) {
776 argc--;
777 argv++;
780 CMutableTransaction tx;
781 int startArg;
783 if (!fCreateBlank) {
784 // require at least one param
785 if (argc < 2)
786 throw std::runtime_error("too few parameters");
788 // param: hex-encoded bitcoin transaction
789 std::string strHexTx(argv[1]);
790 if (strHexTx == "-") // "-" implies standard input
791 strHexTx = readStdin();
793 if (!DecodeHexTx(tx, strHexTx, true))
794 throw std::runtime_error("invalid transaction encoding");
796 startArg = 2;
797 } else
798 startArg = 1;
800 for (int i = startArg; i < argc; i++) {
801 std::string arg = argv[i];
802 std::string key, value;
803 size_t eqpos = arg.find('=');
804 if (eqpos == std::string::npos)
805 key = arg;
806 else {
807 key = arg.substr(0, eqpos);
808 value = arg.substr(eqpos + 1);
811 MutateTx(tx, key, value);
814 OutputTx(tx);
817 catch (const boost::thread_interrupted&) {
818 throw;
820 catch (const std::exception& e) {
821 strPrint = std::string("error: ") + e.what();
822 nRet = EXIT_FAILURE;
824 catch (...) {
825 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
826 throw;
829 if (strPrint != "") {
830 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
832 return nRet;
835 int main(int argc, char* argv[])
837 SetupEnvironment();
839 try {
840 int ret = AppInitRawTx(argc, argv);
841 if (ret != CONTINUE_EXECUTION)
842 return ret;
844 catch (const std::exception& e) {
845 PrintExceptionContinue(&e, "AppInitRawTx()");
846 return EXIT_FAILURE;
847 } catch (...) {
848 PrintExceptionContinue(nullptr, "AppInitRawTx()");
849 return EXIT_FAILURE;
852 int ret = EXIT_FAILURE;
853 try {
854 ret = CommandLineRawTx(argc, argv);
856 catch (const std::exception& e) {
857 PrintExceptionContinue(&e, "CommandLineRawTx()");
858 } catch (...) {
859 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
861 return ret;