Update to latest libsecp256k1
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blob45738b5df83f60be4bd7aa5914e349d0f9e11768
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 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
560 CScript scriptPubKey(pkData.begin(), pkData.end());
563 CCoinsModifier coins = view.ModifyCoins(txid);
564 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
565 std::string err("Previous output scriptPubKey mismatch:\n");
566 err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
567 ScriptToAsmStr(scriptPubKey);
568 throw std::runtime_error(err);
570 if ((unsigned int)nOut >= coins->vout.size())
571 coins->vout.resize(nOut+1);
572 coins->vout[nOut].scriptPubKey = scriptPubKey;
573 coins->vout[nOut].nValue = 0;
574 if (prevOut.exists("amount")) {
575 coins->vout[nOut].nValue = AmountFromValue(prevOut["amount"]);
579 // if redeemScript given and private keys given,
580 // add redeemScript to the tempKeystore so it can be signed:
581 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
582 prevOut.exists("redeemScript")) {
583 UniValue v = prevOut["redeemScript"];
584 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
585 CScript redeemScript(rsData.begin(), rsData.end());
586 tempKeystore.AddCScript(redeemScript);
591 const CKeyStore& keystore = tempKeystore;
593 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
595 // Sign what we can:
596 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
597 CTxIn& txin = mergedTx.vin[i];
598 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
599 if (!coins || !coins->IsAvailable(txin.prevout.n)) {
600 fComplete = false;
601 continue;
603 const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
604 const CAmount& amount = coins->vout[txin.prevout.n].nValue;
606 SignatureData sigdata;
607 // Only sign SIGHASH_SINGLE if there's a corresponding output:
608 if (!fHashSingle || (i < mergedTx.vout.size()))
609 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
611 // ... and merge in other signatures:
612 BOOST_FOREACH(const CTransaction& txv, txVariants)
613 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
614 UpdateTransaction(mergedTx, i, sigdata);
616 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
617 fComplete = false;
620 if (fComplete) {
621 // do nothing... for now
622 // perhaps store this for later optional JSON output
625 tx = mergedTx;
628 class Secp256k1Init
630 ECCVerifyHandle globalVerifyHandle;
632 public:
633 Secp256k1Init() {
634 ECC_Start();
636 ~Secp256k1Init() {
637 ECC_Stop();
641 static void MutateTx(CMutableTransaction& tx, const std::string& command,
642 const std::string& commandVal)
644 std::unique_ptr<Secp256k1Init> ecc;
646 if (command == "nversion")
647 MutateTxVersion(tx, commandVal);
648 else if (command == "locktime")
649 MutateTxLocktime(tx, commandVal);
651 else if (command == "delin")
652 MutateTxDelInput(tx, commandVal);
653 else if (command == "in")
654 MutateTxAddInput(tx, commandVal);
656 else if (command == "delout")
657 MutateTxDelOutput(tx, commandVal);
658 else if (command == "outaddr")
659 MutateTxAddOutAddr(tx, commandVal);
660 else if (command == "outpubkey") {
661 if (!ecc) { ecc.reset(new Secp256k1Init()); }
662 MutateTxAddOutPubKey(tx, commandVal);
663 } else if (command == "outmultisig") {
664 if (!ecc) { ecc.reset(new Secp256k1Init()); }
665 MutateTxAddOutMultiSig(tx, commandVal);
666 } else if (command == "outscript")
667 MutateTxAddOutScript(tx, commandVal);
668 else if (command == "outdata")
669 MutateTxAddOutData(tx, commandVal);
671 else if (command == "sign") {
672 if (!ecc) { ecc.reset(new Secp256k1Init()); }
673 MutateTxSign(tx, commandVal);
676 else if (command == "load")
677 RegisterLoad(commandVal);
679 else if (command == "set")
680 RegisterSet(commandVal);
682 else
683 throw std::runtime_error("unknown command");
686 static void OutputTxJSON(const CTransaction& tx)
688 UniValue entry(UniValue::VOBJ);
689 TxToUniv(tx, uint256(), entry);
691 std::string jsonOutput = entry.write(4);
692 fprintf(stdout, "%s\n", jsonOutput.c_str());
695 static void OutputTxHash(const CTransaction& tx)
697 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
699 fprintf(stdout, "%s\n", strHexHash.c_str());
702 static void OutputTxHex(const CTransaction& tx)
704 std::string strHex = EncodeHexTx(tx);
706 fprintf(stdout, "%s\n", strHex.c_str());
709 static void OutputTx(const CTransaction& tx)
711 if (GetBoolArg("-json", false))
712 OutputTxJSON(tx);
713 else if (GetBoolArg("-txid", false))
714 OutputTxHash(tx);
715 else
716 OutputTxHex(tx);
719 static std::string readStdin()
721 char buf[4096];
722 std::string ret;
724 while (!feof(stdin)) {
725 size_t bread = fread(buf, 1, sizeof(buf), stdin);
726 ret.append(buf, bread);
727 if (bread < sizeof(buf))
728 break;
731 if (ferror(stdin))
732 throw std::runtime_error("error reading stdin");
734 boost::algorithm::trim_right(ret);
736 return ret;
739 static int CommandLineRawTx(int argc, char* argv[])
741 std::string strPrint;
742 int nRet = 0;
743 try {
744 // Skip switches; Permit common stdin convention "-"
745 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
746 (argv[1][1] != 0)) {
747 argc--;
748 argv++;
751 CMutableTransaction tx;
752 int startArg;
754 if (!fCreateBlank) {
755 // require at least one param
756 if (argc < 2)
757 throw std::runtime_error("too few parameters");
759 // param: hex-encoded bitcoin transaction
760 std::string strHexTx(argv[1]);
761 if (strHexTx == "-") // "-" implies standard input
762 strHexTx = readStdin();
764 if (!DecodeHexTx(tx, strHexTx, true))
765 throw std::runtime_error("invalid transaction encoding");
767 startArg = 2;
768 } else
769 startArg = 1;
771 for (int i = startArg; i < argc; i++) {
772 std::string arg = argv[i];
773 std::string key, value;
774 size_t eqpos = arg.find('=');
775 if (eqpos == std::string::npos)
776 key = arg;
777 else {
778 key = arg.substr(0, eqpos);
779 value = arg.substr(eqpos + 1);
782 MutateTx(tx, key, value);
785 OutputTx(tx);
788 catch (const boost::thread_interrupted&) {
789 throw;
791 catch (const std::exception& e) {
792 strPrint = std::string("error: ") + e.what();
793 nRet = EXIT_FAILURE;
795 catch (...) {
796 PrintExceptionContinue(NULL, "CommandLineRawTx()");
797 throw;
800 if (strPrint != "") {
801 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
803 return nRet;
806 int main(int argc, char* argv[])
808 SetupEnvironment();
810 try {
811 int ret = AppInitRawTx(argc, argv);
812 if (ret != CONTINUE_EXECUTION)
813 return ret;
815 catch (const std::exception& e) {
816 PrintExceptionContinue(&e, "AppInitRawTx()");
817 return EXIT_FAILURE;
818 } catch (...) {
819 PrintExceptionContinue(NULL, "AppInitRawTx()");
820 return EXIT_FAILURE;
823 int ret = EXIT_FAILURE;
824 try {
825 ret = CommandLineRawTx(argc, argv);
827 catch (const std::exception& e) {
828 PrintExceptionContinue(&e, "CommandLineRawTx()");
829 } catch (...) {
830 PrintExceptionContinue(NULL, "CommandLineRawTx()");
832 return ret;