1 // Copyright (c) 2009-2014 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 #include "clientversion.h"
7 #include "consensus/consensus.h"
8 #include "consensus/upgrades.h"
12 #include "primitives/transaction.h"
13 #include "script/script.h"
14 #include "script/sign.h"
17 #include "utilmoneystr.h"
18 #include "utilstrencodings.h"
22 #include <boost/algorithm/string.hpp>
23 #include <boost/assign/list_of.hpp>
28 #include "arith_uint256.h"
29 #include "komodo_structs.h"
30 #include "komodo_globals.h"
31 #include "komodo_defs.h"
33 #include "komodo_interest.h"
35 struct CCcontract_info *CCinit(struct CCcontract_info *cp, uint8_t evalcode)
40 uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight)
45 bool IsBlockBoundTransaction(const CTransaction &tx)
50 static bool fCreateBlank;
51 static std::map<std::string,UniValue> registers;
52 static const int CONTINUE_EXECUTION=-1;
53 boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
56 // This function returns either one of EXIT_ codes when it's expected to stop the process or
57 // CONTINUE_EXECUTION when it's expected to continue further.
59 static int AppInitRawTx(int argc, char* argv[])
64 ParseParameters(argc, argv);
66 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
67 if (!SelectParamsFromCommandLine()) {
68 fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
72 fCreateBlank = GetBoolArg("-create", false);
74 if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
76 // First part of help message is specific to this utility
77 std::string strUsage = _("Zcash zcash-tx utility version") + " " + FormatFullVersion() + "\n\n" +
79 " zcash-tx [options] <hex-tx> [commands] " + _("Update hex-encoded zcash transaction") + "\n" +
80 " zcash-tx [options] -create [commands] " + _("Create hex-encoded zcash transaction") + "\n" +
83 fprintf(stdout, "%s", strUsage.c_str());
85 strUsage = HelpMessageGroup(_("Options:"));
86 strUsage += HelpMessageOpt("-?", _("This help message"));
87 strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
88 strUsage += HelpMessageOpt("-json", _("Select JSON output"));
89 strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
90 strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly."));
91 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
93 fprintf(stdout, "%s", strUsage.c_str());
95 strUsage = HelpMessageGroup(_("Commands:"));
96 strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
97 strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
98 strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
99 strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
100 strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
101 strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
102 strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
103 strUsage += HelpMessageOpt("sign=HEIGHT:SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
104 _("This command requires JSON registers:") +
105 _("prevtxs=JSON object") + ", " +
106 _("privatekeys=JSON object") + ". " +
107 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
108 fprintf(stdout, "%s", strUsage.c_str());
110 strUsage = HelpMessageGroup(_("Register Commands:"));
111 strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
112 strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
113 fprintf(stdout, "%s", strUsage.c_str());
116 fprintf(stderr, "Error: too few parameters\n");
121 return CONTINUE_EXECUTION;
124 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
127 if (!val.read(rawJson)) {
128 std::string strErr = "Cannot parse JSON for key " + key;
129 throw std::runtime_error(strErr);
132 registers[key] = val;
135 static void RegisterSet(const std::string& strInput)
137 // separate NAME:VALUE in string
138 size_t pos = strInput.find(':');
139 if ((pos == std::string::npos) ||
141 (pos == (strInput.size() - 1)))
142 throw std::runtime_error("Register input requires NAME:VALUE");
144 std::string key = strInput.substr(0, pos);
145 std::string valStr = strInput.substr(pos + 1, std::string::npos);
147 RegisterSetJson(key, valStr);
150 static void RegisterLoad(const std::string& strInput)
152 // separate NAME:FILENAME in string
153 size_t pos = strInput.find(':');
154 if ((pos == std::string::npos) ||
156 (pos == (strInput.size() - 1)))
157 throw std::runtime_error("Register load requires NAME:FILENAME");
159 std::string key = strInput.substr(0, pos);
160 std::string filename = strInput.substr(pos + 1, std::string::npos);
162 FILE *f = fopen(filename.c_str(), "r");
164 std::string strErr = "Cannot open file " + filename;
165 throw std::runtime_error(strErr);
168 // load file chunks into one big buffer
170 while ((!feof(f)) && (!ferror(f))) {
172 int bread = fread(buf, 1, sizeof(buf), f);
176 valStr.insert(valStr.size(), buf, bread);
179 int error = ferror(f);
183 std::string strErr = "Error reading file " + filename;
184 throw std::runtime_error(strErr);
187 // evaluate as JSON buffer register
188 RegisterSetJson(key, valStr);
191 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
193 int64_t newVersion = atoi64(cmdVal);
194 if (newVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION || newVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION)
195 throw std::runtime_error("Invalid TX version requested");
197 tx.nVersion = (int) newVersion;
200 static void MutateTxExpiry(CMutableTransaction& tx, const std::string& cmdVal)
202 int64_t newExpiry = atoi64(cmdVal);
203 if (newExpiry >= TX_EXPIRY_HEIGHT_THRESHOLD) {
204 throw std::runtime_error("Invalid TX expiry requested");
206 tx.nExpiryHeight = (int) newExpiry;
209 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
211 int64_t newLocktime = atoi64(cmdVal);
212 if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
213 throw std::runtime_error("Invalid TX locktime requested");
215 tx.nLockTime = (unsigned int) newLocktime;
218 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
220 std::vector<std::string> vStrInputParts;
221 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
223 // separate TXID:VOUT in string
224 if (vStrInputParts.size()<2)
225 throw std::runtime_error("TX input missing separator");
227 // extract and validate TXID
228 std::string strTxid = vStrInputParts[0];
229 if ((strTxid.size() != 64) || !IsHex(strTxid))
230 throw std::runtime_error("invalid TX input txid");
231 uint256 txid(uint256S(strTxid));
233 static const unsigned int minTxOutSz = 9;
234 static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz;
236 // extract and validate vout
237 std::string strVout = vStrInputParts[1];
238 int vout = atoi(strVout);
239 if ((vout < 0) || (vout > (int)maxVout))
240 throw std::runtime_error("invalid TX input vout");
242 // extract the optional sequence number
243 uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
244 if (vStrInputParts.size() > 2)
245 nSequenceIn = atoi(vStrInputParts[2]);
247 // append to transaction input list
248 CTxIn txin(txid, vout, CScript(), nSequenceIn);
249 tx.vin.push_back(txin);
252 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
254 // separate VALUE:ADDRESS in string
255 size_t pos = strInput.find(':');
256 if ((pos == std::string::npos) ||
258 (pos == (strInput.size() - 1)))
259 throw std::runtime_error("TX output missing separator");
261 // extract and validate VALUE
262 std::string strValue = strInput.substr(0, pos);
264 if (!ParseMoney(strValue, value))
265 throw std::runtime_error("invalid TX output value");
267 // extract and validate ADDRESS
268 std::string strAddr = strInput.substr(pos + 1, std::string::npos);
269 CTxDestination destination = DecodeDestination(strAddr);
270 if (!IsValidDestination(destination)) {
271 throw std::runtime_error("invalid TX output address");
273 CScript scriptPubKey = GetScriptForDestination(destination);
275 // construct TxOut, append to transaction output list
276 CTxOut txout(value, scriptPubKey);
277 tx.vout.push_back(txout);
280 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
282 // separate VALUE:SCRIPT in string
283 size_t pos = strInput.find(':');
284 if ((pos == std::string::npos) ||
286 throw std::runtime_error("TX output missing separator");
288 // extract and validate VALUE
289 std::string strValue = strInput.substr(0, pos);
291 if (!ParseMoney(strValue, value))
292 throw std::runtime_error("invalid TX output value");
294 // extract and validate script
295 std::string strScript = strInput.substr(pos + 1, std::string::npos);
296 CScript scriptPubKey = ParseScript(strScript); // throws on err
298 // construct TxOut, append to transaction output list
299 CTxOut txout(value, scriptPubKey);
300 tx.vout.push_back(txout);
303 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
305 // parse requested deletion index
306 int inIdx = atoi(strInIdx);
307 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
308 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
309 throw std::runtime_error(strErr.c_str());
312 // delete input from transaction
313 tx.vin.erase(tx.vin.begin() + inIdx);
316 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
318 // parse requested deletion index
319 int outIdx = atoi(strOutIdx);
320 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
321 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
322 throw std::runtime_error(strErr.c_str());
325 // delete output from transaction
326 tx.vout.erase(tx.vout.begin() + outIdx);
329 static const unsigned int N_SIGHASH_OPTS = 6;
330 static const struct {
333 } sighashOptions[N_SIGHASH_OPTS] = {
334 {"ALL", SIGHASH_ALL},
335 {"NONE", SIGHASH_NONE},
336 {"SINGLE", SIGHASH_SINGLE},
337 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
338 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
339 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
342 static bool findSighashFlags(int& flags, const std::string& flagStr)
346 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
347 if (flagStr == sighashOptions[i].flagStr) {
348 flags = sighashOptions[i].flags;
356 uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
358 if (!o.count(strKey))
360 return ParseHashUV(o[strKey], strKey);
363 std::vector<unsigned char> ParseHexUO(std::map<std::string,UniValue>& o, std::string strKey)
365 if (!o.count(strKey)) {
366 std::vector<unsigned char> emptyVec;
369 return ParseHexUV(o[strKey], strKey);
372 static CAmount AmountFromValue(const UniValue& value)
374 if (!value.isNum() && !value.isStr())
375 throw std::runtime_error("Amount is not a number or string");
377 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
378 throw std::runtime_error("Invalid amount");
379 if (!MoneyRange(amount))
380 throw std::runtime_error("Amount out of range");
384 static void MutateTxSign(CMutableTransaction& tx, const std::string& strInput)
386 // separate HEIGHT:SIGHASH-FLAGS in string
387 size_t pos = strInput.find(':');
389 (pos == (strInput.size() - 1)))
390 throw std::runtime_error("Invalid sighash flag separator");
392 // extract and validate HEIGHT
393 std::string strHeight = strInput.substr(0, pos);
394 int nHeight = atoi(strHeight);
396 throw std::runtime_error("invalid height");
399 // extract and validate SIGHASH-FLAGS
400 int nHashType = SIGHASH_ALL;
402 if (pos != std::string::npos) {
403 flagStr = strInput.substr(pos + 1, std::string::npos);
405 if (flagStr.size() > 0)
406 if (!findSighashFlags(nHashType, flagStr))
407 throw std::runtime_error("unknown sighash flag/sign option");
409 std::vector<CTransaction> txVariants;
410 txVariants.push_back(tx);
412 // mergedTx will end up with all the signatures; it
413 // starts as a clone of the raw tx:
414 CMutableTransaction mergedTx(txVariants[0]);
415 bool fComplete = true;
416 CCoinsView viewDummy;
417 CCoinsViewCache view(&viewDummy);
419 if (!registers.count("privatekeys"))
420 throw std::runtime_error("privatekeys register variable must be set.");
421 bool fGivenKeys = false;
422 CBasicKeyStore tempKeystore;
423 UniValue keysObj = registers["privatekeys"];
426 for (size_t kidx = 0; kidx < keysObj.size(); kidx++) {
427 if (!keysObj[kidx].isStr())
428 throw std::runtime_error("privatekey not a std::string");
429 CKey key = DecodeSecret(keysObj[kidx].getValStr());
430 if (!key.IsValid()) {
431 throw std::runtime_error("privatekey not valid");
433 tempKeystore.AddKey(key);
436 // Add previous txouts given in the RPC call:
437 if (!registers.count("prevtxs"))
438 throw std::runtime_error("prevtxs register variable must be set.");
439 UniValue prevtxsObj = registers["prevtxs"];
441 for (size_t previdx = 0; previdx < prevtxsObj.size(); previdx++) {
442 UniValue prevOut = prevtxsObj[previdx];
443 if (!prevOut.isObject())
444 throw std::runtime_error("expected prevtxs internal object");
446 std::map<std::string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
447 if (!prevOut.checkObject(types))
448 throw std::runtime_error("prevtxs internal object typecheck fail");
450 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
452 int nOut = atoi(prevOut["vout"].getValStr());
454 throw std::runtime_error("vout must be positive");
456 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
457 CScript scriptPubKey(pkData.begin(), pkData.end());
460 CCoinsModifier coins = view.ModifyCoins(txid);
461 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
462 std::string err("Previous output scriptPubKey mismatch:\n");
463 err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
464 ScriptToAsmStr(scriptPubKey);
465 throw std::runtime_error(err);
467 if ((unsigned int)nOut >= coins->vout.size())
468 coins->vout.resize(nOut+1);
469 coins->vout[nOut].scriptPubKey = scriptPubKey;
470 coins->vout[nOut].nValue = 0;
471 if (prevOut.exists("amount")) {
472 coins->vout[nOut].nValue = AmountFromValue(prevOut["amount"]);
476 // if redeemScript given and private keys given,
477 // add redeemScript to the tempKeystore so it can be signed:
478 if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
479 prevOut.exists("redeemScript")) {
480 UniValue v = prevOut["redeemScript"];
481 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
482 CScript redeemScript(rsData.begin(), rsData.end());
483 tempKeystore.AddCScript(redeemScript);
488 const CKeyStore& keystore = tempKeystore;
490 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
492 // Grab the consensus branch ID for the given height
493 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
496 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
497 CTxIn& txin = mergedTx.vin[i];
498 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
499 if (!coins || !coins->IsAvailable(txin.prevout.n)) {
503 const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
504 const CAmount& amount = coins->vout[txin.prevout.n].nValue;
506 SignatureData sigdata;
507 // Only sign SIGHASH_SINGLE if there's a corresponding output:
508 if (!fHashSingle || (i < mergedTx.vout.size()))
509 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata, consensusBranchId);
511 // ... and merge in other signatures:
512 BOOST_FOREACH(const CTransaction& txv, txVariants)
513 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i), consensusBranchId);
514 UpdateTransaction(mergedTx, i, sigdata);
516 if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount), consensusBranchId))
521 // do nothing... for now
522 // perhaps store this for later optional JSON output
530 ECCVerifyHandle globalVerifyHandle;
541 static void MutateTx(CMutableTransaction& tx, const std::string& command,
542 const std::string& commandVal)
544 boost::scoped_ptr<Secp256k1Init> ecc;
546 if (command == "nversion")
547 MutateTxVersion(tx, commandVal);
548 else if (command == "locktime")
549 MutateTxLocktime(tx, commandVal);
550 else if (command == "expiry")
551 MutateTxExpiry(tx, commandVal);
553 else if (command == "delin")
554 MutateTxDelInput(tx, commandVal);
555 else if (command == "in")
556 MutateTxAddInput(tx, commandVal);
558 else if (command == "delout")
559 MutateTxDelOutput(tx, commandVal);
560 else if (command == "outaddr")
561 MutateTxAddOutAddr(tx, commandVal);
562 else if (command == "outscript")
563 MutateTxAddOutScript(tx, commandVal);
565 else if (command == "sign") {
566 if (!ecc) { ecc.reset(new Secp256k1Init()); }
567 MutateTxSign(tx, commandVal);
570 else if (command == "load")
571 RegisterLoad(commandVal);
573 else if (command == "set")
574 RegisterSet(commandVal);
577 throw std::runtime_error("unknown command");
580 static void OutputTxJSON(const CTransaction& tx)
582 UniValue entry(UniValue::VOBJ);
583 TxToUniv(tx, uint256(), entry);
585 std::string jsonOutput = entry.write(4);
586 fprintf(stdout, "%s\n", jsonOutput.c_str());
589 static void OutputTxHash(const CTransaction& tx)
591 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
593 fprintf(stdout, "%s\n", strHexHash.c_str());
596 static void OutputTxHex(const CTransaction& tx)
598 std::string strHex = EncodeHexTx(tx);
600 fprintf(stdout, "%s\n", strHex.c_str());
603 static void OutputTx(const CTransaction& tx)
605 if (GetBoolArg("-json", false))
607 else if (GetBoolArg("-txid", false))
613 static std::string readStdin()
618 while (!feof(stdin)) {
619 size_t bread = fread(buf, 1, sizeof(buf), stdin);
620 ret.append(buf, bread);
621 if (bread < sizeof(buf))
626 throw std::runtime_error("error reading stdin");
628 boost::algorithm::trim_right(ret);
633 static int CommandLineRawTx(int argc, char* argv[])
635 std::string strPrint;
638 // Skip switches; Permit common stdin convention "-"
639 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
645 CTransaction txDecodeTmp;
649 // require at least one param
651 throw std::runtime_error("too few parameters");
653 // param: hex-encoded bitcoin transaction
654 std::string strHexTx(argv[1]);
655 if (strHexTx == "-") // "-" implies standard input
656 strHexTx = readStdin();
658 if (!DecodeHexTx(txDecodeTmp, strHexTx))
659 throw std::runtime_error("invalid transaction encoding");
665 CMutableTransaction tx(txDecodeTmp);
667 for (int i = startArg; i < argc; i++) {
668 std::string arg = argv[i];
669 std::string key, value;
670 size_t eqpos = arg.find('=');
671 if (eqpos == std::string::npos)
674 key = arg.substr(0, eqpos);
675 value = arg.substr(eqpos + 1);
678 MutateTx(tx, key, value);
684 catch (const boost::thread_interrupted&) {
687 catch (const std::exception& e) {
688 strPrint = std::string("error: ") + e.what();
692 PrintExceptionContinue(NULL, "CommandLineRawTx()");
696 if (strPrint != "") {
697 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
702 int main(int argc, char* argv[])
707 int ret = AppInitRawTx(argc, argv);
708 if (ret != CONTINUE_EXECUTION)
711 catch (const std::exception& e) {
712 PrintExceptionContinue(&e, "AppInitRawTx()");
715 PrintExceptionContinue(NULL, "AppInitRawTx()");
719 int ret = EXIT_FAILURE;
721 ret = CommandLineRawTx(argc, argv);
723 catch (const std::exception& e) {
724 PrintExceptionContinue(&e, "CommandLineRawTx()");
726 PrintExceptionContinue(NULL, "CommandLineRawTx()");