[depends] ccache 3.3.1
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blobcb863bda191f809353a43f67cd52990c0ba87420
1 // Copyright (c) 2009-2015 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 using namespace std;
31 static bool fCreateBlank;
32 static map<string,UniValue> registers;
34 static bool AppInitRawTx(int argc, char* argv[])
37 // Parameters
39 ParseParameters(argc, argv);
41 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
42 try {
43 SelectParams(ChainNameFromCommandLine());
44 } catch (const std::exception& e) {
45 fprintf(stderr, "Error: %s\n", e.what());
46 return false;
49 fCreateBlank = GetBoolArg("-create", false);
51 if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
53 // First part of help message is specific to this utility
54 std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
55 _("Usage:") + "\n" +
56 " bitcoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded bitcoin transaction") + "\n" +
57 " bitcoin-tx [options] -create [commands] " + _("Create hex-encoded bitcoin transaction") + "\n" +
58 "\n";
60 fprintf(stdout, "%s", strUsage.c_str());
62 strUsage = HelpMessageGroup(_("Options:"));
63 strUsage += HelpMessageOpt("-?", _("This help message"));
64 strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
65 strUsage += HelpMessageOpt("-json", _("Select JSON output"));
66 strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
67 AppendParamsHelpMessages(strUsage);
69 fprintf(stdout, "%s", strUsage.c_str());
71 strUsage = HelpMessageGroup(_("Commands:"));
72 strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
73 strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
74 strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
75 strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
76 strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
77 strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
78 strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
79 strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
80 strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
81 _("This command requires JSON registers:") +
82 _("prevtxs=JSON object") + ", " +
83 _("privatekeys=JSON object") + ". " +
84 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
85 fprintf(stdout, "%s", strUsage.c_str());
87 strUsage = HelpMessageGroup(_("Register Commands:"));
88 strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
89 strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
90 fprintf(stdout, "%s", strUsage.c_str());
92 return false;
94 return true;
97 static void RegisterSetJson(const string& key, const string& rawJson)
99 UniValue val;
100 if (!val.read(rawJson)) {
101 string strErr = "Cannot parse JSON for key " + key;
102 throw runtime_error(strErr);
105 registers[key] = val;
108 static void RegisterSet(const string& strInput)
110 // separate NAME:VALUE in string
111 size_t pos = strInput.find(':');
112 if ((pos == string::npos) ||
113 (pos == 0) ||
114 (pos == (strInput.size() - 1)))
115 throw runtime_error("Register input requires NAME:VALUE");
117 string key = strInput.substr(0, pos);
118 string valStr = strInput.substr(pos + 1, string::npos);
120 RegisterSetJson(key, valStr);
123 static void RegisterLoad(const string& strInput)
125 // separate NAME:FILENAME in string
126 size_t pos = strInput.find(':');
127 if ((pos == string::npos) ||
128 (pos == 0) ||
129 (pos == (strInput.size() - 1)))
130 throw runtime_error("Register load requires NAME:FILENAME");
132 string key = strInput.substr(0, pos);
133 string filename = strInput.substr(pos + 1, string::npos);
135 FILE *f = fopen(filename.c_str(), "r");
136 if (!f) {
137 string strErr = "Cannot open file " + filename;
138 throw runtime_error(strErr);
141 // load file chunks into one big buffer
142 string valStr;
143 while ((!feof(f)) && (!ferror(f))) {
144 char buf[4096];
145 int bread = fread(buf, 1, sizeof(buf), f);
146 if (bread <= 0)
147 break;
149 valStr.insert(valStr.size(), buf, bread);
152 int error = ferror(f);
153 fclose(f);
155 if (error) {
156 string strErr = "Error reading file " + filename;
157 throw runtime_error(strErr);
160 // evaluate as JSON buffer register
161 RegisterSetJson(key, valStr);
164 static void MutateTxVersion(CMutableTransaction& tx, const string& cmdVal)
166 int64_t newVersion = atoi64(cmdVal);
167 if (newVersion < 1 || newVersion > CTransaction::CURRENT_VERSION)
168 throw runtime_error("Invalid TX version requested");
170 tx.nVersion = (int) newVersion;
173 static void MutateTxLocktime(CMutableTransaction& tx, const string& cmdVal)
175 int64_t newLocktime = atoi64(cmdVal);
176 if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
177 throw runtime_error("Invalid TX locktime requested");
179 tx.nLockTime = (unsigned int) newLocktime;
182 static void MutateTxAddInput(CMutableTransaction& tx, const string& strInput)
184 std::vector<std::string> vStrInputParts;
185 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
187 // separate TXID:VOUT in string
188 if (vStrInputParts.size()<2)
189 throw runtime_error("TX input missing separator");
191 // extract and validate TXID
192 string strTxid = vStrInputParts[0];
193 if ((strTxid.size() != 64) || !IsHex(strTxid))
194 throw runtime_error("invalid TX input txid");
195 uint256 txid(uint256S(strTxid));
197 static const unsigned int minTxOutSz = 9;
198 static const unsigned int maxVout = MAX_BLOCK_BASE_SIZE / minTxOutSz;
200 // extract and validate vout
201 string strVout = vStrInputParts[1];
202 int vout = atoi(strVout);
203 if ((vout < 0) || (vout > (int)maxVout))
204 throw runtime_error("invalid TX input vout");
206 // extract the optional sequence number
207 uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
208 if (vStrInputParts.size() > 2)
209 nSequenceIn = std::stoul(vStrInputParts[2]);
211 // append to transaction input list
212 CTxIn txin(txid, vout, CScript(), nSequenceIn);
213 tx.vin.push_back(txin);
216 static void MutateTxAddOutAddr(CMutableTransaction& tx, const string& strInput)
218 // separate VALUE:ADDRESS in string
219 size_t pos = strInput.find(':');
220 if ((pos == string::npos) ||
221 (pos == 0) ||
222 (pos == (strInput.size() - 1)))
223 throw runtime_error("TX output missing separator");
225 // extract and validate VALUE
226 string strValue = strInput.substr(0, pos);
227 CAmount value;
228 if (!ParseMoney(strValue, value))
229 throw runtime_error("invalid TX output value");
231 // extract and validate ADDRESS
232 string strAddr = strInput.substr(pos + 1, string::npos);
233 CBitcoinAddress addr(strAddr);
234 if (!addr.IsValid())
235 throw runtime_error("invalid TX output address");
237 // build standard output script via GetScriptForDestination()
238 CScript scriptPubKey = GetScriptForDestination(addr.Get());
240 // construct TxOut, append to transaction output list
241 CTxOut txout(value, scriptPubKey);
242 tx.vout.push_back(txout);
245 static void MutateTxAddOutData(CMutableTransaction& tx, const string& strInput)
247 CAmount value = 0;
249 // separate [VALUE:]DATA in string
250 size_t pos = strInput.find(':');
252 if (pos==0)
253 throw runtime_error("TX output value not specified");
255 if (pos != string::npos) {
256 // extract and validate VALUE
257 string strValue = strInput.substr(0, pos);
258 if (!ParseMoney(strValue, value))
259 throw runtime_error("invalid TX output value");
262 // extract and validate DATA
263 string strData = strInput.substr(pos + 1, string::npos);
265 if (!IsHex(strData))
266 throw runtime_error("invalid TX output data");
268 std::vector<unsigned char> data = ParseHex(strData);
270 CTxOut txout(value, CScript() << OP_RETURN << data);
271 tx.vout.push_back(txout);
274 static void MutateTxAddOutScript(CMutableTransaction& tx, const string& strInput)
276 // separate VALUE:SCRIPT in string
277 size_t pos = strInput.find(':');
278 if ((pos == string::npos) ||
279 (pos == 0))
280 throw runtime_error("TX output missing separator");
282 // extract and validate VALUE
283 string strValue = strInput.substr(0, pos);
284 CAmount value;
285 if (!ParseMoney(strValue, value))
286 throw runtime_error("invalid TX output value");
288 // extract and validate script
289 string strScript = strInput.substr(pos + 1, string::npos);
290 CScript scriptPubKey = ParseScript(strScript); // throws on err
292 // construct TxOut, append to transaction output list
293 CTxOut txout(value, scriptPubKey);
294 tx.vout.push_back(txout);
297 static void MutateTxDelInput(CMutableTransaction& tx, const string& strInIdx)
299 // parse requested deletion index
300 int inIdx = atoi(strInIdx);
301 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
302 string strErr = "Invalid TX input index '" + strInIdx + "'";
303 throw runtime_error(strErr.c_str());
306 // delete input from transaction
307 tx.vin.erase(tx.vin.begin() + inIdx);
310 static void MutateTxDelOutput(CMutableTransaction& tx, const string& strOutIdx)
312 // parse requested deletion index
313 int outIdx = atoi(strOutIdx);
314 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
315 string strErr = "Invalid TX output index '" + strOutIdx + "'";
316 throw runtime_error(strErr.c_str());
319 // delete output from transaction
320 tx.vout.erase(tx.vout.begin() + outIdx);
323 static const unsigned int N_SIGHASH_OPTS = 6;
324 static const struct {
325 const char *flagStr;
326 int flags;
327 } sighashOptions[N_SIGHASH_OPTS] = {
328 {"ALL", SIGHASH_ALL},
329 {"NONE", SIGHASH_NONE},
330 {"SINGLE", SIGHASH_SINGLE},
331 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
332 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
333 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
336 static bool findSighashFlags(int& flags, const string& flagStr)
338 flags = 0;
340 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
341 if (flagStr == sighashOptions[i].flagStr) {
342 flags = sighashOptions[i].flags;
343 return true;
347 return false;
350 uint256 ParseHashUO(map<string,UniValue>& o, string strKey)
352 if (!o.count(strKey))
353 return uint256();
354 return ParseHashUV(o[strKey], strKey);
357 vector<unsigned char> ParseHexUO(map<string,UniValue>& o, string strKey)
359 if (!o.count(strKey)) {
360 vector<unsigned char> emptyVec;
361 return emptyVec;
363 return ParseHexUV(o[strKey], strKey);
366 static CAmount AmountFromValue(const UniValue& value)
368 if (!value.isNum() && !value.isStr())
369 throw runtime_error("Amount is not a number or string");
370 CAmount amount;
371 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
372 throw runtime_error("Invalid amount");
373 if (!MoneyRange(amount))
374 throw runtime_error("Amount out of range");
375 return amount;
378 static void MutateTxSign(CMutableTransaction& tx, const string& flagStr)
380 int nHashType = SIGHASH_ALL;
382 if (flagStr.size() > 0)
383 if (!findSighashFlags(nHashType, flagStr))
384 throw runtime_error("unknown sighash flag/sign option");
386 vector<CTransaction> txVariants;
387 txVariants.push_back(tx);
389 // mergedTx will end up with all the signatures; it
390 // starts as a clone of the raw tx:
391 CMutableTransaction mergedTx(txVariants[0]);
392 bool fComplete = true;
393 CCoinsView viewDummy;
394 CCoinsViewCache view(&viewDummy);
396 if (!registers.count("privatekeys"))
397 throw runtime_error("privatekeys register variable must be set.");
398 CBasicKeyStore tempKeystore;
399 UniValue keysObj = registers["privatekeys"];
401 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
402 if (!keysObj[kidx].isStr())
403 throw runtime_error("privatekey not a string");
404 CBitcoinSecret vchSecret;
405 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
406 if (!fGood)
407 throw runtime_error("privatekey not valid");
409 CKey key = vchSecret.GetKey();
410 tempKeystore.AddKey(key);
413 // Add previous txouts given in the RPC call:
414 if (!registers.count("prevtxs"))
415 throw runtime_error("prevtxs register variable must be set.");
416 UniValue prevtxsObj = registers["prevtxs"];
418 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
419 UniValue prevOut = prevtxsObj[previdx];
420 if (!prevOut.isObject())
421 throw runtime_error("expected prevtxs internal object");
423 map<string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
424 if (!prevOut.checkObject(types))
425 throw runtime_error("prevtxs internal object typecheck fail");
427 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
429 int nOut = atoi(prevOut["vout"].getValStr());
430 if (nOut < 0)
431 throw runtime_error("vout must be positive");
433 vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
434 CScript scriptPubKey(pkData.begin(), pkData.end());
437 CCoinsModifier coins = view.ModifyCoins(txid);
438 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
439 string err("Previous output scriptPubKey mismatch:\n");
440 err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
441 ScriptToAsmStr(scriptPubKey);
442 throw runtime_error(err);
444 if ((unsigned int)nOut >= coins->vout.size())
445 coins->vout.resize(nOut+1);
446 coins->vout[nOut].scriptPubKey = scriptPubKey;
447 coins->vout[nOut].nValue = 0;
448 if (prevOut.exists("amount")) {
449 coins->vout[nOut].nValue = AmountFromValue(prevOut["amount"]);
453 // if redeemScript given and private keys given,
454 // add redeemScript to the tempKeystore so it can be signed:
455 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
456 prevOut.exists("redeemScript")) {
457 UniValue v = prevOut["redeemScript"];
458 vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
459 CScript redeemScript(rsData.begin(), rsData.end());
460 tempKeystore.AddCScript(redeemScript);
465 const CKeyStore& keystore = tempKeystore;
467 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
469 // Sign what we can:
470 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
471 CTxIn& txin = mergedTx.vin[i];
472 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
473 if (!coins || !coins->IsAvailable(txin.prevout.n)) {
474 fComplete = false;
475 continue;
477 const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
478 const CAmount& amount = coins->vout[txin.prevout.n].nValue;
480 SignatureData sigdata;
481 // Only sign SIGHASH_SINGLE if there's a corresponding output:
482 if (!fHashSingle || (i < mergedTx.vout.size()))
483 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
485 // ... and merge in other signatures:
486 BOOST_FOREACH(const CTransaction& txv, txVariants)
487 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
488 UpdateTransaction(mergedTx, i, sigdata);
490 if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx.wit.vtxinwit.size() > i ? &mergedTx.wit.vtxinwit[i].scriptWitness : NULL, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
491 fComplete = false;
494 if (fComplete) {
495 // do nothing... for now
496 // perhaps store this for later optional JSON output
499 tx = mergedTx;
502 class Secp256k1Init
504 ECCVerifyHandle globalVerifyHandle;
506 public:
507 Secp256k1Init() {
508 ECC_Start();
510 ~Secp256k1Init() {
511 ECC_Stop();
515 static void MutateTx(CMutableTransaction& tx, const string& command,
516 const string& commandVal)
518 std::unique_ptr<Secp256k1Init> ecc;
520 if (command == "nversion")
521 MutateTxVersion(tx, commandVal);
522 else if (command == "locktime")
523 MutateTxLocktime(tx, commandVal);
525 else if (command == "delin")
526 MutateTxDelInput(tx, commandVal);
527 else if (command == "in")
528 MutateTxAddInput(tx, commandVal);
530 else if (command == "delout")
531 MutateTxDelOutput(tx, commandVal);
532 else if (command == "outaddr")
533 MutateTxAddOutAddr(tx, commandVal);
534 else if (command == "outdata")
535 MutateTxAddOutData(tx, commandVal);
536 else if (command == "outscript")
537 MutateTxAddOutScript(tx, commandVal);
539 else if (command == "sign") {
540 if (!ecc) { ecc.reset(new Secp256k1Init()); }
541 MutateTxSign(tx, commandVal);
544 else if (command == "load")
545 RegisterLoad(commandVal);
547 else if (command == "set")
548 RegisterSet(commandVal);
550 else
551 throw runtime_error("unknown command");
554 static void OutputTxJSON(const CTransaction& tx)
556 UniValue entry(UniValue::VOBJ);
557 TxToUniv(tx, uint256(), entry);
559 string jsonOutput = entry.write(4);
560 fprintf(stdout, "%s\n", jsonOutput.c_str());
563 static void OutputTxHash(const CTransaction& tx)
565 string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
567 fprintf(stdout, "%s\n", strHexHash.c_str());
570 static void OutputTxHex(const CTransaction& tx)
572 string strHex = EncodeHexTx(tx);
574 fprintf(stdout, "%s\n", strHex.c_str());
577 static void OutputTx(const CTransaction& tx)
579 if (GetBoolArg("-json", false))
580 OutputTxJSON(tx);
581 else if (GetBoolArg("-txid", false))
582 OutputTxHash(tx);
583 else
584 OutputTxHex(tx);
587 static string readStdin()
589 char buf[4096];
590 string ret;
592 while (!feof(stdin)) {
593 size_t bread = fread(buf, 1, sizeof(buf), stdin);
594 ret.append(buf, bread);
595 if (bread < sizeof(buf))
596 break;
599 if (ferror(stdin))
600 throw runtime_error("error reading stdin");
602 boost::algorithm::trim_right(ret);
604 return ret;
607 static int CommandLineRawTx(int argc, char* argv[])
609 string strPrint;
610 int nRet = 0;
611 try {
612 // Skip switches; Permit common stdin convention "-"
613 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
614 (argv[1][1] != 0)) {
615 argc--;
616 argv++;
619 CTransaction txDecodeTmp;
620 int startArg;
622 if (!fCreateBlank) {
623 // require at least one param
624 if (argc < 2)
625 throw runtime_error("too few parameters");
627 // param: hex-encoded bitcoin transaction
628 string strHexTx(argv[1]);
629 if (strHexTx == "-") // "-" implies standard input
630 strHexTx = readStdin();
632 if (!DecodeHexTx(txDecodeTmp, strHexTx))
633 throw runtime_error("invalid transaction encoding");
635 startArg = 2;
636 } else
637 startArg = 1;
639 CMutableTransaction tx(txDecodeTmp);
641 for (int i = startArg; i < argc; i++) {
642 string arg = argv[i];
643 string key, value;
644 size_t eqpos = arg.find('=');
645 if (eqpos == string::npos)
646 key = arg;
647 else {
648 key = arg.substr(0, eqpos);
649 value = arg.substr(eqpos + 1);
652 MutateTx(tx, key, value);
655 OutputTx(tx);
658 catch (const boost::thread_interrupted&) {
659 throw;
661 catch (const std::exception& e) {
662 strPrint = string("error: ") + e.what();
663 nRet = EXIT_FAILURE;
665 catch (...) {
666 PrintExceptionContinue(NULL, "CommandLineRawTx()");
667 throw;
670 if (strPrint != "") {
671 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
673 return nRet;
676 int main(int argc, char* argv[])
678 SetupEnvironment();
680 try {
681 if(!AppInitRawTx(argc, argv))
682 return EXIT_FAILURE;
684 catch (const std::exception& e) {
685 PrintExceptionContinue(&e, "AppInitRawTx()");
686 return EXIT_FAILURE;
687 } catch (...) {
688 PrintExceptionContinue(NULL, "AppInitRawTx()");
689 return EXIT_FAILURE;
692 int ret = EXIT_FAILURE;
693 try {
694 ret = CommandLineRawTx(argc, argv);
696 catch (const std::exception& e) {
697 PrintExceptionContinue(&e, "CommandLineRawTx()");
698 } catch (...) {
699 PrintExceptionContinue(NULL, "CommandLineRawTx()");
701 return ret;