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 static bool fCreateBlank;
46 static std::map<std::string,UniValue> registers;
47 static const int CONTINUE_EXECUTION=-1;
48 boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
51 // This function returns either one of EXIT_ codes when it's expected to stop the process or
52 // CONTINUE_EXECUTION when it's expected to continue further.
54 static int AppInitRawTx(int argc, char* argv[])
59 ParseParameters(argc, argv);
61 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
62 if (!SelectParamsFromCommandLine()) {
63 fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
67 fCreateBlank = GetBoolArg("-create", false);
69 if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
71 // First part of help message is specific to this utility
72 std::string strUsage = _("Zcash zcash-tx utility version") + " " + FormatFullVersion() + "\n\n" +
74 " zcash-tx [options] <hex-tx> [commands] " + _("Update hex-encoded zcash transaction") + "\n" +
75 " zcash-tx [options] -create [commands] " + _("Create hex-encoded zcash transaction") + "\n" +
78 fprintf(stdout, "%s", strUsage.c_str());
80 strUsage = HelpMessageGroup(_("Options:"));
81 strUsage += HelpMessageOpt("-?", _("This help message"));
82 strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
83 strUsage += HelpMessageOpt("-json", _("Select JSON output"));
84 strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
85 strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly."));
86 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
88 fprintf(stdout, "%s", strUsage.c_str());
90 strUsage = HelpMessageGroup(_("Commands:"));
91 strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
92 strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
93 strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
94 strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
95 strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
96 strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
97 strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
98 strUsage += HelpMessageOpt("sign=HEIGHT:SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
99 _("This command requires JSON registers:") +
100 _("prevtxs=JSON object") + ", " +
101 _("privatekeys=JSON object") + ". " +
102 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
103 fprintf(stdout, "%s", strUsage.c_str());
105 strUsage = HelpMessageGroup(_("Register Commands:"));
106 strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
107 strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
108 fprintf(stdout, "%s", strUsage.c_str());
111 fprintf(stderr, "Error: too few parameters\n");
116 return CONTINUE_EXECUTION;
119 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
122 if (!val.read(rawJson)) {
123 std::string strErr = "Cannot parse JSON for key " + key;
124 throw std::runtime_error(strErr);
127 registers[key] = val;
130 static void RegisterSet(const std::string& strInput)
132 // separate NAME:VALUE in string
133 size_t pos = strInput.find(':');
134 if ((pos == std::string::npos) ||
136 (pos == (strInput.size() - 1)))
137 throw std::runtime_error("Register input requires NAME:VALUE");
139 std::string key = strInput.substr(0, pos);
140 std::string valStr = strInput.substr(pos + 1, std::string::npos);
142 RegisterSetJson(key, valStr);
145 static void RegisterLoad(const std::string& strInput)
147 // separate NAME:FILENAME in string
148 size_t pos = strInput.find(':');
149 if ((pos == std::string::npos) ||
151 (pos == (strInput.size() - 1)))
152 throw std::runtime_error("Register load requires NAME:FILENAME");
154 std::string key = strInput.substr(0, pos);
155 std::string filename = strInput.substr(pos + 1, std::string::npos);
157 FILE *f = fopen(filename.c_str(), "r");
159 std::string strErr = "Cannot open file " + filename;
160 throw std::runtime_error(strErr);
163 // load file chunks into one big buffer
165 while ((!feof(f)) && (!ferror(f))) {
167 int bread = fread(buf, 1, sizeof(buf), f);
171 valStr.insert(valStr.size(), buf, bread);
174 int error = ferror(f);
178 std::string strErr = "Error reading file " + filename;
179 throw std::runtime_error(strErr);
182 // evaluate as JSON buffer register
183 RegisterSetJson(key, valStr);
186 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
188 int64_t newVersion = atoi64(cmdVal);
189 if (newVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION || newVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION)
190 throw std::runtime_error("Invalid TX version requested");
192 tx.nVersion = (int) newVersion;
195 static void MutateTxExpiry(CMutableTransaction& tx, const std::string& cmdVal)
197 int64_t newExpiry = atoi64(cmdVal);
198 if (newExpiry >= TX_EXPIRY_HEIGHT_THRESHOLD) {
199 throw std::runtime_error("Invalid TX expiry requested");
201 tx.nExpiryHeight = (int) newExpiry;
204 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
206 int64_t newLocktime = atoi64(cmdVal);
207 if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
208 throw std::runtime_error("Invalid TX locktime requested");
210 tx.nLockTime = (unsigned int) newLocktime;
213 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
215 std::vector<std::string> vStrInputParts;
216 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
218 // separate TXID:VOUT in string
219 if (vStrInputParts.size()<2)
220 throw std::runtime_error("TX input missing separator");
222 // extract and validate TXID
223 std::string strTxid = vStrInputParts[0];
224 if ((strTxid.size() != 64) || !IsHex(strTxid))
225 throw std::runtime_error("invalid TX input txid");
226 uint256 txid(uint256S(strTxid));
228 static const unsigned int minTxOutSz = 9;
229 static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz;
231 // extract and validate vout
232 std::string strVout = vStrInputParts[1];
233 int vout = atoi(strVout);
234 if ((vout < 0) || (vout > (int)maxVout))
235 throw std::runtime_error("invalid TX input vout");
237 // extract the optional sequence number
238 uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
239 if (vStrInputParts.size() > 2)
240 nSequenceIn = atoi(vStrInputParts[2]);
242 // append to transaction input list
243 CTxIn txin(txid, vout, CScript(), nSequenceIn);
244 tx.vin.push_back(txin);
247 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
249 // separate VALUE:ADDRESS in string
250 size_t pos = strInput.find(':');
251 if ((pos == std::string::npos) ||
253 (pos == (strInput.size() - 1)))
254 throw std::runtime_error("TX output missing separator");
256 // extract and validate VALUE
257 std::string strValue = strInput.substr(0, pos);
259 if (!ParseMoney(strValue, value))
260 throw std::runtime_error("invalid TX output value");
262 // extract and validate ADDRESS
263 std::string strAddr = strInput.substr(pos + 1, std::string::npos);
264 CTxDestination destination = DecodeDestination(strAddr);
265 if (!IsValidDestination(destination)) {
266 throw std::runtime_error("invalid TX output address");
268 CScript scriptPubKey = GetScriptForDestination(destination);
270 // construct TxOut, append to transaction output list
271 CTxOut txout(value, scriptPubKey);
272 tx.vout.push_back(txout);
275 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
277 // separate VALUE:SCRIPT in string
278 size_t pos = strInput.find(':');
279 if ((pos == std::string::npos) ||
281 throw std::runtime_error("TX output missing separator");
283 // extract and validate VALUE
284 std::string strValue = strInput.substr(0, pos);
286 if (!ParseMoney(strValue, value))
287 throw std::runtime_error("invalid TX output value");
289 // extract and validate script
290 std::string strScript = strInput.substr(pos + 1, std::string::npos);
291 CScript scriptPubKey = ParseScript(strScript); // throws on err
293 // construct TxOut, append to transaction output list
294 CTxOut txout(value, scriptPubKey);
295 tx.vout.push_back(txout);
298 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
300 // parse requested deletion index
301 int inIdx = atoi(strInIdx);
302 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
303 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
304 throw std::runtime_error(strErr.c_str());
307 // delete input from transaction
308 tx.vin.erase(tx.vin.begin() + inIdx);
311 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
313 // parse requested deletion index
314 int outIdx = atoi(strOutIdx);
315 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
316 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
317 throw std::runtime_error(strErr.c_str());
320 // delete output from transaction
321 tx.vout.erase(tx.vout.begin() + outIdx);
324 static const unsigned int N_SIGHASH_OPTS = 6;
325 static const struct {
328 } sighashOptions[N_SIGHASH_OPTS] = {
329 {"ALL", SIGHASH_ALL},
330 {"NONE", SIGHASH_NONE},
331 {"SINGLE", SIGHASH_SINGLE},
332 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
333 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
334 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
337 static bool findSighashFlags(int& flags, const std::string& flagStr)
341 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
342 if (flagStr == sighashOptions[i].flagStr) {
343 flags = sighashOptions[i].flags;
351 uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
353 if (!o.count(strKey))
355 return ParseHashUV(o[strKey], strKey);
358 std::vector<unsigned char> ParseHexUO(std::map<std::string,UniValue>& o, std::string strKey)
360 if (!o.count(strKey)) {
361 std::vector<unsigned char> emptyVec;
364 return ParseHexUV(o[strKey], strKey);
367 static CAmount AmountFromValue(const UniValue& value)
369 if (!value.isNum() && !value.isStr())
370 throw std::runtime_error("Amount is not a number or string");
372 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
373 throw std::runtime_error("Invalid amount");
374 if (!MoneyRange(amount))
375 throw std::runtime_error("Amount out of range");
379 static void MutateTxSign(CMutableTransaction& tx, const std::string& strInput)
381 // separate HEIGHT:SIGHASH-FLAGS in string
382 size_t pos = strInput.find(':');
384 (pos == (strInput.size() - 1)))
385 throw std::runtime_error("Invalid sighash flag separator");
387 // extract and validate HEIGHT
388 std::string strHeight = strInput.substr(0, pos);
389 int nHeight = atoi(strHeight);
391 throw std::runtime_error("invalid height");
394 // extract and validate SIGHASH-FLAGS
395 int nHashType = SIGHASH_ALL;
397 if (pos != std::string::npos) {
398 flagStr = strInput.substr(pos + 1, std::string::npos);
400 if (flagStr.size() > 0)
401 if (!findSighashFlags(nHashType, flagStr))
402 throw std::runtime_error("unknown sighash flag/sign option");
404 std::vector<CTransaction> txVariants;
405 txVariants.push_back(tx);
407 // mergedTx will end up with all the signatures; it
408 // starts as a clone of the raw tx:
409 CMutableTransaction mergedTx(txVariants[0]);
410 bool fComplete = true;
411 CCoinsView viewDummy;
412 CCoinsViewCache view(&viewDummy);
414 if (!registers.count("privatekeys"))
415 throw std::runtime_error("privatekeys register variable must be set.");
416 bool fGivenKeys = false;
417 CBasicKeyStore tempKeystore;
418 UniValue keysObj = registers["privatekeys"];
421 for (size_t kidx = 0; kidx < keysObj.size(); kidx++) {
422 if (!keysObj[kidx].isStr())
423 throw std::runtime_error("privatekey not a std::string");
424 CKey key = DecodeSecret(keysObj[kidx].getValStr());
425 if (!key.IsValid()) {
426 throw std::runtime_error("privatekey not valid");
428 tempKeystore.AddKey(key);
431 // Add previous txouts given in the RPC call:
432 if (!registers.count("prevtxs"))
433 throw std::runtime_error("prevtxs register variable must be set.");
434 UniValue prevtxsObj = registers["prevtxs"];
436 for (size_t previdx = 0; previdx < prevtxsObj.size(); previdx++) {
437 UniValue prevOut = prevtxsObj[previdx];
438 if (!prevOut.isObject())
439 throw std::runtime_error("expected prevtxs internal object");
441 std::map<std::string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
442 if (!prevOut.checkObject(types))
443 throw std::runtime_error("prevtxs internal object typecheck fail");
445 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
447 int nOut = atoi(prevOut["vout"].getValStr());
449 throw std::runtime_error("vout must be positive");
451 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
452 CScript scriptPubKey(pkData.begin(), pkData.end());
455 CCoinsModifier coins = view.ModifyCoins(txid);
456 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
457 std::string err("Previous output scriptPubKey mismatch:\n");
458 err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
459 ScriptToAsmStr(scriptPubKey);
460 throw std::runtime_error(err);
462 if ((unsigned int)nOut >= coins->vout.size())
463 coins->vout.resize(nOut+1);
464 coins->vout[nOut].scriptPubKey = scriptPubKey;
465 coins->vout[nOut].nValue = 0;
466 if (prevOut.exists("amount")) {
467 coins->vout[nOut].nValue = AmountFromValue(prevOut["amount"]);
471 // if redeemScript given and private keys given,
472 // add redeemScript to the tempKeystore so it can be signed:
473 if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
474 prevOut.exists("redeemScript")) {
475 UniValue v = prevOut["redeemScript"];
476 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
477 CScript redeemScript(rsData.begin(), rsData.end());
478 tempKeystore.AddCScript(redeemScript);
483 const CKeyStore& keystore = tempKeystore;
485 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
487 // Grab the consensus branch ID for the given height
488 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
491 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
492 CTxIn& txin = mergedTx.vin[i];
493 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
494 if (!coins || !coins->IsAvailable(txin.prevout.n)) {
498 const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
499 const CAmount& amount = coins->vout[txin.prevout.n].nValue;
501 SignatureData sigdata;
502 // Only sign SIGHASH_SINGLE if there's a corresponding output:
503 if (!fHashSingle || (i < mergedTx.vout.size()))
504 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata, consensusBranchId);
506 // ... and merge in other signatures:
507 BOOST_FOREACH(const CTransaction& txv, txVariants)
508 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i), consensusBranchId);
509 UpdateTransaction(mergedTx, i, sigdata);
511 if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount), consensusBranchId))
516 // do nothing... for now
517 // perhaps store this for later optional JSON output
525 ECCVerifyHandle globalVerifyHandle;
536 static void MutateTx(CMutableTransaction& tx, const std::string& command,
537 const std::string& commandVal)
539 boost::scoped_ptr<Secp256k1Init> ecc;
541 if (command == "nversion")
542 MutateTxVersion(tx, commandVal);
543 else if (command == "locktime")
544 MutateTxLocktime(tx, commandVal);
545 else if (command == "expiry")
546 MutateTxExpiry(tx, commandVal);
548 else if (command == "delin")
549 MutateTxDelInput(tx, commandVal);
550 else if (command == "in")
551 MutateTxAddInput(tx, commandVal);
553 else if (command == "delout")
554 MutateTxDelOutput(tx, commandVal);
555 else if (command == "outaddr")
556 MutateTxAddOutAddr(tx, commandVal);
557 else if (command == "outscript")
558 MutateTxAddOutScript(tx, commandVal);
560 else if (command == "sign") {
561 if (!ecc) { ecc.reset(new Secp256k1Init()); }
562 MutateTxSign(tx, commandVal);
565 else if (command == "load")
566 RegisterLoad(commandVal);
568 else if (command == "set")
569 RegisterSet(commandVal);
572 throw std::runtime_error("unknown command");
575 static void OutputTxJSON(const CTransaction& tx)
577 UniValue entry(UniValue::VOBJ);
578 TxToUniv(tx, uint256(), entry);
580 std::string jsonOutput = entry.write(4);
581 fprintf(stdout, "%s\n", jsonOutput.c_str());
584 static void OutputTxHash(const CTransaction& tx)
586 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
588 fprintf(stdout, "%s\n", strHexHash.c_str());
591 static void OutputTxHex(const CTransaction& tx)
593 std::string strHex = EncodeHexTx(tx);
595 fprintf(stdout, "%s\n", strHex.c_str());
598 static void OutputTx(const CTransaction& tx)
600 if (GetBoolArg("-json", false))
602 else if (GetBoolArg("-txid", false))
608 static std::string readStdin()
613 while (!feof(stdin)) {
614 size_t bread = fread(buf, 1, sizeof(buf), stdin);
615 ret.append(buf, bread);
616 if (bread < sizeof(buf))
621 throw std::runtime_error("error reading stdin");
623 boost::algorithm::trim_right(ret);
628 static int CommandLineRawTx(int argc, char* argv[])
630 std::string strPrint;
633 // Skip switches; Permit common stdin convention "-"
634 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
640 CTransaction txDecodeTmp;
644 // require at least one param
646 throw std::runtime_error("too few parameters");
648 // param: hex-encoded bitcoin transaction
649 std::string strHexTx(argv[1]);
650 if (strHexTx == "-") // "-" implies standard input
651 strHexTx = readStdin();
653 if (!DecodeHexTx(txDecodeTmp, strHexTx))
654 throw std::runtime_error("invalid transaction encoding");
660 CMutableTransaction tx(txDecodeTmp);
662 for (int i = startArg; i < argc; i++) {
663 std::string arg = argv[i];
664 std::string key, value;
665 size_t eqpos = arg.find('=');
666 if (eqpos == std::string::npos)
669 key = arg.substr(0, eqpos);
670 value = arg.substr(eqpos + 1);
673 MutateTx(tx, key, value);
679 catch (const boost::thread_interrupted&) {
682 catch (const std::exception& e) {
683 strPrint = std::string("error: ") + e.what();
687 PrintExceptionContinue(NULL, "CommandLineRawTx()");
691 if (strPrint != "") {
692 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
697 int main(int argc, char* argv[])
702 int ret = AppInitRawTx(argc, argv);
703 if (ret != CONTINUE_EXECUTION)
706 catch (const std::exception& e) {
707 PrintExceptionContinue(&e, "AppInitRawTx()");
710 PrintExceptionContinue(NULL, "AppInitRawTx()");
714 int ret = EXIT_FAILURE;
716 ret = CommandLineRawTx(argc, argv);
718 catch (const std::exception& e) {
719 PrintExceptionContinue(&e, "CommandLineRawTx()");
721 PrintExceptionContinue(NULL, "CommandLineRawTx()");