[test] Add getblockchaininfo functional test
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blobd8d7934bf649a17b774d8c7279991d70ca505c39
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 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 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
314 scriptPubKey = GetScriptForWitness(scriptPubKey);
316 if (bScriptHash) {
317 // Get the ID for the script, and then construct a P2SH destination for it.
318 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
321 // construct TxOut, append to transaction output list
322 CTxOut txout(value, scriptPubKey);
323 tx.vout.push_back(txout);
326 static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
328 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
329 std::vector<std::string> vStrInputParts;
330 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
332 // Check that there are enough parameters
333 if (vStrInputParts.size()<3)
334 throw std::runtime_error("Not enough multisig parameters");
336 // Extract and validate VALUE
337 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
339 // Extract REQUIRED
340 uint32_t required = stoul(vStrInputParts[1]);
342 // Extract NUMKEYS
343 uint32_t numkeys = stoul(vStrInputParts[2]);
345 // Validate there are the correct number of pubkeys
346 if (vStrInputParts.size() < numkeys + 3)
347 throw std::runtime_error("incorrect number of multisig pubkeys");
349 if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
350 throw std::runtime_error("multisig parameter mismatch. Required " \
351 + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
353 // extract and validate PUBKEYs
354 std::vector<CPubKey> pubkeys;
355 for(int pos = 1; pos <= int(numkeys); pos++) {
356 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
357 if (!pubkey.IsFullyValid())
358 throw std::runtime_error("invalid TX output pubkey");
359 pubkeys.push_back(pubkey);
362 // Extract FLAGS
363 bool bSegWit = false;
364 bool bScriptHash = false;
365 if (vStrInputParts.size() == numkeys + 4) {
366 std::string flags = vStrInputParts.back();
367 bSegWit = (flags.find("W") != std::string::npos);
368 bScriptHash = (flags.find("S") != std::string::npos);
370 else if (vStrInputParts.size() > numkeys + 4) {
371 // Validate that there were no more parameters passed
372 throw std::runtime_error("Too many parameters");
375 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
377 if (bSegWit) {
378 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
379 scriptPubKey = GetScriptForWitness(scriptPubKey);
381 if (bScriptHash) {
382 // Get the ID for the script, and then construct a P2SH destination for it.
383 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
386 // construct TxOut, append to transaction output list
387 CTxOut txout(value, scriptPubKey);
388 tx.vout.push_back(txout);
391 static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
393 CAmount value = 0;
395 // separate [VALUE:]DATA in string
396 size_t pos = strInput.find(':');
398 if (pos==0)
399 throw std::runtime_error("TX output value not specified");
401 if (pos != std::string::npos) {
402 // Extract and validate VALUE
403 value = ExtractAndValidateValue(strInput.substr(0, pos));
406 // extract and validate DATA
407 std::string strData = strInput.substr(pos + 1, std::string::npos);
409 if (!IsHex(strData))
410 throw std::runtime_error("invalid TX output data");
412 std::vector<unsigned char> data = ParseHex(strData);
414 CTxOut txout(value, CScript() << OP_RETURN << data);
415 tx.vout.push_back(txout);
418 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
420 // separate VALUE:SCRIPT[:FLAGS]
421 std::vector<std::string> vStrInputParts;
422 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
423 if (vStrInputParts.size() < 2)
424 throw std::runtime_error("TX output missing separator");
426 // Extract and validate VALUE
427 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
429 // extract and validate script
430 std::string strScript = vStrInputParts[1];
431 CScript scriptPubKey = ParseScript(strScript);
433 // Extract FLAGS
434 bool bSegWit = false;
435 bool bScriptHash = false;
436 if (vStrInputParts.size() == 3) {
437 std::string flags = vStrInputParts.back();
438 bSegWit = (flags.find("W") != std::string::npos);
439 bScriptHash = (flags.find("S") != std::string::npos);
442 if (bSegWit) {
443 scriptPubKey = GetScriptForWitness(scriptPubKey);
445 if (bScriptHash) {
446 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
449 // construct TxOut, append to transaction output list
450 CTxOut txout(value, scriptPubKey);
451 tx.vout.push_back(txout);
454 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
456 // parse requested deletion index
457 int inIdx = atoi(strInIdx);
458 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
459 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
460 throw std::runtime_error(strErr.c_str());
463 // delete input from transaction
464 tx.vin.erase(tx.vin.begin() + inIdx);
467 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
469 // parse requested deletion index
470 int outIdx = atoi(strOutIdx);
471 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
472 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
473 throw std::runtime_error(strErr.c_str());
476 // delete output from transaction
477 tx.vout.erase(tx.vout.begin() + outIdx);
480 static const unsigned int N_SIGHASH_OPTS = 6;
481 static const struct {
482 const char *flagStr;
483 int flags;
484 } sighashOptions[N_SIGHASH_OPTS] = {
485 {"ALL", SIGHASH_ALL},
486 {"NONE", SIGHASH_NONE},
487 {"SINGLE", SIGHASH_SINGLE},
488 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
489 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
490 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
493 static bool findSighashFlags(int& flags, const std::string& flagStr)
495 flags = 0;
497 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
498 if (flagStr == sighashOptions[i].flagStr) {
499 flags = sighashOptions[i].flags;
500 return true;
504 return false;
507 static CAmount AmountFromValue(const UniValue& value)
509 if (!value.isNum() && !value.isStr())
510 throw std::runtime_error("Amount is not a number or string");
511 CAmount amount;
512 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
513 throw std::runtime_error("Invalid amount");
514 if (!MoneyRange(amount))
515 throw std::runtime_error("Amount out of range");
516 return amount;
519 static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
521 int nHashType = SIGHASH_ALL;
523 if (flagStr.size() > 0)
524 if (!findSighashFlags(nHashType, flagStr))
525 throw std::runtime_error("unknown sighash flag/sign option");
527 std::vector<CTransaction> txVariants;
528 txVariants.push_back(tx);
530 // mergedTx will end up with all the signatures; it
531 // starts as a clone of the raw tx:
532 CMutableTransaction mergedTx(txVariants[0]);
533 bool fComplete = true;
534 CCoinsView viewDummy;
535 CCoinsViewCache view(&viewDummy);
537 if (!registers.count("privatekeys"))
538 throw std::runtime_error("privatekeys register variable must be set.");
539 CBasicKeyStore tempKeystore;
540 UniValue keysObj = registers["privatekeys"];
542 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
543 if (!keysObj[kidx].isStr())
544 throw std::runtime_error("privatekey not a std::string");
545 CBitcoinSecret vchSecret;
546 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
547 if (!fGood)
548 throw std::runtime_error("privatekey not valid");
550 CKey key = vchSecret.GetKey();
551 tempKeystore.AddKey(key);
554 // Add previous txouts given in the RPC call:
555 if (!registers.count("prevtxs"))
556 throw std::runtime_error("prevtxs register variable must be set.");
557 UniValue prevtxsObj = registers["prevtxs"];
559 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
560 UniValue prevOut = prevtxsObj[previdx];
561 if (!prevOut.isObject())
562 throw std::runtime_error("expected prevtxs internal object");
564 std::map<std::string, UniValue::VType> types = {
565 {"txid", UniValue::VSTR},
566 {"vout", UniValue::VNUM},
567 {"scriptPubKey", UniValue::VSTR},
569 if (!prevOut.checkObject(types))
570 throw std::runtime_error("prevtxs internal object typecheck fail");
572 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
574 int nOut = atoi(prevOut["vout"].getValStr());
575 if (nOut < 0)
576 throw std::runtime_error("vout must be positive");
578 COutPoint out(txid, nOut);
579 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
580 CScript scriptPubKey(pkData.begin(), pkData.end());
583 const Coin& coin = view.AccessCoin(out);
584 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
585 std::string err("Previous output scriptPubKey mismatch:\n");
586 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
587 ScriptToAsmStr(scriptPubKey);
588 throw std::runtime_error(err);
590 Coin newcoin;
591 newcoin.out.scriptPubKey = scriptPubKey;
592 newcoin.out.nValue = 0;
593 if (prevOut.exists("amount")) {
594 newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
596 newcoin.nHeight = 1;
597 view.AddCoin(out, std::move(newcoin), true);
600 // if redeemScript given and private keys given,
601 // add redeemScript to the tempKeystore so it can be signed:
602 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
603 prevOut.exists("redeemScript")) {
604 UniValue v = prevOut["redeemScript"];
605 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
606 CScript redeemScript(rsData.begin(), rsData.end());
607 tempKeystore.AddCScript(redeemScript);
612 const CKeyStore& keystore = tempKeystore;
614 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
616 // Sign what we can:
617 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
618 CTxIn& txin = mergedTx.vin[i];
619 const Coin& coin = view.AccessCoin(txin.prevout);
620 if (coin.IsSpent()) {
621 fComplete = false;
622 continue;
624 const CScript& prevPubKey = coin.out.scriptPubKey;
625 const CAmount& amount = coin.out.nValue;
627 SignatureData sigdata;
628 // Only sign SIGHASH_SINGLE if there's a corresponding output:
629 if (!fHashSingle || (i < mergedTx.vout.size()))
630 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
632 // ... and merge in other signatures:
633 for (const CTransaction& txv : txVariants)
634 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
635 UpdateTransaction(mergedTx, i, sigdata);
637 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
638 fComplete = false;
641 if (fComplete) {
642 // do nothing... for now
643 // perhaps store this for later optional JSON output
646 tx = mergedTx;
649 class Secp256k1Init
651 ECCVerifyHandle globalVerifyHandle;
653 public:
654 Secp256k1Init() {
655 ECC_Start();
657 ~Secp256k1Init() {
658 ECC_Stop();
662 static void MutateTx(CMutableTransaction& tx, const std::string& command,
663 const std::string& commandVal)
665 std::unique_ptr<Secp256k1Init> ecc;
667 if (command == "nversion")
668 MutateTxVersion(tx, commandVal);
669 else if (command == "locktime")
670 MutateTxLocktime(tx, commandVal);
671 else if (command == "replaceable") {
672 MutateTxRBFOptIn(tx, commandVal);
675 else if (command == "delin")
676 MutateTxDelInput(tx, commandVal);
677 else if (command == "in")
678 MutateTxAddInput(tx, commandVal);
680 else if (command == "delout")
681 MutateTxDelOutput(tx, commandVal);
682 else if (command == "outaddr")
683 MutateTxAddOutAddr(tx, commandVal);
684 else if (command == "outpubkey") {
685 if (!ecc) { ecc.reset(new Secp256k1Init()); }
686 MutateTxAddOutPubKey(tx, commandVal);
687 } else if (command == "outmultisig") {
688 if (!ecc) { ecc.reset(new Secp256k1Init()); }
689 MutateTxAddOutMultiSig(tx, commandVal);
690 } else if (command == "outscript")
691 MutateTxAddOutScript(tx, commandVal);
692 else if (command == "outdata")
693 MutateTxAddOutData(tx, commandVal);
695 else if (command == "sign") {
696 if (!ecc) { ecc.reset(new Secp256k1Init()); }
697 MutateTxSign(tx, commandVal);
700 else if (command == "load")
701 RegisterLoad(commandVal);
703 else if (command == "set")
704 RegisterSet(commandVal);
706 else
707 throw std::runtime_error("unknown command");
710 static void OutputTxJSON(const CTransaction& tx)
712 UniValue entry(UniValue::VOBJ);
713 TxToUniv(tx, uint256(), entry);
715 std::string jsonOutput = entry.write(4);
716 fprintf(stdout, "%s\n", jsonOutput.c_str());
719 static void OutputTxHash(const CTransaction& tx)
721 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
723 fprintf(stdout, "%s\n", strHexHash.c_str());
726 static void OutputTxHex(const CTransaction& tx)
728 std::string strHex = EncodeHexTx(tx);
730 fprintf(stdout, "%s\n", strHex.c_str());
733 static void OutputTx(const CTransaction& tx)
735 if (gArgs.GetBoolArg("-json", false))
736 OutputTxJSON(tx);
737 else if (gArgs.GetBoolArg("-txid", false))
738 OutputTxHash(tx);
739 else
740 OutputTxHex(tx);
743 static std::string readStdin()
745 char buf[4096];
746 std::string ret;
748 while (!feof(stdin)) {
749 size_t bread = fread(buf, 1, sizeof(buf), stdin);
750 ret.append(buf, bread);
751 if (bread < sizeof(buf))
752 break;
755 if (ferror(stdin))
756 throw std::runtime_error("error reading stdin");
758 boost::algorithm::trim_right(ret);
760 return ret;
763 static int CommandLineRawTx(int argc, char* argv[])
765 std::string strPrint;
766 int nRet = 0;
767 try {
768 // Skip switches; Permit common stdin convention "-"
769 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
770 (argv[1][1] != 0)) {
771 argc--;
772 argv++;
775 CMutableTransaction tx;
776 int startArg;
778 if (!fCreateBlank) {
779 // require at least one param
780 if (argc < 2)
781 throw std::runtime_error("too few parameters");
783 // param: hex-encoded bitcoin transaction
784 std::string strHexTx(argv[1]);
785 if (strHexTx == "-") // "-" implies standard input
786 strHexTx = readStdin();
788 if (!DecodeHexTx(tx, strHexTx, true))
789 throw std::runtime_error("invalid transaction encoding");
791 startArg = 2;
792 } else
793 startArg = 1;
795 for (int i = startArg; i < argc; i++) {
796 std::string arg = argv[i];
797 std::string key, value;
798 size_t eqpos = arg.find('=');
799 if (eqpos == std::string::npos)
800 key = arg;
801 else {
802 key = arg.substr(0, eqpos);
803 value = arg.substr(eqpos + 1);
806 MutateTx(tx, key, value);
809 OutputTx(tx);
812 catch (const boost::thread_interrupted&) {
813 throw;
815 catch (const std::exception& e) {
816 strPrint = std::string("error: ") + e.what();
817 nRet = EXIT_FAILURE;
819 catch (...) {
820 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
821 throw;
824 if (strPrint != "") {
825 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
827 return nRet;
830 int main(int argc, char* argv[])
832 SetupEnvironment();
834 try {
835 int ret = AppInitRawTx(argc, argv);
836 if (ret != CONTINUE_EXECUTION)
837 return ret;
839 catch (const std::exception& e) {
840 PrintExceptionContinue(&e, "AppInitRawTx()");
841 return EXIT_FAILURE;
842 } catch (...) {
843 PrintExceptionContinue(nullptr, "AppInitRawTx()");
844 return EXIT_FAILURE;
847 int ret = EXIT_FAILURE;
848 try {
849 ret = CommandLineRawTx(argc, argv);
851 catch (const std::exception& e) {
852 PrintExceptionContinue(&e, "CommandLineRawTx()");
853 } catch (...) {
854 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
856 return ret;