1 // Copyright (c) 2009-2014 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or https://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 "pbaas/pbaas.h"
15 #include "script/sign.h"
18 #include "utilmoneystr.h"
19 #include "utilstrencodings.h"
23 #include <boost/algorithm/string.hpp>
24 #include <boost/assign/list_of.hpp>
29 #include "arith_uint256.h"
30 #include "komodo_structs.h"
31 #include "komodo_globals.h"
32 #include "komodo_defs.h"
34 #include "komodo_interest.h"
36 struct CCcontract_info *CCinit(struct CCcontract_info *cp, uint8_t evalcode)
41 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)
46 CConnectedChains ConnectedChains;
47 CCurrencyDefinition CConnectedChains::GetCachedCurrency(const uint160 ¤cyID)
49 return CCurrencyDefinition();
52 static bool fCreateBlank;
53 static std::map<std::string,UniValue> registers;
54 static const int CONTINUE_EXECUTION=-1;
55 boost::optional<libzcash::SaplingPaymentAddress> defaultSaplingDest;
58 // This function returns either one of EXIT_ codes when it's expected to stop the process or
59 // CONTINUE_EXECUTION when it's expected to continue further.
61 static int AppInitRawTx(int argc, char* argv[])
66 ParseParameters(argc, argv);
68 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
69 if (!SelectParamsFromCommandLine()) {
70 fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
74 fCreateBlank = GetBoolArg("-create", false);
76 if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
78 // First part of help message is specific to this utility
79 std::string strUsage = _("Zcash zcash-tx utility version") + " " + FormatFullVersion() + "\n\n" +
81 " zcash-tx [options] <hex-tx> [commands] " + _("Update hex-encoded zcash transaction") + "\n" +
82 " zcash-tx [options] -create [commands] " + _("Create hex-encoded zcash transaction") + "\n" +
85 fprintf(stdout, "%s", strUsage.c_str());
87 strUsage = HelpMessageGroup(_("Options:"));
88 strUsage += HelpMessageOpt("-?", _("This help message"));
89 strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
90 strUsage += HelpMessageOpt("-json", _("Select JSON output"));
91 strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
92 strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly."));
93 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
95 fprintf(stdout, "%s", strUsage.c_str());
97 strUsage = HelpMessageGroup(_("Commands:"));
98 strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
99 strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
100 strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
101 strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
102 strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
103 strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
104 strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
105 strUsage += HelpMessageOpt("sign=HEIGHT:SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
106 _("This command requires JSON registers:") +
107 _("prevtxs=JSON object") + ", " +
108 _("privatekeys=JSON object") + ". " +
109 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
110 fprintf(stdout, "%s", strUsage.c_str());
112 strUsage = HelpMessageGroup(_("Register Commands:"));
113 strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
114 strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
115 fprintf(stdout, "%s", strUsage.c_str());
118 fprintf(stderr, "Error: too few parameters\n");
123 return CONTINUE_EXECUTION;
126 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
129 if (!val.read(rawJson)) {
130 std::string strErr = "Cannot parse JSON for key " + key;
131 throw std::runtime_error(strErr);
134 registers[key] = val;
137 static void RegisterSet(const std::string& strInput)
139 // separate NAME:VALUE in string
140 size_t pos = strInput.find(':');
141 if ((pos == std::string::npos) ||
143 (pos == (strInput.size() - 1)))
144 throw std::runtime_error("Register input requires NAME:VALUE");
146 std::string key = strInput.substr(0, pos);
147 std::string valStr = strInput.substr(pos + 1, std::string::npos);
149 RegisterSetJson(key, valStr);
152 static void RegisterLoad(const std::string& strInput)
154 // separate NAME:FILENAME in string
155 size_t pos = strInput.find(':');
156 if ((pos == std::string::npos) ||
158 (pos == (strInput.size() - 1)))
159 throw std::runtime_error("Register load requires NAME:FILENAME");
161 std::string key = strInput.substr(0, pos);
162 std::string filename = strInput.substr(pos + 1, std::string::npos);
164 FILE *f = fopen(filename.c_str(), "r");
166 std::string strErr = "Cannot open file " + filename;
167 throw std::runtime_error(strErr);
170 // load file chunks into one big buffer
172 while ((!feof(f)) && (!ferror(f))) {
174 int bread = fread(buf, 1, sizeof(buf), f);
178 valStr.insert(valStr.size(), buf, bread);
181 int error = ferror(f);
185 std::string strErr = "Error reading file " + filename;
186 throw std::runtime_error(strErr);
189 // evaluate as JSON buffer register
190 RegisterSetJson(key, valStr);
193 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
195 int64_t newVersion = atoi64(cmdVal);
196 if (newVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION || newVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION)
197 throw std::runtime_error("Invalid TX version requested");
199 tx.nVersion = (int) newVersion;
202 static void MutateTxExpiry(CMutableTransaction& tx, const std::string& cmdVal)
204 int64_t newExpiry = atoi64(cmdVal);
205 if (newExpiry <= 0 || newExpiry >= TX_EXPIRY_HEIGHT_THRESHOLD) {
206 throw std::runtime_error("Invalid TX expiry requested");
208 tx.nExpiryHeight = (int) newExpiry;
211 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
213 int64_t newLocktime = atoi64(cmdVal);
214 if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
215 throw std::runtime_error("Invalid TX locktime requested");
217 tx.nLockTime = (unsigned int) newLocktime;
220 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
222 std::vector<std::string> vStrInputParts;
223 boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
225 // separate TXID:VOUT in string
226 if (vStrInputParts.size()<2)
227 throw std::runtime_error("TX input missing separator");
229 // extract and validate TXID
230 std::string strTxid = vStrInputParts[0];
231 if ((strTxid.size() != 64) || !IsHex(strTxid))
232 throw std::runtime_error("invalid TX input txid");
233 uint256 txid(uint256S(strTxid));
235 static const unsigned int minTxOutSz = 9;
236 static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz;
238 // extract and validate vout
239 std::string strVout = vStrInputParts[1];
240 int vout = atoi(strVout);
241 if ((vout < 0) || (vout > (int)maxVout))
242 throw std::runtime_error("invalid TX input vout");
244 // extract the optional sequence number
245 uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
246 if (vStrInputParts.size() > 2)
247 nSequenceIn = atoi(vStrInputParts[2]);
249 // append to transaction input list
250 CTxIn txin(txid, vout, CScript(), nSequenceIn);
251 tx.vin.push_back(txin);
254 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
256 // separate VALUE:ADDRESS in string
257 size_t pos = strInput.find(':');
258 if ((pos == std::string::npos) ||
260 (pos == (strInput.size() - 1)))
261 throw std::runtime_error("TX output missing separator");
263 // extract and validate VALUE
264 std::string strValue = strInput.substr(0, pos);
266 if (!ParseMoney(strValue, value))
267 throw std::runtime_error("invalid TX output value");
269 // extract and validate ADDRESS
270 std::string strAddr = strInput.substr(pos + 1, std::string::npos);
271 CTxDestination destination = DecodeDestination(strAddr);
272 if (!IsValidDestination(destination)) {
273 throw std::runtime_error("invalid TX output address");
275 CScript scriptPubKey = GetScriptForDestination(destination);
277 // construct TxOut, append to transaction output list
278 CTxOut txout(value, scriptPubKey);
279 tx.vout.push_back(txout);
282 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
284 // separate VALUE:SCRIPT in string
285 size_t pos = strInput.find(':');
286 if ((pos == std::string::npos) ||
288 throw std::runtime_error("TX output missing separator");
290 // extract and validate VALUE
291 std::string strValue = strInput.substr(0, pos);
293 if (!ParseMoney(strValue, value))
294 throw std::runtime_error("invalid TX output value");
296 // extract and validate script
297 std::string strScript = strInput.substr(pos + 1, std::string::npos);
298 CScript scriptPubKey = ParseScript(strScript); // throws on err
300 // construct TxOut, append to transaction output list
301 CTxOut txout(value, scriptPubKey);
302 tx.vout.push_back(txout);
305 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
307 // parse requested deletion index
308 int inIdx = atoi(strInIdx);
309 if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
310 std::string strErr = "Invalid TX input index '" + strInIdx + "'";
311 throw std::runtime_error(strErr.c_str());
314 // delete input from transaction
315 tx.vin.erase(tx.vin.begin() + inIdx);
318 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
320 // parse requested deletion index
321 int outIdx = atoi(strOutIdx);
322 if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
323 std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
324 throw std::runtime_error(strErr.c_str());
327 // delete output from transaction
328 tx.vout.erase(tx.vout.begin() + outIdx);
331 static const unsigned int N_SIGHASH_OPTS = 6;
332 static const struct {
335 } sighashOptions[N_SIGHASH_OPTS] = {
336 {"ALL", SIGHASH_ALL},
337 {"NONE", SIGHASH_NONE},
338 {"SINGLE", SIGHASH_SINGLE},
339 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
340 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
341 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
344 static bool findSighashFlags(int& flags, const std::string& flagStr)
348 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
349 if (flagStr == sighashOptions[i].flagStr) {
350 flags = sighashOptions[i].flags;
358 uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
360 if (!o.count(strKey))
362 return ParseHashUV(o[strKey], strKey);
365 std::vector<unsigned char> ParseHexUO(std::map<std::string,UniValue>& o, std::string strKey)
367 if (!o.count(strKey)) {
368 std::vector<unsigned char> emptyVec;
371 return ParseHexUV(o[strKey], strKey);
374 static void MutateTxSign(CMutableTransaction& tx, const std::string& strInput)
376 // separate HEIGHT:SIGHASH-FLAGS in string
377 size_t pos = strInput.find(':');
379 (pos == (strInput.size() - 1)))
380 throw std::runtime_error("Invalid sighash flag separator");
382 // extract and validate HEIGHT
383 std::string strHeight = strInput.substr(0, pos);
384 int nHeight = atoi(strHeight);
386 throw std::runtime_error("invalid height");
389 // extract and validate SIGHASH-FLAGS
390 int nHashType = SIGHASH_ALL;
392 if (pos != std::string::npos) {
393 flagStr = strInput.substr(pos + 1, std::string::npos);
395 if (flagStr.size() > 0)
396 if (!findSighashFlags(nHashType, flagStr))
397 throw std::runtime_error("unknown sighash flag/sign option");
399 std::vector<CTransaction> txVariants;
400 txVariants.push_back(tx);
402 // mergedTx will end up with all the signatures; it
403 // starts as a clone of the raw tx:
404 CMutableTransaction mergedTx(txVariants[0]);
405 bool fComplete = true;
406 CCoinsView viewDummy;
407 CCoinsViewCache view(&viewDummy);
409 if (!registers.count("privatekeys"))
410 throw std::runtime_error("privatekeys register variable must be set.");
411 bool fGivenKeys = false;
412 CBasicKeyStore tempKeystore;
413 UniValue keysObj = registers["privatekeys"];
416 for (size_t kidx = 0; kidx < keysObj.size(); kidx++) {
417 if (!keysObj[kidx].isStr())
418 throw std::runtime_error("privatekey not a std::string");
419 CKey key = DecodeSecret(keysObj[kidx].getValStr());
420 if (!key.IsValid()) {
421 throw std::runtime_error("privatekey not valid");
423 tempKeystore.AddKey(key);
426 // Add previous txouts given in the RPC call:
427 if (!registers.count("prevtxs"))
428 throw std::runtime_error("prevtxs register variable must be set.");
429 UniValue prevtxsObj = registers["prevtxs"];
431 for (size_t previdx = 0; previdx < prevtxsObj.size(); previdx++) {
432 UniValue prevOut = prevtxsObj[previdx];
433 if (!prevOut.isObject())
434 throw std::runtime_error("expected prevtxs internal object");
436 std::map<std::string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
437 if (!prevOut.checkObject(types))
438 throw std::runtime_error("prevtxs internal object typecheck fail");
440 uint256 txid = ParseHashUV(prevOut["txid"], "txid");
442 int nOut = atoi(prevOut["vout"].getValStr());
444 throw std::runtime_error("vout must be positive");
446 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
447 CScript scriptPubKey(pkData.begin(), pkData.end());
450 CCoinsModifier coins = view.ModifyCoins(txid);
451 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
452 std::string err("Previous output scriptPubKey mismatch:\n");
453 err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
454 ScriptToAsmStr(scriptPubKey);
455 throw std::runtime_error(err);
457 if ((unsigned int)nOut >= coins->vout.size())
458 coins->vout.resize(nOut+1);
459 coins->vout[nOut].scriptPubKey = scriptPubKey;
460 coins->vout[nOut].nValue = 0;
461 if (prevOut.exists("amount")) {
462 coins->vout[nOut].nValue = AmountFromValue(prevOut["amount"]);
466 // if redeemScript given and private keys given,
467 // add redeemScript to the tempKeystore so it can be signed:
468 if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
469 prevOut.exists("redeemScript")) {
470 UniValue v = prevOut["redeemScript"];
471 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
472 CScript redeemScript(rsData.begin(), rsData.end());
473 tempKeystore.AddCScript(redeemScript);
478 const CKeyStore& keystore = tempKeystore;
480 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
482 // Grab the consensus branch ID for the given height
483 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
486 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
487 CTxIn& txin = mergedTx.vin[i];
488 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
489 if (!coins || !coins->IsAvailable(txin.prevout.n)) {
493 const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
494 const CAmount& amount = coins->vout[txin.prevout.n].nValue;
496 SignatureData sigdata;
497 // Only sign SIGHASH_SINGLE if there's a corresponding output:
498 if (!fHashSingle || (i < mergedTx.vout.size()))
499 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, prevPubKey, nHeight, nHashType), prevPubKey, sigdata, consensusBranchId);
501 // ... and merge in other signatures:
502 BOOST_FOREACH(const CTransaction& txv, txVariants)
503 sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i), consensusBranchId);
504 UpdateTransaction(mergedTx, i, sigdata);
506 if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount), consensusBranchId))
511 // do nothing... for now
512 // perhaps store this for later optional JSON output
520 ECCVerifyHandle globalVerifyHandle;
531 static void MutateTx(CMutableTransaction& tx, const std::string& command,
532 const std::string& commandVal)
534 boost::scoped_ptr<Secp256k1Init> ecc;
536 if (command == "nversion")
537 MutateTxVersion(tx, commandVal);
538 else if (command == "locktime")
539 MutateTxLocktime(tx, commandVal);
540 else if (command == "expiry")
541 MutateTxExpiry(tx, commandVal);
543 else if (command == "delin")
544 MutateTxDelInput(tx, commandVal);
545 else if (command == "in")
546 MutateTxAddInput(tx, commandVal);
548 else if (command == "delout")
549 MutateTxDelOutput(tx, commandVal);
550 else if (command == "outaddr")
551 MutateTxAddOutAddr(tx, commandVal);
552 else if (command == "outscript")
553 MutateTxAddOutScript(tx, commandVal);
555 else if (command == "sign") {
556 if (!ecc) { ecc.reset(new Secp256k1Init()); }
557 MutateTxSign(tx, commandVal);
560 else if (command == "load")
561 RegisterLoad(commandVal);
563 else if (command == "set")
564 RegisterSet(commandVal);
567 throw std::runtime_error("unknown command");
570 static void OutputTxJSON(const CTransaction& tx)
572 UniValue entry(UniValue::VOBJ);
573 TxToUniv(tx, uint256(), entry);
575 std::string jsonOutput = entry.write(4);
576 fprintf(stdout, "%s\n", jsonOutput.c_str());
579 static void OutputTxHash(const CTransaction& tx)
581 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
583 fprintf(stdout, "%s\n", strHexHash.c_str());
586 static void OutputTxHex(const CTransaction& tx)
588 std::string strHex = EncodeHexTx(tx);
590 fprintf(stdout, "%s\n", strHex.c_str());
593 static void OutputTx(const CTransaction& tx)
595 if (GetBoolArg("-json", false))
597 else if (GetBoolArg("-txid", false))
603 static std::string readStdin()
608 while (!feof(stdin)) {
609 size_t bread = fread(buf, 1, sizeof(buf), stdin);
610 ret.append(buf, bread);
611 if (bread < sizeof(buf))
616 throw std::runtime_error("error reading stdin");
618 boost::algorithm::trim_right(ret);
623 static int CommandLineRawTx(int argc, char* argv[])
625 std::string strPrint;
628 // Skip switches; Permit common stdin convention "-"
629 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
635 CTransaction txDecodeTmp;
639 // require at least one param
641 throw std::runtime_error("too few parameters");
643 // param: hex-encoded bitcoin transaction
644 std::string strHexTx(argv[1]);
645 if (strHexTx == "-") // "-" implies standard input
646 strHexTx = readStdin();
648 if (!DecodeHexTx(txDecodeTmp, strHexTx))
649 throw std::runtime_error("invalid transaction encoding");
655 CMutableTransaction tx(txDecodeTmp);
657 for (int i = startArg; i < argc; i++) {
658 std::string arg = argv[i];
659 std::string key, value;
660 size_t eqpos = arg.find('=');
661 if (eqpos == std::string::npos)
664 key = arg.substr(0, eqpos);
665 value = arg.substr(eqpos + 1);
668 MutateTx(tx, key, value);
674 catch (const boost::thread_interrupted&) {
677 catch (const std::exception& e) {
678 strPrint = std::string("error: ") + e.what();
682 PrintExceptionContinue(NULL, "CommandLineRawTx()");
686 if (strPrint != "") {
687 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
692 int main(int argc, char* argv[])
697 int ret = AppInitRawTx(argc, argv);
698 if (ret != CONTINUE_EXECUTION)
701 catch (const std::exception& e) {
702 PrintExceptionContinue(&e, "AppInitRawTx()");
705 PrintExceptionContinue(NULL, "AppInitRawTx()");
709 int ret = EXIT_FAILURE;
711 ret = CommandLineRawTx(argc, argv);
713 catch (const std::exception& e) {
714 PrintExceptionContinue(&e, "CommandLineRawTx()");
716 PrintExceptionContinue(NULL, "CommandLineRawTx()");