Merge #12001: [RPC] Adding ::minRelayTxFee amount to getmempoolinfo and updating...
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blob9bcf3fe8ddc0134576abf42cc902cf397917ca31
1 // Copyright (c) 2009-2017 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 CTxDestination destination = DecodeDestination(strAddr);
275 if (!IsValidDestination(destination)) {
276 throw std::runtime_error("invalid TX output address");
278 CScript scriptPubKey = GetScriptForDestination(destination);
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 if (!pubkey.IsCompressed()) {
314 throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
316 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
317 scriptPubKey = GetScriptForWitness(scriptPubKey);
319 if (bScriptHash) {
320 // Get the ID for the script, and then construct a P2SH destination for it.
321 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
324 // construct TxOut, append to transaction output list
325 CTxOut txout(value, scriptPubKey);
326 tx.vout.push_back(txout);
329 static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
331 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
332 std::vector<std::string> vStrInputParts;
333 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
335 // Check that there are enough parameters
336 if (vStrInputParts.size()<3)
337 throw std::runtime_error("Not enough multisig parameters");
339 // Extract and validate VALUE
340 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
342 // Extract REQUIRED
343 uint32_t required = stoul(vStrInputParts[1]);
345 // Extract NUMKEYS
346 uint32_t numkeys = stoul(vStrInputParts[2]);
348 // Validate there are the correct number of pubkeys
349 if (vStrInputParts.size() < numkeys + 3)
350 throw std::runtime_error("incorrect number of multisig pubkeys");
352 if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
353 throw std::runtime_error("multisig parameter mismatch. Required " \
354 + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
356 // extract and validate PUBKEYs
357 std::vector<CPubKey> pubkeys;
358 for(int pos = 1; pos <= int(numkeys); pos++) {
359 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
360 if (!pubkey.IsFullyValid())
361 throw std::runtime_error("invalid TX output pubkey");
362 pubkeys.push_back(pubkey);
365 // Extract FLAGS
366 bool bSegWit = false;
367 bool bScriptHash = false;
368 if (vStrInputParts.size() == numkeys + 4) {
369 std::string flags = vStrInputParts.back();
370 bSegWit = (flags.find("W") != std::string::npos);
371 bScriptHash = (flags.find("S") != std::string::npos);
373 else if (vStrInputParts.size() > numkeys + 4) {
374 // Validate that there were no more parameters passed
375 throw std::runtime_error("Too many parameters");
378 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
380 if (bSegWit) {
381 for (CPubKey& pubkey : pubkeys) {
382 if (!pubkey.IsCompressed()) {
383 throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
386 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
387 scriptPubKey = GetScriptForWitness(scriptPubKey);
389 if (bScriptHash) {
390 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
391 throw std::runtime_error(strprintf(
392 "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
394 // Get the ID for the script, and then construct a P2SH destination for it.
395 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
398 // construct TxOut, append to transaction output list
399 CTxOut txout(value, scriptPubKey);
400 tx.vout.push_back(txout);
403 static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
405 CAmount value = 0;
407 // separate [VALUE:]DATA in string
408 size_t pos = strInput.find(':');
410 if (pos==0)
411 throw std::runtime_error("TX output value not specified");
413 if (pos != std::string::npos) {
414 // Extract and validate VALUE
415 value = ExtractAndValidateValue(strInput.substr(0, pos));
418 // extract and validate DATA
419 std::string strData = strInput.substr(pos + 1, std::string::npos);
421 if (!IsHex(strData))
422 throw std::runtime_error("invalid TX output data");
424 std::vector<unsigned char> data = ParseHex(strData);
426 CTxOut txout(value, CScript() << OP_RETURN << data);
427 tx.vout.push_back(txout);
430 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
432 // separate VALUE:SCRIPT[:FLAGS]
433 std::vector<std::string> vStrInputParts;
434 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
435 if (vStrInputParts.size() < 2)
436 throw std::runtime_error("TX output missing separator");
438 // Extract and validate VALUE
439 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
441 // extract and validate script
442 std::string strScript = vStrInputParts[1];
443 CScript scriptPubKey = ParseScript(strScript);
445 // Extract FLAGS
446 bool bSegWit = false;
447 bool bScriptHash = false;
448 if (vStrInputParts.size() == 3) {
449 std::string flags = vStrInputParts.back();
450 bSegWit = (flags.find("W") != std::string::npos);
451 bScriptHash = (flags.find("S") != std::string::npos);
454 if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
455 throw std::runtime_error(strprintf(
456 "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
459 if (bSegWit) {
460 scriptPubKey = GetScriptForWitness(scriptPubKey);
462 if (bScriptHash) {
463 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
464 throw std::runtime_error(strprintf(
465 "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
467 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
470 // construct TxOut, append to transaction output list
471 CTxOut txout(value, scriptPubKey);
472 tx.vout.push_back(txout);
475 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
477 // parse requested deletion index
478 int inIdx = atoi(strInIdx);
479 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
480 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
481 throw std::runtime_error(strErr.c_str());
484 // delete input from transaction
485 tx.vin.erase(tx.vin.begin() + inIdx);
488 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
490 // parse requested deletion index
491 int outIdx = atoi(strOutIdx);
492 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
493 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
494 throw std::runtime_error(strErr.c_str());
497 // delete output from transaction
498 tx.vout.erase(tx.vout.begin() + outIdx);
501 static const unsigned int N_SIGHASH_OPTS = 6;
502 static const struct {
503 const char *flagStr;
504 int flags;
505 } sighashOptions[N_SIGHASH_OPTS] = {
506 {"ALL", SIGHASH_ALL},
507 {"NONE", SIGHASH_NONE},
508 {"SINGLE", SIGHASH_SINGLE},
509 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
510 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
511 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
514 static bool findSighashFlags(int& flags, const std::string& flagStr)
516 flags = 0;
518 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
519 if (flagStr == sighashOptions[i].flagStr) {
520 flags = sighashOptions[i].flags;
521 return true;
525 return false;
528 static CAmount AmountFromValue(const UniValue& value)
530 if (!value.isNum() && !value.isStr())
531 throw std::runtime_error("Amount is not a number or string");
532 CAmount amount;
533 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
534 throw std::runtime_error("Invalid amount");
535 if (!MoneyRange(amount))
536 throw std::runtime_error("Amount out of range");
537 return amount;
540 static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
542 int nHashType = SIGHASH_ALL;
544 if (flagStr.size() > 0)
545 if (!findSighashFlags(nHashType, flagStr))
546 throw std::runtime_error("unknown sighash flag/sign option");
548 std::vector<CTransaction> txVariants;
549 txVariants.push_back(tx);
551 // mergedTx will end up with all the signatures; it
552 // starts as a clone of the raw tx:
553 CMutableTransaction mergedTx(txVariants[0]);
554 bool fComplete = true;
555 CCoinsView viewDummy;
556 CCoinsViewCache view(&viewDummy);
558 if (!registers.count("privatekeys"))
559 throw std::runtime_error("privatekeys register variable must be set.");
560 CBasicKeyStore tempKeystore;
561 UniValue keysObj = registers["privatekeys"];
563 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
564 if (!keysObj[kidx].isStr())
565 throw std::runtime_error("privatekey not a std::string");
566 CBitcoinSecret vchSecret;
567 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
568 if (!fGood)
569 throw std::runtime_error("privatekey not valid");
571 CKey key = vchSecret.GetKey();
572 tempKeystore.AddKey(key);
575 // Add previous txouts given in the RPC call:
576 if (!registers.count("prevtxs"))
577 throw std::runtime_error("prevtxs register variable must be set.");
578 UniValue prevtxsObj = registers["prevtxs"];
580 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
581 UniValue prevOut = prevtxsObj[previdx];
582 if (!prevOut.isObject())
583 throw std::runtime_error("expected prevtxs internal object");
585 std::map<std::string, UniValue::VType> types = {
586 {"txid", UniValue::VSTR},
587 {"vout", UniValue::VNUM},
588 {"scriptPubKey", UniValue::VSTR},
590 if (!prevOut.checkObject(types))
591 throw std::runtime_error("prevtxs internal object typecheck fail");
593 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
595 int nOut = atoi(prevOut["vout"].getValStr());
596 if (nOut < 0)
597 throw std::runtime_error("vout must be positive");
599 COutPoint out(txid, nOut);
600 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
601 CScript scriptPubKey(pkData.begin(), pkData.end());
604 const Coin& coin = view.AccessCoin(out);
605 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
606 std::string err("Previous output scriptPubKey mismatch:\n");
607 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
608 ScriptToAsmStr(scriptPubKey);
609 throw std::runtime_error(err);
611 Coin newcoin;
612 newcoin.out.scriptPubKey = scriptPubKey;
613 newcoin.out.nValue = 0;
614 if (prevOut.exists("amount")) {
615 newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
617 newcoin.nHeight = 1;
618 view.AddCoin(out, std::move(newcoin), true);
621 // if redeemScript given and private keys given,
622 // add redeemScript to the tempKeystore so it can be signed:
623 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
624 prevOut.exists("redeemScript")) {
625 UniValue v = prevOut["redeemScript"];
626 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
627 CScript redeemScript(rsData.begin(), rsData.end());
628 tempKeystore.AddCScript(redeemScript);
633 const CKeyStore& keystore = tempKeystore;
635 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
637 // Sign what we can:
638 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
639 CTxIn& txin = mergedTx.vin[i];
640 const Coin& coin = view.AccessCoin(txin.prevout);
641 if (coin.IsSpent()) {
642 fComplete = false;
643 continue;
645 const CScript& prevPubKey = coin.out.scriptPubKey;
646 const CAmount& amount = coin.out.nValue;
648 SignatureData sigdata;
649 // Only sign SIGHASH_SINGLE if there's a corresponding output:
650 if (!fHashSingle || (i < mergedTx.vout.size()))
651 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
653 // ... and merge in other signatures:
654 for (const CTransaction& txv : txVariants)
655 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
656 UpdateTransaction(mergedTx, i, sigdata);
658 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
659 fComplete = false;
662 if (fComplete) {
663 // do nothing... for now
664 // perhaps store this for later optional JSON output
667 tx = mergedTx;
670 class Secp256k1Init
672 ECCVerifyHandle globalVerifyHandle;
674 public:
675 Secp256k1Init() {
676 ECC_Start();
678 ~Secp256k1Init() {
679 ECC_Stop();
683 static void MutateTx(CMutableTransaction& tx, const std::string& command,
684 const std::string& commandVal)
686 std::unique_ptr<Secp256k1Init> ecc;
688 if (command == "nversion")
689 MutateTxVersion(tx, commandVal);
690 else if (command == "locktime")
691 MutateTxLocktime(tx, commandVal);
692 else if (command == "replaceable") {
693 MutateTxRBFOptIn(tx, commandVal);
696 else if (command == "delin")
697 MutateTxDelInput(tx, commandVal);
698 else if (command == "in")
699 MutateTxAddInput(tx, commandVal);
701 else if (command == "delout")
702 MutateTxDelOutput(tx, commandVal);
703 else if (command == "outaddr")
704 MutateTxAddOutAddr(tx, commandVal);
705 else if (command == "outpubkey") {
706 ecc.reset(new Secp256k1Init());
707 MutateTxAddOutPubKey(tx, commandVal);
708 } else if (command == "outmultisig") {
709 ecc.reset(new Secp256k1Init());
710 MutateTxAddOutMultiSig(tx, commandVal);
711 } else if (command == "outscript")
712 MutateTxAddOutScript(tx, commandVal);
713 else if (command == "outdata")
714 MutateTxAddOutData(tx, commandVal);
716 else if (command == "sign") {
717 ecc.reset(new Secp256k1Init());
718 MutateTxSign(tx, commandVal);
721 else if (command == "load")
722 RegisterLoad(commandVal);
724 else if (command == "set")
725 RegisterSet(commandVal);
727 else
728 throw std::runtime_error("unknown command");
731 static void OutputTxJSON(const CTransaction& tx)
733 UniValue entry(UniValue::VOBJ);
734 TxToUniv(tx, uint256(), entry);
736 std::string jsonOutput = entry.write(4);
737 fprintf(stdout, "%s\n", jsonOutput.c_str());
740 static void OutputTxHash(const CTransaction& tx)
742 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
744 fprintf(stdout, "%s\n", strHexHash.c_str());
747 static void OutputTxHex(const CTransaction& tx)
749 std::string strHex = EncodeHexTx(tx);
751 fprintf(stdout, "%s\n", strHex.c_str());
754 static void OutputTx(const CTransaction& tx)
756 if (gArgs.GetBoolArg("-json", false))
757 OutputTxJSON(tx);
758 else if (gArgs.GetBoolArg("-txid", false))
759 OutputTxHash(tx);
760 else
761 OutputTxHex(tx);
764 static std::string readStdin()
766 char buf[4096];
767 std::string ret;
769 while (!feof(stdin)) {
770 size_t bread = fread(buf, 1, sizeof(buf), stdin);
771 ret.append(buf, bread);
772 if (bread < sizeof(buf))
773 break;
776 if (ferror(stdin))
777 throw std::runtime_error("error reading stdin");
779 boost::algorithm::trim_right(ret);
781 return ret;
784 static int CommandLineRawTx(int argc, char* argv[])
786 std::string strPrint;
787 int nRet = 0;
788 try {
789 // Skip switches; Permit common stdin convention "-"
790 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
791 (argv[1][1] != 0)) {
792 argc--;
793 argv++;
796 CMutableTransaction tx;
797 int startArg;
799 if (!fCreateBlank) {
800 // require at least one param
801 if (argc < 2)
802 throw std::runtime_error("too few parameters");
804 // param: hex-encoded bitcoin transaction
805 std::string strHexTx(argv[1]);
806 if (strHexTx == "-") // "-" implies standard input
807 strHexTx = readStdin();
809 if (!DecodeHexTx(tx, strHexTx, true))
810 throw std::runtime_error("invalid transaction encoding");
812 startArg = 2;
813 } else
814 startArg = 1;
816 for (int i = startArg; i < argc; i++) {
817 std::string arg = argv[i];
818 std::string key, value;
819 size_t eqpos = arg.find('=');
820 if (eqpos == std::string::npos)
821 key = arg;
822 else {
823 key = arg.substr(0, eqpos);
824 value = arg.substr(eqpos + 1);
827 MutateTx(tx, key, value);
830 OutputTx(tx);
833 catch (const boost::thread_interrupted&) {
834 throw;
836 catch (const std::exception& e) {
837 strPrint = std::string("error: ") + e.what();
838 nRet = EXIT_FAILURE;
840 catch (...) {
841 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
842 throw;
845 if (strPrint != "") {
846 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
848 return nRet;
851 int main(int argc, char* argv[])
853 SetupEnvironment();
855 try {
856 int ret = AppInitRawTx(argc, argv);
857 if (ret != CONTINUE_EXECUTION)
858 return ret;
860 catch (const std::exception& e) {
861 PrintExceptionContinue(&e, "AppInitRawTx()");
862 return EXIT_FAILURE;
863 } catch (...) {
864 PrintExceptionContinue(nullptr, "AppInitRawTx()");
865 return EXIT_FAILURE;
868 int ret = EXIT_FAILURE;
869 try {
870 ret = CommandLineRawTx(argc, argv);
872 catch (const std::exception& e) {
873 PrintExceptionContinue(&e, "CommandLineRawTx()");
874 } catch (...) {
875 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
877 return ret;