]> Git Repo - VerusCoin.git/blob - src/komodo-tx.cpp
Merge branch 'dev' of https://github.com/miketout/VerusCoin into dev
[VerusCoin.git] / src / komodo-tx.cpp
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.
4
5 #include "clientversion.h"
6 #include "coins.h"
7 #include "consensus/consensus.h"
8 #include "consensus/upgrades.h"
9 #include "core_io.h"
10 #include "key_io.h"
11 #include "keystore.h"
12 #include "primitives/transaction.h"
13 #include "script/script.h"
14 #include "script/sign.h"
15 #include <univalue.h>
16 #include "util.h"
17 #include "utilmoneystr.h"
18 #include "utilstrencodings.h"
19
20 #include <stdio.h>
21
22 #include <boost/algorithm/string.hpp>
23 #include <boost/assign/list_of.hpp>
24
25 using namespace std;
26
27 #include "uint256.h"
28 #include "arith_uint256.h"
29 #include "komodo_structs.h"
30 #include "komodo_globals.h"
31 #include "komodo_defs.h"
32
33 #include "komodo_interest.h"
34
35 struct CCcontract_info *CCinit(struct CCcontract_info *cp, uint8_t evalcode)
36 {
37     return NULL;
38 }
39
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)
41 {
42     return(0);
43 }
44
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;
49
50 //
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.
53 //
54 static int AppInitRawTx(int argc, char* argv[])
55 {
56     //
57     // Parameters
58     //
59     ParseParameters(argc, argv);
60
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");
64         return false;
65     }
66
67     fCreateBlank = GetBoolArg("-create", false);
68
69     if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
70     {
71         // First part of help message is specific to this utility
72         std::string strUsage = _("Zcash zcash-tx utility version") + " " + FormatFullVersion() + "\n\n" +
73             _("Usage:") + "\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" +
76               "\n";
77
78         fprintf(stdout, "%s", strUsage.c_str());
79
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"));
87
88         fprintf(stdout, "%s", strUsage.c_str());
89
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());
104
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());
109
110         if (argc < 2) {
111             fprintf(stderr, "Error: too few parameters\n");
112             return EXIT_FAILURE;
113         }
114         return EXIT_SUCCESS;
115     }
116     return CONTINUE_EXECUTION;
117 }
118
119 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
120 {
121     UniValue val;
122     if (!val.read(rawJson)) {
123         std::string strErr = "Cannot parse JSON for key " + key;
124         throw std::runtime_error(strErr);
125     }
126
127     registers[key] = val;
128 }
129
130 static void RegisterSet(const std::string& strInput)
131 {
132     // separate NAME:VALUE in string
133     size_t pos = strInput.find(':');
134     if ((pos == std::string::npos) ||
135         (pos == 0) ||
136         (pos == (strInput.size() - 1)))
137         throw std::runtime_error("Register input requires NAME:VALUE");
138
139     std::string key = strInput.substr(0, pos);
140     std::string valStr = strInput.substr(pos + 1, std::string::npos);
141
142     RegisterSetJson(key, valStr);
143 }
144
145 static void RegisterLoad(const std::string& strInput)
146 {
147     // separate NAME:FILENAME in string
148     size_t pos = strInput.find(':');
149     if ((pos == std::string::npos) ||
150         (pos == 0) ||
151         (pos == (strInput.size() - 1)))
152         throw std::runtime_error("Register load requires NAME:FILENAME");
153
154     std::string key = strInput.substr(0, pos);
155     std::string filename = strInput.substr(pos + 1, std::string::npos);
156
157     FILE *f = fopen(filename.c_str(), "r");
158     if (!f) {
159         std::string strErr = "Cannot open file " + filename;
160         throw std::runtime_error(strErr);
161     }
162
163     // load file chunks into one big buffer
164     std::string valStr;
165     while ((!feof(f)) && (!ferror(f))) {
166         char buf[4096];
167         int bread = fread(buf, 1, sizeof(buf), f);
168         if (bread <= 0)
169             break;
170
171         valStr.insert(valStr.size(), buf, bread);
172     }
173
174     int error = ferror(f);
175     fclose(f);
176
177     if (error) {
178         std::string strErr = "Error reading file " + filename;
179         throw std::runtime_error(strErr);
180     }
181
182     // evaluate as JSON buffer register
183     RegisterSetJson(key, valStr);
184 }
185
186 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
187 {
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");
191
192     tx.nVersion = (int) newVersion;
193 }
194
195 static void MutateTxExpiry(CMutableTransaction& tx, const std::string& cmdVal)
196 {
197     int64_t newExpiry = atoi64(cmdVal);
198     if (newExpiry >= TX_EXPIRY_HEIGHT_THRESHOLD) {
199         throw std::runtime_error("Invalid TX expiry requested");
200     }
201     tx.nExpiryHeight = (int) newExpiry;
202 }
203
204 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
205 {
206     int64_t newLocktime = atoi64(cmdVal);
207     if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
208         throw std::runtime_error("Invalid TX locktime requested");
209
210     tx.nLockTime = (unsigned int) newLocktime;
211 }
212
213 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
214 {
215     std::vector<std::string> vStrInputParts;
216     boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
217
218     // separate TXID:VOUT in string
219     if (vStrInputParts.size()<2)
220         throw std::runtime_error("TX input missing separator");
221
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));
227
228     static const unsigned int minTxOutSz = 9;
229     static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz;
230
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");
236
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]);
241
242     // append to transaction input list
243     CTxIn txin(txid, vout, CScript(), nSequenceIn);
244     tx.vin.push_back(txin);
245 }
246
247 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
248 {
249     // separate VALUE:ADDRESS in string
250     size_t pos = strInput.find(':');
251     if ((pos == std::string::npos) ||
252         (pos == 0) ||
253         (pos == (strInput.size() - 1)))
254         throw std::runtime_error("TX output missing separator");
255
256     // extract and validate VALUE
257     std::string strValue = strInput.substr(0, pos);
258     CAmount value;
259     if (!ParseMoney(strValue, value))
260         throw std::runtime_error("invalid TX output value");
261
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");
267     }
268     CScript scriptPubKey = GetScriptForDestination(destination);
269
270     // construct TxOut, append to transaction output list
271     CTxOut txout(value, scriptPubKey);
272     tx.vout.push_back(txout);
273 }
274
275 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
276 {
277     // separate VALUE:SCRIPT in string
278     size_t pos = strInput.find(':');
279     if ((pos == std::string::npos) ||
280         (pos == 0))
281         throw std::runtime_error("TX output missing separator");
282
283     // extract and validate VALUE
284     std::string strValue = strInput.substr(0, pos);
285     CAmount value;
286     if (!ParseMoney(strValue, value))
287         throw std::runtime_error("invalid TX output value");
288
289     // extract and validate script
290     std::string strScript = strInput.substr(pos + 1, std::string::npos);
291     CScript scriptPubKey = ParseScript(strScript); // throws on err
292
293     // construct TxOut, append to transaction output list
294     CTxOut txout(value, scriptPubKey);
295     tx.vout.push_back(txout);
296 }
297
298 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
299 {
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());
305     }
306
307     // delete input from transaction
308     tx.vin.erase(tx.vin.begin() + inIdx);
309 }
310
311 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
312 {
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());
318     }
319
320     // delete output from transaction
321     tx.vout.erase(tx.vout.begin() + outIdx);
322 }
323
324 static const unsigned int N_SIGHASH_OPTS = 6;
325 static const struct {
326     const char *flagStr;
327     int flags;
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},
335 };
336
337 static bool findSighashFlags(int& flags, const std::string& flagStr)
338 {
339     flags = 0;
340
341     for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
342         if (flagStr == sighashOptions[i].flagStr) {
343             flags = sighashOptions[i].flags;
344             return true;
345         }
346     }
347
348     return false;
349 }
350
351 uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
352 {
353     if (!o.count(strKey))
354         return uint256();
355     return ParseHashUV(o[strKey], strKey);
356 }
357
358 std::vector<unsigned char> ParseHexUO(std::map<std::string,UniValue>& o, std::string strKey)
359 {
360     if (!o.count(strKey)) {
361         std::vector<unsigned char> emptyVec;
362         return emptyVec;
363     }
364     return ParseHexUV(o[strKey], strKey);
365 }
366
367 static CAmount AmountFromValue(const UniValue& value)
368 {
369     if (!value.isNum() && !value.isStr())
370         throw std::runtime_error("Amount is not a number or string");
371     CAmount amount;
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");
376     return amount;
377 }
378
379 static void MutateTxSign(CMutableTransaction& tx, const std::string& strInput)
380 {
381     // separate HEIGHT:SIGHASH-FLAGS in string
382     size_t pos = strInput.find(':');
383     if ((pos == 0) ||
384         (pos == (strInput.size() - 1)))
385         throw std::runtime_error("Invalid sighash flag separator");
386
387     // extract and validate HEIGHT
388     std::string strHeight = strInput.substr(0, pos);
389     int nHeight = atoi(strHeight);
390     if (nHeight <= 0) {
391         throw std::runtime_error("invalid height");
392     }
393
394     // extract and validate SIGHASH-FLAGS
395     int nHashType = SIGHASH_ALL;
396     std::string flagStr;
397     if (pos != std::string::npos) {
398         flagStr = strInput.substr(pos + 1, std::string::npos);
399     }
400     if (flagStr.size() > 0)
401         if (!findSighashFlags(nHashType, flagStr))
402             throw std::runtime_error("unknown sighash flag/sign option");
403
404     std::vector<CTransaction> txVariants;
405     txVariants.push_back(tx);
406
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);
413
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"];
419     fGivenKeys = true;
420
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");
427         }
428         tempKeystore.AddKey(key);
429     }
430
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"];
435     {
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");
440
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");
444
445             uint256 txid = ParseHashUV(prevOut["txid"], "txid");
446
447             int nOut = atoi(prevOut["vout"].getValStr());
448             if (nOut < 0)
449                 throw std::runtime_error("vout must be positive");
450
451             std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
452             CScript scriptPubKey(pkData.begin(), pkData.end());
453
454             {
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);
461                 }
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"]);
468                 }
469             }
470
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);
479             }
480         }
481     }
482
483     const CKeyStore& keystore = tempKeystore;
484
485     bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
486
487     // Grab the consensus branch ID for the given height
488     auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
489
490     // Sign what we can:
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)) {
495             fComplete = false;
496             continue;
497         }
498         const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
499         const CAmount& amount = coins->vout[txin.prevout.n].nValue;
500
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);
505
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);
510
511         if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount), consensusBranchId))
512             fComplete = false;
513     }
514
515     if (fComplete) {
516         // do nothing... for now
517         // perhaps store this for later optional JSON output
518     }
519
520     tx = mergedTx;
521 }
522
523 class Secp256k1Init
524 {
525     ECCVerifyHandle globalVerifyHandle;
526
527 public:
528     Secp256k1Init() {
529         ECC_Start();
530     }
531     ~Secp256k1Init() {
532         ECC_Stop();
533     }
534 };
535
536 static void MutateTx(CMutableTransaction& tx, const std::string& command,
537                      const std::string& commandVal)
538 {
539     boost::scoped_ptr<Secp256k1Init> ecc;
540
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);
547
548     else if (command == "delin")
549         MutateTxDelInput(tx, commandVal);
550     else if (command == "in")
551         MutateTxAddInput(tx, commandVal);
552
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);
559
560     else if (command == "sign") {
561         if (!ecc) { ecc.reset(new Secp256k1Init()); }
562         MutateTxSign(tx, commandVal);
563     }
564
565     else if (command == "load")
566         RegisterLoad(commandVal);
567
568     else if (command == "set")
569         RegisterSet(commandVal);
570
571     else
572         throw std::runtime_error("unknown command");
573 }
574
575 static void OutputTxJSON(const CTransaction& tx)
576 {
577     UniValue entry(UniValue::VOBJ);
578     TxToUniv(tx, uint256(), entry);
579
580     std::string jsonOutput = entry.write(4);
581     fprintf(stdout, "%s\n", jsonOutput.c_str());
582 }
583
584 static void OutputTxHash(const CTransaction& tx)
585 {
586     std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
587
588     fprintf(stdout, "%s\n", strHexHash.c_str());
589 }
590
591 static void OutputTxHex(const CTransaction& tx)
592 {
593     std::string strHex = EncodeHexTx(tx);
594
595     fprintf(stdout, "%s\n", strHex.c_str());
596 }
597
598 static void OutputTx(const CTransaction& tx)
599 {
600     if (GetBoolArg("-json", false))
601         OutputTxJSON(tx);
602     else if (GetBoolArg("-txid", false))
603         OutputTxHash(tx);
604     else
605         OutputTxHex(tx);
606 }
607
608 static std::string readStdin()
609 {
610     char buf[4096];
611     std::string ret;
612
613     while (!feof(stdin)) {
614         size_t bread = fread(buf, 1, sizeof(buf), stdin);
615         ret.append(buf, bread);
616         if (bread < sizeof(buf))
617             break;
618     }
619
620     if (ferror(stdin))
621         throw std::runtime_error("error reading stdin");
622
623     boost::algorithm::trim_right(ret);
624
625     return ret;
626 }
627
628 static int CommandLineRawTx(int argc, char* argv[])
629 {
630     std::string strPrint;
631     int nRet = 0;
632     try {
633         // Skip switches; Permit common stdin convention "-"
634         while (argc > 1 && IsSwitchChar(argv[1][0]) &&
635                (argv[1][1] != 0)) {
636             argc--;
637             argv++;
638         }
639
640         CTransaction txDecodeTmp;
641         int startArg;
642
643         if (!fCreateBlank) {
644             // require at least one param
645             if (argc < 2)
646                 throw std::runtime_error("too few parameters");
647
648             // param: hex-encoded bitcoin transaction
649             std::string strHexTx(argv[1]);
650             if (strHexTx == "-")                 // "-" implies standard input
651                 strHexTx = readStdin();
652
653             if (!DecodeHexTx(txDecodeTmp, strHexTx))
654                 throw std::runtime_error("invalid transaction encoding");
655
656             startArg = 2;
657         } else
658             startArg = 1;
659
660         CMutableTransaction tx(txDecodeTmp);
661
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)
667                 key = arg;
668             else {
669                 key = arg.substr(0, eqpos);
670                 value = arg.substr(eqpos + 1);
671             }
672
673             MutateTx(tx, key, value);
674         }
675
676         OutputTx(tx);
677     }
678
679     catch (const boost::thread_interrupted&) {
680         throw;
681     }
682     catch (const std::exception& e) {
683         strPrint = std::string("error: ") + e.what();
684         nRet = EXIT_FAILURE;
685     }
686     catch (...) {
687         PrintExceptionContinue(NULL, "CommandLineRawTx()");
688         throw;
689     }
690
691     if (strPrint != "") {
692         fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
693     }
694     return nRet;
695 }
696
697 int main(int argc, char* argv[])
698 {
699     SetupEnvironment();
700
701     try {
702         int ret = AppInitRawTx(argc, argv);
703         if (ret != CONTINUE_EXECUTION)
704             return ret;
705     }
706     catch (const std::exception& e) {
707         PrintExceptionContinue(&e, "AppInitRawTx()");
708         return EXIT_FAILURE;
709     } catch (...) {
710         PrintExceptionContinue(NULL, "AppInitRawTx()");
711         return EXIT_FAILURE;
712     }
713
714     int ret = EXIT_FAILURE;
715     try {
716         ret = CommandLineRawTx(argc, argv);
717     }
718     catch (const std::exception& e) {
719         PrintExceptionContinue(&e, "CommandLineRawTx()");
720     } catch (...) {
721         PrintExceptionContinue(NULL, "CommandLineRawTx()");
722     }
723     return ret;
724 }
This page took 0.066319 seconds and 4 git commands to generate.