Update luke-jr's PGP key
[bitcoinplatinum.git] / src / bitcoin-tx.cpp
blobf9ea94b9f42d35fdba730186aac9ca9c36617c44
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_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 void MutateTxSign(CMutableTransaction& tx, const string& flagStr)
368 int nHashType = SIGHASH_ALL;
370 if (flagStr.size() > 0)
371 if (!findSighashFlags(nHashType, flagStr))
372 throw runtime_error("unknown sighash flag/sign option");
374 vector<CTransaction> txVariants;
375 txVariants.push_back(tx);
377 // mergedTx will end up with all the signatures; it
378 // starts as a clone of the raw tx:
379 CMutableTransaction mergedTx(txVariants[0]);
380 bool fComplete = true;
381 CCoinsView viewDummy;
382 CCoinsViewCache view(&viewDummy);
384 if (!registers.count("privatekeys"))
385 throw runtime_error("privatekeys register variable must be set.");
386 bool fGivenKeys = false;
387 CBasicKeyStore tempKeystore;
388 UniValue keysObj = registers["privatekeys"];
389 fGivenKeys = true;
391 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
392 if (!keysObj[kidx].isStr())
393 throw runtime_error("privatekey not a string");
394 CBitcoinSecret vchSecret;
395 bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
396 if (!fGood)
397 throw runtime_error("privatekey not valid");
399 CKey key = vchSecret.GetKey();
400 tempKeystore.AddKey(key);
403 // Add previous txouts given in the RPC call:
404 if (!registers.count("prevtxs"))
405 throw runtime_error("prevtxs register variable must be set.");
406 UniValue prevtxsObj = registers["prevtxs"];
408 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
409 UniValue prevOut = prevtxsObj[previdx];
410 if (!prevOut.isObject())
411 throw runtime_error("expected prevtxs internal object");
413 map<string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
414 if (!prevOut.checkObject(types))
415 throw runtime_error("prevtxs internal object typecheck fail");
417 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
419 int nOut = atoi(prevOut["vout"].getValStr());
420 if (nOut < 0)
421 throw runtime_error("vout must be positive");
423 vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
424 CScript scriptPubKey(pkData.begin(), pkData.end());
427 CCoinsModifier coins = view.ModifyCoins(txid);
428 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
429 string err("Previous output scriptPubKey mismatch:\n");
430 err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
431 ScriptToAsmStr(scriptPubKey);
432 throw runtime_error(err);
434 if ((unsigned int)nOut >= coins->vout.size())
435 coins->vout.resize(nOut+1);
436 coins->vout[nOut].scriptPubKey = scriptPubKey;
437 coins->vout[nOut].nValue = 0; // we don't know the actual output value
440 // if redeemScript given and private keys given,
441 // add redeemScript to the tempKeystore so it can be signed:
442 if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
443 prevOut.exists("redeemScript")) {
444 UniValue v = prevOut["redeemScript"];
445 vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
446 CScript redeemScript(rsData.begin(), rsData.end());
447 tempKeystore.AddCScript(redeemScript);
452 const CKeyStore& keystore = tempKeystore;
454 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
456 // Sign what we can:
457 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
458 CTxIn& txin = mergedTx.vin[i];
459 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
460 if (!coins || !coins->IsAvailable(txin.prevout.n)) {
461 fComplete = false;
462 continue;
464 const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
466 txin.scriptSig.clear();
467 // Only sign SIGHASH_SINGLE if there's a corresponding output:
468 if (!fHashSingle || (i < mergedTx.vout.size()))
469 SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
471 // ... and merge in other signatures:
472 BOOST_FOREACH(const CTransaction& txv, txVariants) {
473 txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
475 if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i)))
476 fComplete = false;
479 if (fComplete) {
480 // do nothing... for now
481 // perhaps store this for later optional JSON output
484 tx = mergedTx;
487 class Secp256k1Init
489 ECCVerifyHandle globalVerifyHandle;
491 public:
492 Secp256k1Init() {
493 ECC_Start();
495 ~Secp256k1Init() {
496 ECC_Stop();
500 static void MutateTx(CMutableTransaction& tx, const string& command,
501 const string& commandVal)
503 boost::scoped_ptr<Secp256k1Init> ecc;
505 if (command == "nversion")
506 MutateTxVersion(tx, commandVal);
507 else if (command == "locktime")
508 MutateTxLocktime(tx, commandVal);
510 else if (command == "delin")
511 MutateTxDelInput(tx, commandVal);
512 else if (command == "in")
513 MutateTxAddInput(tx, commandVal);
515 else if (command == "delout")
516 MutateTxDelOutput(tx, commandVal);
517 else if (command == "outaddr")
518 MutateTxAddOutAddr(tx, commandVal);
519 else if (command == "outdata")
520 MutateTxAddOutData(tx, commandVal);
521 else if (command == "outscript")
522 MutateTxAddOutScript(tx, commandVal);
524 else if (command == "sign") {
525 if (!ecc) { ecc.reset(new Secp256k1Init()); }
526 MutateTxSign(tx, commandVal);
529 else if (command == "load")
530 RegisterLoad(commandVal);
532 else if (command == "set")
533 RegisterSet(commandVal);
535 else
536 throw runtime_error("unknown command");
539 static void OutputTxJSON(const CTransaction& tx)
541 UniValue entry(UniValue::VOBJ);
542 TxToUniv(tx, uint256(), entry);
544 string jsonOutput = entry.write(4);
545 fprintf(stdout, "%s\n", jsonOutput.c_str());
548 static void OutputTxHash(const CTransaction& tx)
550 string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
552 fprintf(stdout, "%s\n", strHexHash.c_str());
555 static void OutputTxHex(const CTransaction& tx)
557 string strHex = EncodeHexTx(tx);
559 fprintf(stdout, "%s\n", strHex.c_str());
562 static void OutputTx(const CTransaction& tx)
564 if (GetBoolArg("-json", false))
565 OutputTxJSON(tx);
566 else if (GetBoolArg("-txid", false))
567 OutputTxHash(tx);
568 else
569 OutputTxHex(tx);
572 static string readStdin()
574 char buf[4096];
575 string ret;
577 while (!feof(stdin)) {
578 size_t bread = fread(buf, 1, sizeof(buf), stdin);
579 ret.append(buf, bread);
580 if (bread < sizeof(buf))
581 break;
584 if (ferror(stdin))
585 throw runtime_error("error reading stdin");
587 boost::algorithm::trim_right(ret);
589 return ret;
592 static int CommandLineRawTx(int argc, char* argv[])
594 string strPrint;
595 int nRet = 0;
596 try {
597 // Skip switches; Permit common stdin convention "-"
598 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
599 (argv[1][1] != 0)) {
600 argc--;
601 argv++;
604 CTransaction txDecodeTmp;
605 int startArg;
607 if (!fCreateBlank) {
608 // require at least one param
609 if (argc < 2)
610 throw runtime_error("too few parameters");
612 // param: hex-encoded bitcoin transaction
613 string strHexTx(argv[1]);
614 if (strHexTx == "-") // "-" implies standard input
615 strHexTx = readStdin();
617 if (!DecodeHexTx(txDecodeTmp, strHexTx))
618 throw runtime_error("invalid transaction encoding");
620 startArg = 2;
621 } else
622 startArg = 1;
624 CMutableTransaction tx(txDecodeTmp);
626 for (int i = startArg; i < argc; i++) {
627 string arg = argv[i];
628 string key, value;
629 size_t eqpos = arg.find('=');
630 if (eqpos == string::npos)
631 key = arg;
632 else {
633 key = arg.substr(0, eqpos);
634 value = arg.substr(eqpos + 1);
637 MutateTx(tx, key, value);
640 OutputTx(tx);
643 catch (const boost::thread_interrupted&) {
644 throw;
646 catch (const std::exception& e) {
647 strPrint = string("error: ") + e.what();
648 nRet = EXIT_FAILURE;
650 catch (...) {
651 PrintExceptionContinue(NULL, "CommandLineRawTx()");
652 throw;
655 if (strPrint != "") {
656 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
658 return nRet;
661 int main(int argc, char* argv[])
663 SetupEnvironment();
665 try {
666 if(!AppInitRawTx(argc, argv))
667 return EXIT_FAILURE;
669 catch (const std::exception& e) {
670 PrintExceptionContinue(&e, "AppInitRawTx()");
671 return EXIT_FAILURE;
672 } catch (...) {
673 PrintExceptionContinue(NULL, "AppInitRawTx()");
674 return EXIT_FAILURE;
677 int ret = EXIT_FAILURE;
678 try {
679 ret = CommandLineRawTx(argc, argv);
681 catch (const std::exception& e) {
682 PrintExceptionContinue(&e, "CommandLineRawTx()");
683 } catch (...) {
684 PrintExceptionContinue(NULL, "CommandLineRawTx()");
686 return ret;