[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blobe4f44435ba292312e9d755d1a468bf09c6bf835b
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 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 // Get the ID for the script, and then construct a P2SH destination for it.
391 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
394 // construct TxOut, append to transaction output list
395 CTxOut txout(value, scriptPubKey);
396 tx.vout.push_back(txout);
399 static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
401 CAmount value = 0;
403 // separate [VALUE:]DATA in string
404 size_t pos = strInput.find(':');
406 if (pos==0)
407 throw std::runtime_error("TX output value not specified");
409 if (pos != std::string::npos) {
410 // Extract and validate VALUE
411 value = ExtractAndValidateValue(strInput.substr(0, pos));
414 // extract and validate DATA
415 std::string strData = strInput.substr(pos + 1, std::string::npos);
417 if (!IsHex(strData))
418 throw std::runtime_error("invalid TX output data");
420 std::vector<unsigned char> data = ParseHex(strData);
422 CTxOut txout(value, CScript() << OP_RETURN << data);
423 tx.vout.push_back(txout);
426 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
428 // separate VALUE:SCRIPT[:FLAGS]
429 std::vector<std::string> vStrInputParts;
430 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
431 if (vStrInputParts.size() < 2)
432 throw std::runtime_error("TX output missing separator");
434 // Extract and validate VALUE
435 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
437 // extract and validate script
438 std::string strScript = vStrInputParts[1];
439 CScript scriptPubKey = ParseScript(strScript);
441 // Extract FLAGS
442 bool bSegWit = false;
443 bool bScriptHash = false;
444 if (vStrInputParts.size() == 3) {
445 std::string flags = vStrInputParts.back();
446 bSegWit = (flags.find("W") != std::string::npos);
447 bScriptHash = (flags.find("S") != std::string::npos);
450 if (bSegWit) {
451 scriptPubKey = GetScriptForWitness(scriptPubKey);
453 if (bScriptHash) {
454 scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
457 // construct TxOut, append to transaction output list
458 CTxOut txout(value, scriptPubKey);
459 tx.vout.push_back(txout);
462 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
464 // parse requested deletion index
465 int inIdx = atoi(strInIdx);
466 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
467 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
468 throw std::runtime_error(strErr.c_str());
471 // delete input from transaction
472 tx.vin.erase(tx.vin.begin() + inIdx);
475 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
477 // parse requested deletion index
478 int outIdx = atoi(strOutIdx);
479 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
480 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
481 throw std::runtime_error(strErr.c_str());
484 // delete output from transaction
485 tx.vout.erase(tx.vout.begin() + outIdx);
488 static const unsigned int N_SIGHASH_OPTS = 6;
489 static const struct {
490 const char *flagStr;
491 int flags;
492 } sighashOptions[N_SIGHASH_OPTS] = {
493 {"ALL", SIGHASH_ALL},
494 {"NONE", SIGHASH_NONE},
495 {"SINGLE", SIGHASH_SINGLE},
496 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
497 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
498 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
501 static bool findSighashFlags(int& flags, const std::string& flagStr)
503 flags = 0;
505 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
506 if (flagStr == sighashOptions[i].flagStr) {
507 flags = sighashOptions[i].flags;
508 return true;
512 return false;
515 static CAmount AmountFromValue(const UniValue& value)
517 if (!value.isNum() && !value.isStr())
518 throw std::runtime_error("Amount is not a number or string");
519 CAmount amount;
520 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
521 throw std::runtime_error("Invalid amount");
522 if (!MoneyRange(amount))
523 throw std::runtime_error("Amount out of range");
524 return amount;
527 static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
529 int nHashType = SIGHASH_ALL;
531 if (flagStr.size() > 0)
532 if (!findSighashFlags(nHashType, flagStr))
533 throw std::runtime_error("unknown sighash flag/sign option");
535 std::vector<CTransaction> txVariants;
536 txVariants.push_back(tx);
538 // mergedTx will end up with all the signatures; it
539 // starts as a clone of the raw tx:
540 CMutableTransaction mergedTx(txVariants[0]);
541 bool fComplete = true;
542 CCoinsView viewDummy;
543 CCoinsViewCache view(&viewDummy);
545 if (!registers.count("privatekeys"))
546 throw std::runtime_error("privatekeys register variable must be set.");
547 CBasicKeyStore tempKeystore;
548 UniValue keysObj = registers["privatekeys"];
550 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
551 if (!keysObj[kidx].isStr())
552 throw std::runtime_error("privatekey not a std::string");
553 CBitcoinSecret vchSecret;
554 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
555 if (!fGood)
556 throw std::runtime_error("privatekey not valid");
558 CKey key = vchSecret.GetKey();
559 tempKeystore.AddKey(key);
562 // Add previous txouts given in the RPC call:
563 if (!registers.count("prevtxs"))
564 throw std::runtime_error("prevtxs register variable must be set.");
565 UniValue prevtxsObj = registers["prevtxs"];
567 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
568 UniValue prevOut = prevtxsObj[previdx];
569 if (!prevOut.isObject())
570 throw std::runtime_error("expected prevtxs internal object");
572 std::map<std::string, UniValue::VType> types = {
573 {"txid", UniValue::VSTR},
574 {"vout", UniValue::VNUM},
575 {"scriptPubKey", UniValue::VSTR},
577 if (!prevOut.checkObject(types))
578 throw std::runtime_error("prevtxs internal object typecheck fail");
580 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
582 int nOut = atoi(prevOut["vout"].getValStr());
583 if (nOut < 0)
584 throw std::runtime_error("vout must be positive");
586 COutPoint out(txid, nOut);
587 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
588 CScript scriptPubKey(pkData.begin(), pkData.end());
591 const Coin& coin = view.AccessCoin(out);
592 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
593 std::string err("Previous output scriptPubKey mismatch:\n");
594 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
595 ScriptToAsmStr(scriptPubKey);
596 throw std::runtime_error(err);
598 Coin newcoin;
599 newcoin.out.scriptPubKey = scriptPubKey;
600 newcoin.out.nValue = 0;
601 if (prevOut.exists("amount")) {
602 newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
604 newcoin.nHeight = 1;
605 view.AddCoin(out, std::move(newcoin), true);
608 // if redeemScript given and private keys given,
609 // add redeemScript to the tempKeystore so it can be signed:
610 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
611 prevOut.exists("redeemScript")) {
612 UniValue v = prevOut["redeemScript"];
613 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
614 CScript redeemScript(rsData.begin(), rsData.end());
615 tempKeystore.AddCScript(redeemScript);
620 const CKeyStore& keystore = tempKeystore;
622 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
624 // Sign what we can:
625 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
626 CTxIn& txin = mergedTx.vin[i];
627 const Coin& coin = view.AccessCoin(txin.prevout);
628 if (coin.IsSpent()) {
629 fComplete = false;
630 continue;
632 const CScript& prevPubKey = coin.out.scriptPubKey;
633 const CAmount& amount = coin.out.nValue;
635 SignatureData sigdata;
636 // Only sign SIGHASH_SINGLE if there's a corresponding output:
637 if (!fHashSingle || (i < mergedTx.vout.size()))
638 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
640 // ... and merge in other signatures:
641 for (const CTransaction& txv : txVariants)
642 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
643 UpdateTransaction(mergedTx, i, sigdata);
645 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
646 fComplete = false;
649 if (fComplete) {
650 // do nothing... for now
651 // perhaps store this for later optional JSON output
654 tx = mergedTx;
657 class Secp256k1Init
659 ECCVerifyHandle globalVerifyHandle;
661 public:
662 Secp256k1Init() {
663 ECC_Start();
665 ~Secp256k1Init() {
666 ECC_Stop();
670 static void MutateTx(CMutableTransaction& tx, const std::string& command,
671 const std::string& commandVal)
673 std::unique_ptr<Secp256k1Init> ecc;
675 if (command == "nversion")
676 MutateTxVersion(tx, commandVal);
677 else if (command == "locktime")
678 MutateTxLocktime(tx, commandVal);
679 else if (command == "replaceable") {
680 MutateTxRBFOptIn(tx, commandVal);
683 else if (command == "delin")
684 MutateTxDelInput(tx, commandVal);
685 else if (command == "in")
686 MutateTxAddInput(tx, commandVal);
688 else if (command == "delout")
689 MutateTxDelOutput(tx, commandVal);
690 else if (command == "outaddr")
691 MutateTxAddOutAddr(tx, commandVal);
692 else if (command == "outpubkey") {
693 if (!ecc) { ecc.reset(new Secp256k1Init()); }
694 MutateTxAddOutPubKey(tx, commandVal);
695 } else if (command == "outmultisig") {
696 if (!ecc) { ecc.reset(new Secp256k1Init()); }
697 MutateTxAddOutMultiSig(tx, commandVal);
698 } else if (command == "outscript")
699 MutateTxAddOutScript(tx, commandVal);
700 else if (command == "outdata")
701 MutateTxAddOutData(tx, commandVal);
703 else if (command == "sign") {
704 if (!ecc) { ecc.reset(new Secp256k1Init()); }
705 MutateTxSign(tx, commandVal);
708 else if (command == "load")
709 RegisterLoad(commandVal);
711 else if (command == "set")
712 RegisterSet(commandVal);
714 else
715 throw std::runtime_error("unknown command");
718 static void OutputTxJSON(const CTransaction& tx)
720 UniValue entry(UniValue::VOBJ);
721 TxToUniv(tx, uint256(), entry);
723 std::string jsonOutput = entry.write(4);
724 fprintf(stdout, "%s\n", jsonOutput.c_str());
727 static void OutputTxHash(const CTransaction& tx)
729 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
731 fprintf(stdout, "%s\n", strHexHash.c_str());
734 static void OutputTxHex(const CTransaction& tx)
736 std::string strHex = EncodeHexTx(tx);
738 fprintf(stdout, "%s\n", strHex.c_str());
741 static void OutputTx(const CTransaction& tx)
743 if (gArgs.GetBoolArg("-json", false))
744 OutputTxJSON(tx);
745 else if (gArgs.GetBoolArg("-txid", false))
746 OutputTxHash(tx);
747 else
748 OutputTxHex(tx);
751 static std::string readStdin()
753 char buf[4096];
754 std::string ret;
756 while (!feof(stdin)) {
757 size_t bread = fread(buf, 1, sizeof(buf), stdin);
758 ret.append(buf, bread);
759 if (bread < sizeof(buf))
760 break;
763 if (ferror(stdin))
764 throw std::runtime_error("error reading stdin");
766 boost::algorithm::trim_right(ret);
768 return ret;
771 static int CommandLineRawTx(int argc, char* argv[])
773 std::string strPrint;
774 int nRet = 0;
775 try {
776 // Skip switches; Permit common stdin convention "-"
777 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
778 (argv[1][1] != 0)) {
779 argc--;
780 argv++;
783 CMutableTransaction tx;
784 int startArg;
786 if (!fCreateBlank) {
787 // require at least one param
788 if (argc < 2)
789 throw std::runtime_error("too few parameters");
791 // param: hex-encoded bitcoin transaction
792 std::string strHexTx(argv[1]);
793 if (strHexTx == "-") // "-" implies standard input
794 strHexTx = readStdin();
796 if (!DecodeHexTx(tx, strHexTx, true))
797 throw std::runtime_error("invalid transaction encoding");
799 startArg = 2;
800 } else
801 startArg = 1;
803 for (int i = startArg; i < argc; i++) {
804 std::string arg = argv[i];
805 std::string key, value;
806 size_t eqpos = arg.find('=');
807 if (eqpos == std::string::npos)
808 key = arg;
809 else {
810 key = arg.substr(0, eqpos);
811 value = arg.substr(eqpos + 1);
814 MutateTx(tx, key, value);
817 OutputTx(tx);
820 catch (const boost::thread_interrupted&) {
821 throw;
823 catch (const std::exception& e) {
824 strPrint = std::string("error: ") + e.what();
825 nRet = EXIT_FAILURE;
827 catch (...) {
828 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
829 throw;
832 if (strPrint != "") {
833 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
835 return nRet;
838 int main(int argc, char* argv[])
840 SetupEnvironment();
842 try {
843 int ret = AppInitRawTx(argc, argv);
844 if (ret != CONTINUE_EXECUTION)
845 return ret;
847 catch (const std::exception& e) {
848 PrintExceptionContinue(&e, "AppInitRawTx()");
849 return EXIT_FAILURE;
850 } catch (...) {
851 PrintExceptionContinue(nullptr, "AppInitRawTx()");
852 return EXIT_FAILURE;
855 int ret = EXIT_FAILURE;
856 try {
857 ret = CommandLineRawTx(argc, argv);
859 catch (const std::exception& e) {
860 PrintExceptionContinue(&e, "CommandLineRawTx()");
861 } catch (...) {
862 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
864 return ret;