]> Git Repo - VerusCoin.git/blob - src/komodo-tx.cpp
Merge remote-tracking branch 'asher/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 bool IsBlockBoundTransaction(const CTransaction &tx)
46 {
47     return false;
48 }
49
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;
54
55 //
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.
58 //
59 static int AppInitRawTx(int argc, char* argv[])
60 {
61     //
62     // Parameters
63     //
64     ParseParameters(argc, argv);
65
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");
69         return false;
70     }
71
72     fCreateBlank = GetBoolArg("-create", false);
73
74     if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
75     {
76         // First part of help message is specific to this utility
77         std::string strUsage = _("Zcash zcash-tx utility version") + " " + FormatFullVersion() + "\n\n" +
78             _("Usage:") + "\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" +
81               "\n";
82
83         fprintf(stdout, "%s", strUsage.c_str());
84
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"));
92
93         fprintf(stdout, "%s", strUsage.c_str());
94
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());
109
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());
114
115         if (argc < 2) {
116             fprintf(stderr, "Error: too few parameters\n");
117             return EXIT_FAILURE;
118         }
119         return EXIT_SUCCESS;
120     }
121     return CONTINUE_EXECUTION;
122 }
123
124 static void RegisterSetJson(const std::string& key, const std::string& rawJson)
125 {
126     UniValue val;
127     if (!val.read(rawJson)) {
128         std::string strErr = "Cannot parse JSON for key " + key;
129         throw std::runtime_error(strErr);
130     }
131
132     registers[key] = val;
133 }
134
135 static void RegisterSet(const std::string& strInput)
136 {
137     // separate NAME:VALUE in string
138     size_t pos = strInput.find(':');
139     if ((pos == std::string::npos) ||
140         (pos == 0) ||
141         (pos == (strInput.size() - 1)))
142         throw std::runtime_error("Register input requires NAME:VALUE");
143
144     std::string key = strInput.substr(0, pos);
145     std::string valStr = strInput.substr(pos + 1, std::string::npos);
146
147     RegisterSetJson(key, valStr);
148 }
149
150 static void RegisterLoad(const std::string& strInput)
151 {
152     // separate NAME:FILENAME in string
153     size_t pos = strInput.find(':');
154     if ((pos == std::string::npos) ||
155         (pos == 0) ||
156         (pos == (strInput.size() - 1)))
157         throw std::runtime_error("Register load requires NAME:FILENAME");
158
159     std::string key = strInput.substr(0, pos);
160     std::string filename = strInput.substr(pos + 1, std::string::npos);
161
162     FILE *f = fopen(filename.c_str(), "r");
163     if (!f) {
164         std::string strErr = "Cannot open file " + filename;
165         throw std::runtime_error(strErr);
166     }
167
168     // load file chunks into one big buffer
169     std::string valStr;
170     while ((!feof(f)) && (!ferror(f))) {
171         char buf[4096];
172         int bread = fread(buf, 1, sizeof(buf), f);
173         if (bread <= 0)
174             break;
175
176         valStr.insert(valStr.size(), buf, bread);
177     }
178
179     int error = ferror(f);
180     fclose(f);
181
182     if (error) {
183         std::string strErr = "Error reading file " + filename;
184         throw std::runtime_error(strErr);
185     }
186
187     // evaluate as JSON buffer register
188     RegisterSetJson(key, valStr);
189 }
190
191 static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
192 {
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");
196
197     tx.nVersion = (int) newVersion;
198 }
199
200 static void MutateTxExpiry(CMutableTransaction& tx, const std::string& cmdVal)
201 {
202     int64_t newExpiry = atoi64(cmdVal);
203     if (newExpiry >= TX_EXPIRY_HEIGHT_THRESHOLD) {
204         throw std::runtime_error("Invalid TX expiry requested");
205     }
206     tx.nExpiryHeight = (int) newExpiry;
207 }
208
209 static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
210 {
211     int64_t newLocktime = atoi64(cmdVal);
212     if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
213         throw std::runtime_error("Invalid TX locktime requested");
214
215     tx.nLockTime = (unsigned int) newLocktime;
216 }
217
218 static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
219 {
220     std::vector<std::string> vStrInputParts;
221     boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
222
223     // separate TXID:VOUT in string
224     if (vStrInputParts.size()<2)
225         throw std::runtime_error("TX input missing separator");
226
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));
232
233     static const unsigned int minTxOutSz = 9;
234     static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz;
235
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");
241
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]);
246
247     // append to transaction input list
248     CTxIn txin(txid, vout, CScript(), nSequenceIn);
249     tx.vin.push_back(txin);
250 }
251
252 static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
253 {
254     // separate VALUE:ADDRESS in string
255     size_t pos = strInput.find(':');
256     if ((pos == std::string::npos) ||
257         (pos == 0) ||
258         (pos == (strInput.size() - 1)))
259         throw std::runtime_error("TX output missing separator");
260
261     // extract and validate VALUE
262     std::string strValue = strInput.substr(0, pos);
263     CAmount value;
264     if (!ParseMoney(strValue, value))
265         throw std::runtime_error("invalid TX output value");
266
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");
272     }
273     CScript scriptPubKey = GetScriptForDestination(destination);
274
275     // construct TxOut, append to transaction output list
276     CTxOut txout(value, scriptPubKey);
277     tx.vout.push_back(txout);
278 }
279
280 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
281 {
282     // separate VALUE:SCRIPT in string
283     size_t pos = strInput.find(':');
284     if ((pos == std::string::npos) ||
285         (pos == 0))
286         throw std::runtime_error("TX output missing separator");
287
288     // extract and validate VALUE
289     std::string strValue = strInput.substr(0, pos);
290     CAmount value;
291     if (!ParseMoney(strValue, value))
292         throw std::runtime_error("invalid TX output value");
293
294     // extract and validate script
295     std::string strScript = strInput.substr(pos + 1, std::string::npos);
296     CScript scriptPubKey = ParseScript(strScript); // throws on err
297
298     // construct TxOut, append to transaction output list
299     CTxOut txout(value, scriptPubKey);
300     tx.vout.push_back(txout);
301 }
302
303 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
304 {
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());
310     }
311
312     // delete input from transaction
313     tx.vin.erase(tx.vin.begin() + inIdx);
314 }
315
316 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
317 {
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());
323     }
324
325     // delete output from transaction
326     tx.vout.erase(tx.vout.begin() + outIdx);
327 }
328
329 static const unsigned int N_SIGHASH_OPTS = 6;
330 static const struct {
331     const char *flagStr;
332     int flags;
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},
340 };
341
342 static bool findSighashFlags(int& flags, const std::string& flagStr)
343 {
344     flags = 0;
345
346     for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
347         if (flagStr == sighashOptions[i].flagStr) {
348             flags = sighashOptions[i].flags;
349             return true;
350         }
351     }
352
353     return false;
354 }
355
356 uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
357 {
358     if (!o.count(strKey))
359         return uint256();
360     return ParseHashUV(o[strKey], strKey);
361 }
362
363 std::vector<unsigned char> ParseHexUO(std::map<std::string,UniValue>& o, std::string strKey)
364 {
365     if (!o.count(strKey)) {
366         std::vector<unsigned char> emptyVec;
367         return emptyVec;
368     }
369     return ParseHexUV(o[strKey], strKey);
370 }
371
372 static CAmount AmountFromValue(const UniValue& value)
373 {
374     if (!value.isNum() && !value.isStr())
375         throw std::runtime_error("Amount is not a number or string");
376     CAmount amount;
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");
381     return amount;
382 }
383
384 static void MutateTxSign(CMutableTransaction& tx, const std::string& strInput)
385 {
386     // separate HEIGHT:SIGHASH-FLAGS in string
387     size_t pos = strInput.find(':');
388     if ((pos == 0) ||
389         (pos == (strInput.size() - 1)))
390         throw std::runtime_error("Invalid sighash flag separator");
391
392     // extract and validate HEIGHT
393     std::string strHeight = strInput.substr(0, pos);
394     int nHeight = atoi(strHeight);
395     if (nHeight <= 0) {
396         throw std::runtime_error("invalid height");
397     }
398
399     // extract and validate SIGHASH-FLAGS
400     int nHashType = SIGHASH_ALL;
401     std::string flagStr;
402     if (pos != std::string::npos) {
403         flagStr = strInput.substr(pos + 1, std::string::npos);
404     }
405     if (flagStr.size() > 0)
406         if (!findSighashFlags(nHashType, flagStr))
407             throw std::runtime_error("unknown sighash flag/sign option");
408
409     std::vector<CTransaction> txVariants;
410     txVariants.push_back(tx);
411
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);
418
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"];
424     fGivenKeys = true;
425
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");
432         }
433         tempKeystore.AddKey(key);
434     }
435
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"];
440     {
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");
445
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");
449
450             uint256 txid = ParseHashUV(prevOut["txid"], "txid");
451
452             int nOut = atoi(prevOut["vout"].getValStr());
453             if (nOut < 0)
454                 throw std::runtime_error("vout must be positive");
455
456             std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
457             CScript scriptPubKey(pkData.begin(), pkData.end());
458
459             {
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);
466                 }
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"]);
473                 }
474             }
475
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);
484             }
485         }
486     }
487
488     const CKeyStore& keystore = tempKeystore;
489
490     bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
491
492     // Grab the consensus branch ID for the given height
493     auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
494
495     // Sign what we can:
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)) {
500             fComplete = false;
501             continue;
502         }
503         const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
504         const CAmount& amount = coins->vout[txin.prevout.n].nValue;
505
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);
510
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);
515
516         if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount), consensusBranchId))
517             fComplete = false;
518     }
519
520     if (fComplete) {
521         // do nothing... for now
522         // perhaps store this for later optional JSON output
523     }
524
525     tx = mergedTx;
526 }
527
528 class Secp256k1Init
529 {
530     ECCVerifyHandle globalVerifyHandle;
531
532 public:
533     Secp256k1Init() {
534         ECC_Start();
535     }
536     ~Secp256k1Init() {
537         ECC_Stop();
538     }
539 };
540
541 static void MutateTx(CMutableTransaction& tx, const std::string& command,
542                      const std::string& commandVal)
543 {
544     boost::scoped_ptr<Secp256k1Init> ecc;
545
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);
552
553     else if (command == "delin")
554         MutateTxDelInput(tx, commandVal);
555     else if (command == "in")
556         MutateTxAddInput(tx, commandVal);
557
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);
564
565     else if (command == "sign") {
566         if (!ecc) { ecc.reset(new Secp256k1Init()); }
567         MutateTxSign(tx, commandVal);
568     }
569
570     else if (command == "load")
571         RegisterLoad(commandVal);
572
573     else if (command == "set")
574         RegisterSet(commandVal);
575
576     else
577         throw std::runtime_error("unknown command");
578 }
579
580 static void OutputTxJSON(const CTransaction& tx)
581 {
582     UniValue entry(UniValue::VOBJ);
583     TxToUniv(tx, uint256(), entry);
584
585     std::string jsonOutput = entry.write(4);
586     fprintf(stdout, "%s\n", jsonOutput.c_str());
587 }
588
589 static void OutputTxHash(const CTransaction& tx)
590 {
591     std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
592
593     fprintf(stdout, "%s\n", strHexHash.c_str());
594 }
595
596 static void OutputTxHex(const CTransaction& tx)
597 {
598     std::string strHex = EncodeHexTx(tx);
599
600     fprintf(stdout, "%s\n", strHex.c_str());
601 }
602
603 static void OutputTx(const CTransaction& tx)
604 {
605     if (GetBoolArg("-json", false))
606         OutputTxJSON(tx);
607     else if (GetBoolArg("-txid", false))
608         OutputTxHash(tx);
609     else
610         OutputTxHex(tx);
611 }
612
613 static std::string readStdin()
614 {
615     char buf[4096];
616     std::string ret;
617
618     while (!feof(stdin)) {
619         size_t bread = fread(buf, 1, sizeof(buf), stdin);
620         ret.append(buf, bread);
621         if (bread < sizeof(buf))
622             break;
623     }
624
625     if (ferror(stdin))
626         throw std::runtime_error("error reading stdin");
627
628     boost::algorithm::trim_right(ret);
629
630     return ret;
631 }
632
633 static int CommandLineRawTx(int argc, char* argv[])
634 {
635     std::string strPrint;
636     int nRet = 0;
637     try {
638         // Skip switches; Permit common stdin convention "-"
639         while (argc > 1 && IsSwitchChar(argv[1][0]) &&
640                (argv[1][1] != 0)) {
641             argc--;
642             argv++;
643         }
644
645         CTransaction txDecodeTmp;
646         int startArg;
647
648         if (!fCreateBlank) {
649             // require at least one param
650             if (argc < 2)
651                 throw std::runtime_error("too few parameters");
652
653             // param: hex-encoded bitcoin transaction
654             std::string strHexTx(argv[1]);
655             if (strHexTx == "-")                 // "-" implies standard input
656                 strHexTx = readStdin();
657
658             if (!DecodeHexTx(txDecodeTmp, strHexTx))
659                 throw std::runtime_error("invalid transaction encoding");
660
661             startArg = 2;
662         } else
663             startArg = 1;
664
665         CMutableTransaction tx(txDecodeTmp);
666
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)
672                 key = arg;
673             else {
674                 key = arg.substr(0, eqpos);
675                 value = arg.substr(eqpos + 1);
676             }
677
678             MutateTx(tx, key, value);
679         }
680
681         OutputTx(tx);
682     }
683
684     catch (const boost::thread_interrupted&) {
685         throw;
686     }
687     catch (const std::exception& e) {
688         strPrint = std::string("error: ") + e.what();
689         nRet = EXIT_FAILURE;
690     }
691     catch (...) {
692         PrintExceptionContinue(NULL, "CommandLineRawTx()");
693         throw;
694     }
695
696     if (strPrint != "") {
697         fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
698     }
699     return nRet;
700 }
701
702 int main(int argc, char* argv[])
703 {
704     SetupEnvironment();
705
706     try {
707         int ret = AppInitRawTx(argc, argv);
708         if (ret != CONTINUE_EXECUTION)
709             return ret;
710     }
711     catch (const std::exception& e) {
712         PrintExceptionContinue(&e, "AppInitRawTx()");
713         return EXIT_FAILURE;
714     } catch (...) {
715         PrintExceptionContinue(NULL, "AppInitRawTx()");
716         return EXIT_FAILURE;
717     }
718
719     int ret = EXIT_FAILURE;
720     try {
721         ret = CommandLineRawTx(argc, argv);
722     }
723     catch (const std::exception& e) {
724         PrintExceptionContinue(&e, "CommandLineRawTx()");
725     } catch (...) {
726         PrintExceptionContinue(NULL, "CommandLineRawTx()");
727     }
728     return ret;
729 }
This page took 0.066365 seconds and 4 git commands to generate.