scripted-diff: various renames for per-utxo consistency
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blobcf280f485cb93c2634d20747c3133df158139ea1
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 "primitives/transaction.h"
17 #include "script/script.h"
18 #include "script/sign.h"
19 #include <univalue.h>
20 #include "util.h"
21 #include "utilmoneystr.h"
22 #include "utilstrencodings.h"
24 #include <stdio.h>
26 #include <boost/algorithm/string.hpp>
27 #include <boost/assign/list_of.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 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 = GetBoolArg("-create", false);
54 if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || 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("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
81 strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
82 _("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
83 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
84 strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
85 strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
86 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
87 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
88 strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
89 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
90 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
91 strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
92 _("This command requires JSON registers:") +
93 _("prevtxs=JSON object") + ", " +
94 _("privatekeys=JSON object") + ". " +
95 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
96 fprintf(stdout, "%s", strUsage.c_str());
98 strUsage = HelpMessageGroup(_("Register Commands:"));
99 strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
100 strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
101 fprintf(stdout, "%s", strUsage.c_str());
103 if (argc < 2) {
104 fprintf(stderr, "Error: too few parameters\n");
105 return EXIT_FAILURE;
107 return EXIT_SUCCESS;
109 return CONTINUE_EXECUTION;
112 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
114 UniValue val;
115 if (!val.read(rawJson)) {
116 std::string strErr = "Cannot parse JSON for key " + key;
117 throw std::runtime_error(strErr);
120 registers[key] = val;
123 static void RegisterSet(const std::string& strInput)
125 // separate NAME:VALUE in string
126 size_t pos = strInput.find(':');
127 if ((pos == std::string::npos) ||
128 (pos == 0) ||
129 (pos == (strInput.size() - 1)))
130 throw std::runtime_error("Register input requires NAME:VALUE");
132 std::string key = strInput.substr(0, pos);
133 std::string valStr = strInput.substr(pos + 1, std::string::npos);
135 RegisterSetJson(key, valStr);
138 static void RegisterLoad(const std::string& strInput)
140 // separate NAME:FILENAME in string
141 size_t pos = strInput.find(':');
142 if ((pos == std::string::npos) ||
143 (pos == 0) ||
144 (pos == (strInput.size() - 1)))
145 throw std::runtime_error("Register load requires NAME:FILENAME");
147 std::string key = strInput.substr(0, pos);
148 std::string filename = strInput.substr(pos + 1, std::string::npos);
150 FILE *f = fopen(filename.c_str(), "r");
151 if (!f) {
152 std::string strErr = "Cannot open file " + filename;
153 throw std::runtime_error(strErr);
156 // load file chunks into one big buffer
157 std::string valStr;
158 while ((!feof(f)) && (!ferror(f))) {
159 char buf[4096];
160 int bread = fread(buf, 1, sizeof(buf), f);
161 if (bread <= 0)
162 break;
164 valStr.insert(valStr.size(), buf, bread);
167 int error = ferror(f);
168 fclose(f);
170 if (error) {
171 std::string strErr = "Error reading file " + filename;
172 throw std::runtime_error(strErr);
175 // evaluate as JSON buffer register
176 RegisterSetJson(key, valStr);
179 static CAmount ExtractAndValidateValue(const std::string& strValue)
181 CAmount value;
182 if (!ParseMoney(strValue, value))
183 throw std::runtime_error("invalid TX output value");
184 return value;
187 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
189 int64_t newVersion = atoi64(cmdVal);
190 if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
191 throw std::runtime_error("Invalid TX version requested");
193 tx.nVersion = (int) newVersion;
196 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
198 int64_t newLocktime = atoi64(cmdVal);
199 if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
200 throw std::runtime_error("Invalid TX locktime requested");
202 tx.nLockTime = (unsigned int) newLocktime;
205 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
207 std::vector<std::string> vStrInputParts;
208 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
210 // separate TXID:VOUT in string
211 if (vStrInputParts.size()<2)
212 throw std::runtime_error("TX input missing separator");
214 // extract and validate TXID
215 std::string strTxid = vStrInputParts[0];
216 if ((strTxid.size() != 64) || !IsHex(strTxid))
217 throw std::runtime_error("invalid TX input txid");
218 uint256 txid(uint256S(strTxid));
220 static const unsigned int minTxOutSz = 9;
221 static const unsigned int maxVout = MAX_BLOCK_BASE_SIZE / minTxOutSz;
223 // extract and validate vout
224 std::string strVout = vStrInputParts[1];
225 int vout = atoi(strVout);
226 if ((vout < 0) || (vout > (int)maxVout))
227 throw std::runtime_error("invalid TX input vout");
229 // extract the optional sequence number
230 uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
231 if (vStrInputParts.size() > 2)
232 nSequenceIn = std::stoul(vStrInputParts[2]);
234 // append to transaction input list
235 CTxIn txin(txid, vout, CScript(), nSequenceIn);
236 tx.vin.push_back(txin);
239 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
241 // Separate into VALUE:ADDRESS
242 std::vector<std::string> vStrInputParts;
243 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
245 if (vStrInputParts.size() != 2)
246 throw std::runtime_error("TX output missing or too many separators");
248 // Extract and validate VALUE
249 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
251 // extract and validate ADDRESS
252 std::string strAddr = vStrInputParts[1];
253 CBitcoinAddress addr(strAddr);
254 if (!addr.IsValid())
255 throw std::runtime_error("invalid TX output address");
256 // build standard output script via GetScriptForDestination()
257 CScript scriptPubKey = GetScriptForDestination(addr.Get());
259 // construct TxOut, append to transaction output list
260 CTxOut txout(value, scriptPubKey);
261 tx.vout.push_back(txout);
264 static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
266 // Separate into VALUE:PUBKEY[:FLAGS]
267 std::vector<std::string> vStrInputParts;
268 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
270 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
271 throw std::runtime_error("TX output missing or too many separators");
273 // Extract and validate VALUE
274 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
276 // Extract and validate PUBKEY
277 CPubKey pubkey(ParseHex(vStrInputParts[1]));
278 if (!pubkey.IsFullyValid())
279 throw std::runtime_error("invalid TX output pubkey");
280 CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
281 CBitcoinAddress addr(scriptPubKey);
283 // Extract and validate FLAGS
284 bool bSegWit = false;
285 bool bScriptHash = false;
286 if (vStrInputParts.size() == 3) {
287 std::string flags = vStrInputParts[2];
288 bSegWit = (flags.find("W") != std::string::npos);
289 bScriptHash = (flags.find("S") != std::string::npos);
292 if (bSegWit) {
293 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
294 scriptPubKey = GetScriptForWitness(scriptPubKey);
296 if (bScriptHash) {
297 // Get the address for the redeem script, then call
298 // GetScriptForDestination() to construct a P2SH scriptPubKey.
299 CBitcoinAddress redeemScriptAddr(scriptPubKey);
300 scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get());
303 // construct TxOut, append to transaction output list
304 CTxOut txout(value, scriptPubKey);
305 tx.vout.push_back(txout);
308 static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
310 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
311 std::vector<std::string> vStrInputParts;
312 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
314 // Check that there are enough parameters
315 if (vStrInputParts.size()<3)
316 throw std::runtime_error("Not enough multisig parameters");
318 // Extract and validate VALUE
319 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
321 // Extract REQUIRED
322 uint32_t required = stoul(vStrInputParts[1]);
324 // Extract NUMKEYS
325 uint32_t numkeys = stoul(vStrInputParts[2]);
327 // Validate there are the correct number of pubkeys
328 if (vStrInputParts.size() < numkeys + 3)
329 throw std::runtime_error("incorrect number of multisig pubkeys");
331 if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
332 throw std::runtime_error("multisig parameter mismatch. Required " \
333 + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
335 // extract and validate PUBKEYs
336 std::vector<CPubKey> pubkeys;
337 for(int pos = 1; pos <= int(numkeys); pos++) {
338 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
339 if (!pubkey.IsFullyValid())
340 throw std::runtime_error("invalid TX output pubkey");
341 pubkeys.push_back(pubkey);
344 // Extract FLAGS
345 bool bSegWit = false;
346 bool bScriptHash = false;
347 if (vStrInputParts.size() == numkeys + 4) {
348 std::string flags = vStrInputParts.back();
349 bSegWit = (flags.find("W") != std::string::npos);
350 bScriptHash = (flags.find("S") != std::string::npos);
352 else if (vStrInputParts.size() > numkeys + 4) {
353 // Validate that there were no more parameters passed
354 throw std::runtime_error("Too many parameters");
357 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
359 if (bSegWit) {
360 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
361 scriptPubKey = GetScriptForWitness(scriptPubKey);
363 if (bScriptHash) {
364 // Get the address for the redeem script, then call
365 // GetScriptForDestination() to construct a P2SH scriptPubKey.
366 CBitcoinAddress addr(scriptPubKey);
367 scriptPubKey = GetScriptForDestination(addr.Get());
370 // construct TxOut, append to transaction output list
371 CTxOut txout(value, scriptPubKey);
372 tx.vout.push_back(txout);
375 static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
377 CAmount value = 0;
379 // separate [VALUE:]DATA in string
380 size_t pos = strInput.find(':');
382 if (pos==0)
383 throw std::runtime_error("TX output value not specified");
385 if (pos != std::string::npos) {
386 // Extract and validate VALUE
387 value = ExtractAndValidateValue(strInput.substr(0, pos));
390 // extract and validate DATA
391 std::string strData = strInput.substr(pos + 1, std::string::npos);
393 if (!IsHex(strData))
394 throw std::runtime_error("invalid TX output data");
396 std::vector<unsigned char> data = ParseHex(strData);
398 CTxOut txout(value, CScript() << OP_RETURN << data);
399 tx.vout.push_back(txout);
402 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
404 // separate VALUE:SCRIPT[:FLAGS]
405 std::vector<std::string> vStrInputParts;
406 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
407 if (vStrInputParts.size() < 2)
408 throw std::runtime_error("TX output missing separator");
410 // Extract and validate VALUE
411 CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
413 // extract and validate script
414 std::string strScript = vStrInputParts[1];
415 CScript scriptPubKey = ParseScript(strScript);
417 // Extract FLAGS
418 bool bSegWit = false;
419 bool bScriptHash = false;
420 if (vStrInputParts.size() == 3) {
421 std::string flags = vStrInputParts.back();
422 bSegWit = (flags.find("W") != std::string::npos);
423 bScriptHash = (flags.find("S") != std::string::npos);
426 if (bSegWit) {
427 scriptPubKey = GetScriptForWitness(scriptPubKey);
429 if (bScriptHash) {
430 CBitcoinAddress addr(scriptPubKey);
431 scriptPubKey = GetScriptForDestination(addr.Get());
434 // construct TxOut, append to transaction output list
435 CTxOut txout(value, scriptPubKey);
436 tx.vout.push_back(txout);
439 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
441 // parse requested deletion index
442 int inIdx = atoi(strInIdx);
443 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
444 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
445 throw std::runtime_error(strErr.c_str());
448 // delete input from transaction
449 tx.vin.erase(tx.vin.begin() + inIdx);
452 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
454 // parse requested deletion index
455 int outIdx = atoi(strOutIdx);
456 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
457 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
458 throw std::runtime_error(strErr.c_str());
461 // delete output from transaction
462 tx.vout.erase(tx.vout.begin() + outIdx);
465 static const unsigned int N_SIGHASH_OPTS = 6;
466 static const struct {
467 const char *flagStr;
468 int flags;
469 } sighashOptions[N_SIGHASH_OPTS] = {
470 {"ALL", SIGHASH_ALL},
471 {"NONE", SIGHASH_NONE},
472 {"SINGLE", SIGHASH_SINGLE},
473 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
474 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
475 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
478 static bool findSighashFlags(int& flags, const std::string& flagStr)
480 flags = 0;
482 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
483 if (flagStr == sighashOptions[i].flagStr) {
484 flags = sighashOptions[i].flags;
485 return true;
489 return false;
492 static CAmount AmountFromValue(const UniValue& value)
494 if (!value.isNum() && !value.isStr())
495 throw std::runtime_error("Amount is not a number or string");
496 CAmount amount;
497 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
498 throw std::runtime_error("Invalid amount");
499 if (!MoneyRange(amount))
500 throw std::runtime_error("Amount out of range");
501 return amount;
504 static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
506 int nHashType = SIGHASH_ALL;
508 if (flagStr.size() > 0)
509 if (!findSighashFlags(nHashType, flagStr))
510 throw std::runtime_error("unknown sighash flag/sign option");
512 std::vector<CTransaction> txVariants;
513 txVariants.push_back(tx);
515 // mergedTx will end up with all the signatures; it
516 // starts as a clone of the raw tx:
517 CMutableTransaction mergedTx(txVariants[0]);
518 bool fComplete = true;
519 CCoinsView viewDummy;
520 CCoinsViewCache view(&viewDummy);
522 if (!registers.count("privatekeys"))
523 throw std::runtime_error("privatekeys register variable must be set.");
524 CBasicKeyStore tempKeystore;
525 UniValue keysObj = registers["privatekeys"];
527 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
528 if (!keysObj[kidx].isStr())
529 throw std::runtime_error("privatekey not a std::string");
530 CBitcoinSecret vchSecret;
531 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
532 if (!fGood)
533 throw std::runtime_error("privatekey not valid");
535 CKey key = vchSecret.GetKey();
536 tempKeystore.AddKey(key);
539 // Add previous txouts given in the RPC call:
540 if (!registers.count("prevtxs"))
541 throw std::runtime_error("prevtxs register variable must be set.");
542 UniValue prevtxsObj = registers["prevtxs"];
544 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
545 UniValue prevOut = prevtxsObj[previdx];
546 if (!prevOut.isObject())
547 throw std::runtime_error("expected prevtxs internal object");
549 std::map<std::string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
550 if (!prevOut.checkObject(types))
551 throw std::runtime_error("prevtxs internal object typecheck fail");
553 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
555 int nOut = atoi(prevOut["vout"].getValStr());
556 if (nOut < 0)
557 throw std::runtime_error("vout must be positive");
559 COutPoint out(txid, nOut);
560 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
561 CScript scriptPubKey(pkData.begin(), pkData.end());
564 const Coin& coin = view.AccessCoin(out);
565 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
566 std::string err("Previous output scriptPubKey mismatch:\n");
567 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
568 ScriptToAsmStr(scriptPubKey);
569 throw std::runtime_error(err);
571 Coin newcoin;
572 newcoin.out.scriptPubKey = scriptPubKey;
573 newcoin.out.nValue = 0;
574 if (prevOut.exists("amount")) {
575 newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
577 newcoin.nHeight = 1;
578 view.AddCoin(out, std::move(newcoin), true);
581 // if redeemScript given and private keys given,
582 // add redeemScript to the tempKeystore so it can be signed:
583 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
584 prevOut.exists("redeemScript")) {
585 UniValue v = prevOut["redeemScript"];
586 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
587 CScript redeemScript(rsData.begin(), rsData.end());
588 tempKeystore.AddCScript(redeemScript);
593 const CKeyStore& keystore = tempKeystore;
595 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
597 // Sign what we can:
598 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
599 CTxIn& txin = mergedTx.vin[i];
600 const Coin& coin = view.AccessCoin(txin.prevout);
601 if (coin.IsSpent()) {
602 fComplete = false;
603 continue;
605 const CScript& prevPubKey = coin.out.scriptPubKey;
606 const CAmount& amount = coin.out.nValue;
608 SignatureData sigdata;
609 // Only sign SIGHASH_SINGLE if there's a corresponding output:
610 if (!fHashSingle || (i < mergedTx.vout.size()))
611 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
613 // ... and merge in other signatures:
614 BOOST_FOREACH(const CTransaction& txv, txVariants)
615 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
616 UpdateTransaction(mergedTx, i, sigdata);
618 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
619 fComplete = false;
622 if (fComplete) {
623 // do nothing... for now
624 // perhaps store this for later optional JSON output
627 tx = mergedTx;
630 class Secp256k1Init
632 ECCVerifyHandle globalVerifyHandle;
634 public:
635 Secp256k1Init() {
636 ECC_Start();
638 ~Secp256k1Init() {
639 ECC_Stop();
643 static void MutateTx(CMutableTransaction& tx, const std::string& command,
644 const std::string& commandVal)
646 std::unique_ptr<Secp256k1Init> ecc;
648 if (command == "nversion")
649 MutateTxVersion(tx, commandVal);
650 else if (command == "locktime")
651 MutateTxLocktime(tx, commandVal);
653 else if (command == "delin")
654 MutateTxDelInput(tx, commandVal);
655 else if (command == "in")
656 MutateTxAddInput(tx, commandVal);
658 else if (command == "delout")
659 MutateTxDelOutput(tx, commandVal);
660 else if (command == "outaddr")
661 MutateTxAddOutAddr(tx, commandVal);
662 else if (command == "outpubkey") {
663 if (!ecc) { ecc.reset(new Secp256k1Init()); }
664 MutateTxAddOutPubKey(tx, commandVal);
665 } else if (command == "outmultisig") {
666 if (!ecc) { ecc.reset(new Secp256k1Init()); }
667 MutateTxAddOutMultiSig(tx, commandVal);
668 } else if (command == "outscript")
669 MutateTxAddOutScript(tx, commandVal);
670 else if (command == "outdata")
671 MutateTxAddOutData(tx, commandVal);
673 else if (command == "sign") {
674 if (!ecc) { ecc.reset(new Secp256k1Init()); }
675 MutateTxSign(tx, commandVal);
678 else if (command == "load")
679 RegisterLoad(commandVal);
681 else if (command == "set")
682 RegisterSet(commandVal);
684 else
685 throw std::runtime_error("unknown command");
688 static void OutputTxJSON(const CTransaction& tx)
690 UniValue entry(UniValue::VOBJ);
691 TxToUniv(tx, uint256(), entry);
693 std::string jsonOutput = entry.write(4);
694 fprintf(stdout, "%s\n", jsonOutput.c_str());
697 static void OutputTxHash(const CTransaction& tx)
699 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
701 fprintf(stdout, "%s\n", strHexHash.c_str());
704 static void OutputTxHex(const CTransaction& tx)
706 std::string strHex = EncodeHexTx(tx);
708 fprintf(stdout, "%s\n", strHex.c_str());
711 static void OutputTx(const CTransaction& tx)
713 if (GetBoolArg("-json", false))
714 OutputTxJSON(tx);
715 else if (GetBoolArg("-txid", false))
716 OutputTxHash(tx);
717 else
718 OutputTxHex(tx);
721 static std::string readStdin()
723 char buf[4096];
724 std::string ret;
726 while (!feof(stdin)) {
727 size_t bread = fread(buf, 1, sizeof(buf), stdin);
728 ret.append(buf, bread);
729 if (bread < sizeof(buf))
730 break;
733 if (ferror(stdin))
734 throw std::runtime_error("error reading stdin");
736 boost::algorithm::trim_right(ret);
738 return ret;
741 static int CommandLineRawTx(int argc, char* argv[])
743 std::string strPrint;
744 int nRet = 0;
745 try {
746 // Skip switches; Permit common stdin convention "-"
747 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
748 (argv[1][1] != 0)) {
749 argc--;
750 argv++;
753 CMutableTransaction tx;
754 int startArg;
756 if (!fCreateBlank) {
757 // require at least one param
758 if (argc < 2)
759 throw std::runtime_error("too few parameters");
761 // param: hex-encoded bitcoin transaction
762 std::string strHexTx(argv[1]);
763 if (strHexTx == "-") // "-" implies standard input
764 strHexTx = readStdin();
766 if (!DecodeHexTx(tx, strHexTx, true))
767 throw std::runtime_error("invalid transaction encoding");
769 startArg = 2;
770 } else
771 startArg = 1;
773 for (int i = startArg; i < argc; i++) {
774 std::string arg = argv[i];
775 std::string key, value;
776 size_t eqpos = arg.find('=');
777 if (eqpos == std::string::npos)
778 key = arg;
779 else {
780 key = arg.substr(0, eqpos);
781 value = arg.substr(eqpos + 1);
784 MutateTx(tx, key, value);
787 OutputTx(tx);
790 catch (const boost::thread_interrupted&) {
791 throw;
793 catch (const std::exception& e) {
794 strPrint = std::string("error: ") + e.what();
795 nRet = EXIT_FAILURE;
797 catch (...) {
798 PrintExceptionContinue(NULL, "CommandLineRawTx()");
799 throw;
802 if (strPrint != "") {
803 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
805 return nRet;
808 int main(int argc, char* argv[])
810 SetupEnvironment();
812 try {
813 int ret = AppInitRawTx(argc, argv);
814 if (ret != CONTINUE_EXECUTION)
815 return ret;
817 catch (const std::exception& e) {
818 PrintExceptionContinue(&e, "AppInitRawTx()");
819 return EXIT_FAILURE;
820 } catch (...) {
821 PrintExceptionContinue(NULL, "AppInitRawTx()");
822 return EXIT_FAILURE;
825 int ret = EXIT_FAILURE;
826 try {
827 ret = CommandLineRawTx(argc, argv);
829 catch (const std::exception& e) {
830 PrintExceptionContinue(&e, "CommandLineRawTx()");
831 } catch (...) {
832 PrintExceptionContinue(NULL, "CommandLineRawTx()");
834 return ret;