Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
bitcoin-tx.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2019 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#if defined(HAVE_CONFIG_H)
6#include <config/bitcoin-config.h>
7#endif
8
9#include <chainparams.h>
10#include <clientversion.h>
11#include <coins.h>
12#include <common/args.h>
13#include <common/system.h>
14#include <consensus/amount.h>
15#include <consensus/consensus.h>
16#include <core_io.h>
17#include <currencyunit.h>
18#include <key_io.h>
20#include <rpc/util.h>
21#include <script/script.h>
22#include <script/sign.h>
24#include <util/exception.h>
25#include <util/fs.h>
26#include <util/moneystr.h>
27#include <util/strencodings.h>
28#include <util/string.h>
29#include <util/translation.h>
30
31#include <univalue.h>
32
33#include <cstdio>
34#include <functional>
35#include <memory>
36
37static bool fCreateBlank;
38static std::map<std::string, UniValue> registers;
39static const int CONTINUE_EXECUTION = -1;
40
41const std::function<std::string(const char *)> G_TRANSLATION_FUN = nullptr;
42
45
47 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
49 argsman.AddArg("-create", "Create new, empty TX.", ArgsManager::ALLOW_ANY,
51 argsman.AddArg("-json", "Select JSON output", ArgsManager::ALLOW_ANY,
53 argsman.AddArg(
54 "-txid",
55 "Output only the hex-encoded transaction id of the resultant "
56 "transaction.",
59
60 argsman.AddArg("delin=N", "Delete input N from TX", ArgsManager::ALLOW_ANY,
62 argsman.AddArg("delout=N", "Delete output N from TX",
64 argsman.AddArg("in=TXID:VOUT(:SEQUENCE_NUMBER)", "Add input to TX",
66 argsman.AddArg("locktime=N", "Set TX lock time to N",
68 argsman.AddArg("nversion=N", "Set TX version to N", ArgsManager::ALLOW_ANY,
70 argsman.AddArg("outaddr=VALUE:ADDRESS", "Add address-based output to TX",
72 argsman.AddArg("outpubkey=VALUE:PUBKEY[:FLAGS]",
73 "Add pay-to-pubkey output to TX. "
74 "Optionally add the \"S\" flag to wrap the output in a "
75 "pay-to-script-hash.",
77 argsman.AddArg("outdata=[VALUE:]DATA", "Add data-based output to TX",
79 argsman.AddArg("outscript=VALUE:SCRIPT[:FLAGS]",
80 "Add raw script output to TX. "
81 "Optionally add the \"S\" flag to wrap the output in a "
82 "pay-to-script-hash.",
84 argsman.AddArg(
85 "outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]",
86 "Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. "
87 "Optionally add the \"S\" flag to wrap the output in a "
88 "pay-to-script-hash.",
90 argsman.AddArg("sign=SIGHASH-FLAGS",
91 "Add zero or more signatures to transaction. "
92 "This command requires JSON registers:"
93 "prevtxs=JSON object, "
94 "privatekeys=JSON object. "
95 "See signrawtransactionwithkey docs for format of sighash "
96 "flags, JSON objects.",
98
99 argsman.AddArg("load=NAME:FILENAME",
100 "Load JSON file FILENAME into register NAME",
102 argsman.AddArg("set=NAME:JSON-STRING",
103 "Set register NAME to given JSON-STRING",
105}
106
107//
108// This function returns either one of EXIT_ codes when it's expected to stop
109// the process or CONTINUE_EXECUTION when it's expected to continue further.
110//
111static int AppInitRawTx(int argc, char *argv[]) {
112 //
113 // Parameters
114 //
116 std::string error;
118 tfm::format(std::cerr, "Error parsing command line arguments: %s\n",
119 error);
120 return EXIT_FAILURE;
121 }
122
123 // Check for -chain, -testnet or -regtest parameter (Params() calls are only
124 // valid after this clause)
125 try {
127 } catch (const std::exception &e) {
128 tfm::format(std::cerr, "Error: %s\n", e.what());
129 return EXIT_FAILURE;
130 }
131
132 fCreateBlank = gArgs.GetBoolArg("-create", false);
133
134 if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
135 // First part of help message is specific to this utility
136 std::string strUsage = PACKAGE_NAME " bitcoin-tx utility version " +
137 FormatFullVersion() + "\n";
138
139 if (gArgs.IsArgSet("-version")) {
141 } else {
142 strUsage +=
143 "\n"
144 "Usage: bitcoin-tx [options] <hex-tx> [commands] Update "
145 "hex-encoded bitcoin transaction\n"
146 "or: bitcoin-tx [options] -create [commands] Create "
147 "hex-encoded bitcoin transaction\n"
148 "\n";
150 }
151
152 tfm::format(std::cout, "%s", strUsage);
153
154 if (argc < 2) {
155 tfm::format(std::cerr, "Error: too few parameters\n");
156 return EXIT_FAILURE;
157 }
158
159 return EXIT_SUCCESS;
160 }
161
162 return CONTINUE_EXECUTION;
163}
164
165static void RegisterSetJson(const std::string &key,
166 const std::string &rawJson) {
167 UniValue val;
168 if (!val.read(rawJson)) {
169 std::string strErr = "Cannot parse JSON for key " + key;
170 throw std::runtime_error(strErr);
171 }
172
173 registers[key] = val;
174}
175
176static void RegisterSet(const std::string &strInput) {
177 // separate NAME:VALUE in string
178 size_t pos = strInput.find(':');
179 if ((pos == std::string::npos) || (pos == 0) ||
180 (pos == (strInput.size() - 1))) {
181 throw std::runtime_error("Register input requires NAME:VALUE");
182 }
183
184 std::string key = strInput.substr(0, pos);
185 std::string valStr = strInput.substr(pos + 1, std::string::npos);
186
188}
189
190static void RegisterLoad(const std::string &strInput) {
191 // separate NAME:FILENAME in string
192 size_t pos = strInput.find(':');
193 if ((pos == std::string::npos) || (pos == 0) ||
194 (pos == (strInput.size() - 1))) {
195 throw std::runtime_error("Register load requires NAME:FILENAME");
196 }
197
198 std::string key = strInput.substr(0, pos);
199 std::string filename = strInput.substr(pos + 1, std::string::npos);
200
201 FILE *f = fsbridge::fopen(filename.c_str(), "r");
202 if (!f) {
203 std::string strErr = "Cannot open file " + filename;
204 throw std::runtime_error(strErr);
205 }
206
207 // load file chunks into one big buffer
208 std::string valStr;
209 while ((!feof(f)) && (!ferror(f))) {
210 char buf[4096];
211 int bread = fread(buf, 1, sizeof(buf), f);
212 if (bread <= 0) {
213 break;
214 }
215
216 valStr.insert(valStr.size(), buf, bread);
217 }
218
219 int error = ferror(f);
220 fclose(f);
221
222 if (error) {
223 std::string strErr = "Error reading file " + filename;
224 throw std::runtime_error(strErr);
225 }
226
227 // evaluate as JSON buffer register
229}
230
231static Amount ExtractAndValidateValue(const std::string &strValue) {
232 Amount value;
233 if (!ParseMoney(strValue, value)) {
234 throw std::runtime_error("invalid TX output value");
235 }
236
237 return value;
238}
239
241 const std::string &cmdVal) {
243 if (!ParseInt64(cmdVal, &newVersion) ||
246 throw std::runtime_error("Invalid TX version requested: '" + cmdVal +
247 "'");
248 }
249
250 tx.nVersion = int(newVersion);
251}
252
254 const std::string &cmdVal) {
257 newLocktime > 0xffffffffLL) {
258 throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal +
259 "'");
260 }
261
262 tx.nLockTime = (unsigned int)newLocktime;
263}
264
266 const std::string &strInput) {
267 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
268
269 // separate TXID:VOUT in string
270 if (vStrInputParts.size() < 2) {
271 throw std::runtime_error("TX input missing separator");
272 }
273
274 // extract and validate TXID
275 uint256 hash;
276 if (!ParseHashStr(vStrInputParts[0], hash)) {
277 throw std::runtime_error("invalid TX input txid");
278 }
279
280 TxId txid(hash);
281
282 static const unsigned int minTxOutSz = 9;
283 static const unsigned int maxVout = MAX_TX_SIZE / minTxOutSz;
284
285 // extract and validate vout
286 const std::string &strVout = vStrInputParts[1];
287 int64_t vout;
288 if (!ParseInt64(strVout, &vout) || vout < 0 ||
289 vout > static_cast<int64_t>(maxVout)) {
290 throw std::runtime_error("invalid TX input vout '" + strVout + "'");
291 }
292
293 // extract the optional sequence number
294 uint32_t nSequenceIn = std::numeric_limits<unsigned int>::max();
295 if (vStrInputParts.size() > 2) {
296 nSequenceIn = std::stoul(vStrInputParts[2]);
297 }
298
299 // append to transaction input list
300 CTxIn txin(txid, vout, CScript(), nSequenceIn);
301 tx.vin.push_back(txin);
302}
303
305 const std::string &strInput,
306 const CChainParams &chainParams) {
307 // Separate into VALUE:ADDRESS
308 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
309
310 if (vStrInputParts.size() != 2) {
311 throw std::runtime_error("TX output missing or too many separators");
312 }
313
314 // Extract and validate VALUE
316
317 // extract and validate ADDRESS
318 std::string strAddr = vStrInputParts[1];
319 CTxDestination destination = DecodeDestination(strAddr, chainParams);
320 if (!IsValidDestination(destination)) {
321 throw std::runtime_error("invalid TX output address");
322 }
323 CScript scriptPubKey = GetScriptForDestination(destination);
324
325 // construct TxOut, append to transaction output list
326 CTxOut txout(value, scriptPubKey);
327 tx.vout.push_back(txout);
328}
329
331 const std::string &strInput) {
332 // Separate into VALUE:PUBKEY[:FLAGS]
333 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
334
335 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
336 throw std::runtime_error("TX output missing or too many separators");
337 }
338
339 // Extract and validate VALUE
341
342 // Extract and validate PUBKEY
343 CPubKey pubkey(ParseHex(vStrInputParts[1]));
344 if (!pubkey.IsFullyValid()) {
345 throw std::runtime_error("invalid TX output pubkey");
346 }
347
348 CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
349
350 // Extract and validate FLAGS
351 bool bScriptHash = false;
352 if (vStrInputParts.size() == 3) {
353 std::string flags = vStrInputParts[2];
354 bScriptHash = (flags.find('S') != std::string::npos);
355 }
356
357 if (bScriptHash) {
358 // Get the ID for the script, and then construct a P2SH destination for
359 // it.
360 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
361 }
362
363 // construct TxOut, append to transaction output list
364 CTxOut txout(value, scriptPubKey);
365 tx.vout.push_back(txout);
366}
367
369 const std::string &strInput) {
370 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
371 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
372
373 // Check that there are enough parameters
374 if (vStrInputParts.size() < 3) {
375 throw std::runtime_error("Not enough multisig parameters");
376 }
377
378 // Extract and validate VALUE
380
381 // Extract REQUIRED
383
384 // Extract NUMKEYS
386
387 // Validate there are the correct number of pubkeys
388 if (vStrInputParts.size() < numkeys + 3) {
389 throw std::runtime_error("incorrect number of multisig pubkeys");
390 }
391
394 throw std::runtime_error("multisig parameter mismatch. Required " +
395 ToString(required) + " of " +
396 ToString(numkeys) + "signatures.");
397 }
398
399 // extract and validate PUBKEYs
400 std::vector<CPubKey> pubkeys;
401 for (int pos = 1; pos <= int(numkeys); pos++) {
402 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
403 if (!pubkey.IsFullyValid()) {
404 throw std::runtime_error("invalid TX output pubkey");
405 }
406
407 pubkeys.push_back(pubkey);
408 }
409
410 // Extract FLAGS
411 bool bScriptHash = false;
412 if (vStrInputParts.size() == numkeys + 4) {
413 std::string flags = vStrInputParts.back();
414 bScriptHash = (flags.find('S') != std::string::npos);
415 } else if (vStrInputParts.size() > numkeys + 4) {
416 // Validate that there were no more parameters passed
417 throw std::runtime_error("Too many parameters");
418 }
419
420 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
421
422 if (bScriptHash) {
423 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
424 throw std::runtime_error(
425 strprintf("redeemScript exceeds size limit: %d > %d",
426 scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
427 }
428 // Get the ID for the script, and then construct a P2SH destination for
429 // it.
430 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
431 }
432
433 // construct TxOut, append to transaction output list
434 CTxOut txout(value, scriptPubKey);
435 tx.vout.push_back(txout);
436}
437
439 const std::string &strInput) {
440 Amount value = Amount::zero();
441
442 // separate [VALUE:]DATA in string
443 size_t pos = strInput.find(':');
444
445 if (pos == 0) {
446 throw std::runtime_error("TX output value not specified");
447 }
448
449 if (pos == std::string::npos) {
450 pos = 0;
451 } else {
452 // Extract and validate VALUE
453 value = ExtractAndValidateValue(strInput.substr(0, pos));
454 ++pos;
455 }
456
457 // extract and validate DATA
458 const std::string strData{strInput.substr(pos, std::string::npos)};
459
460 if (!IsHex(strData)) {
461 throw std::runtime_error("invalid TX output data");
462 }
463
464 std::vector<uint8_t> data = ParseHex(strData);
465
466 CTxOut txout(value, CScript() << OP_RETURN << data);
467 tx.vout.push_back(txout);
468}
469
471 const std::string &strInput) {
472 // separate VALUE:SCRIPT[:FLAGS]
473 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
474 if (vStrInputParts.size() < 2) {
475 throw std::runtime_error("TX output missing separator");
476 }
477
478 // Extract and validate VALUE
480
481 // extract and validate script
482 std::string strScript = vStrInputParts[1];
483 CScript scriptPubKey = ParseScript(strScript);
484
485 // Extract FLAGS
486 bool bScriptHash = false;
487 if (vStrInputParts.size() == 3) {
488 std::string flags = vStrInputParts.back();
489 bScriptHash = (flags.find('S') != std::string::npos);
490 }
491
492 if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
493 throw std::runtime_error(strprintf("script exceeds size limit: %d > %d",
494 scriptPubKey.size(),
496 }
497
498 if (bScriptHash) {
499 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
500 throw std::runtime_error(
501 strprintf("redeemScript exceeds size limit: %d > %d",
502 scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
503 }
504 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
505 }
506
507 // construct TxOut, append to transaction output list
508 CTxOut txout(value, scriptPubKey);
509 tx.vout.push_back(txout);
510}
511
513 const std::string &strInIdx) {
514 // parse requested deletion index
516 if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 ||
517 inIdx >= static_cast<int64_t>(tx.vin.size())) {
518 throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
519 }
520
521 // delete input from transaction
522 tx.vin.erase(tx.vin.begin() + inIdx);
523}
524
526 const std::string &strOutIdx) {
527 // parse requested deletion index
529 if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 ||
530 outIdx >= static_cast<int64_t>(tx.vout.size())) {
531 throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
532 }
533
534 // delete output from transaction
535 tx.vout.erase(tx.vout.begin() + outIdx);
536}
537
538static const unsigned int N_SIGHASH_OPTS = 12;
539static const struct {
540 const char *flagStr;
541 int flags;
543 {"ALL", SIGHASH_ALL},
544 {"NONE", SIGHASH_NONE},
545 {"SINGLE", SIGHASH_SINGLE},
546 {"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
547 {"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
548 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
549 {"ALL|FORKID", SIGHASH_ALL | SIGHASH_FORKID},
550 {"NONE|FORKID", SIGHASH_NONE | SIGHASH_FORKID},
551 {"SINGLE|FORKID", SIGHASH_SINGLE | SIGHASH_FORKID},
552 {"ALL|FORKID|ANYONECANPAY",
554 {"NONE|FORKID|ANYONECANPAY",
556 {"SINGLE|FORKID|ANYONECANPAY",
559
560static bool findSigHashFlags(SigHashType &sigHashType,
561 const std::string &flagStr) {
562 sigHashType = SigHashType();
563
564 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
565 if (flagStr == sigHashOptions[i].flagStr) {
566 sigHashType = SigHashType(sigHashOptions[i].flags);
567 return true;
568 }
569 }
570
571 return false;
572}
573
574static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr) {
575 SigHashType sigHashType = SigHashType().withForkId();
576
577 if ((flagStr.size() > 0) && !findSigHashFlags(sigHashType, flagStr)) {
578 throw std::runtime_error("unknown sighash flag/sign option");
579 }
580
581 // mergedTx will end up with all the signatures; it
582 // starts as a clone of the raw tx:
584 const CMutableTransaction txv{tx};
585
588
589 if (!registers.count("privatekeys")) {
590 throw std::runtime_error("privatekeys register variable must be set.");
591 }
592
594 UniValue keysObj = registers["privatekeys"];
595
596 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
597 if (!keysObj[kidx].isStr()) {
598 throw std::runtime_error("privatekey not a std::string");
599 }
600
601 CKey key = DecodeSecret(keysObj[kidx].getValStr());
602 if (!key.IsValid()) {
603 throw std::runtime_error("privatekey not valid");
604 }
605 tempKeystore.AddKey(key);
606 }
607
608 // Add previous txouts given in the RPC call:
609 if (!registers.count("prevtxs")) {
610 throw std::runtime_error("prevtxs register variable must be set.");
611 }
612
613 UniValue prevtxsObj = registers["prevtxs"];
614
615 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
617 if (!prevOut.isObject()) {
618 throw std::runtime_error("expected prevtxs internal object");
619 }
620
621 std::map<std::string, UniValue::VType> types = {
622 {"txid", UniValue::VSTR},
623 {"vout", UniValue::VNUM},
624 {"scriptPubKey", UniValue::VSTR}};
625 if (!prevOut.checkObject(types)) {
626 throw std::runtime_error("prevtxs internal object typecheck fail");
627 }
628
629 uint256 hash;
630 if (!ParseHashStr(prevOut["txid"].get_str(), hash)) {
631 throw std::runtime_error("txid must be hexadecimal string (not '" +
632 prevOut["txid"].get_str() + "')");
633 }
634
635 TxId txid(hash);
636
637 const int nOut = prevOut["vout"].getInt<int>();
638 if (nOut < 0) {
639 throw std::runtime_error("vout cannot be negative");
640 }
641
642 COutPoint out(txid, nOut);
643 std::vector<uint8_t> pkData(
644 ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
645 CScript scriptPubKey(pkData.begin(), pkData.end());
646
647 {
648 const Coin &coin = view.AccessCoin(out);
649 if (!coin.IsSpent() &&
650 coin.GetTxOut().scriptPubKey != scriptPubKey) {
651 std::string err("Previous output scriptPubKey mismatch:\n");
653 "\nvs:\n" + ScriptToAsmStr(scriptPubKey);
654 throw std::runtime_error(err);
655 }
656
657 CTxOut txout;
658 txout.scriptPubKey = scriptPubKey;
659 txout.nValue = Amount::zero();
660 if (prevOut.exists("amount")) {
661 txout.nValue = AmountFromValue(prevOut["amount"]);
662 }
663
664 view.AddCoin(out, Coin(txout, 1, false), true);
665 }
666
667 // If redeemScript given and private keys given, add redeemScript to the
668 // tempKeystore so it can be signed:
669 if (scriptPubKey.IsPayToScriptHash() &&
670 prevOut.exists("redeemScript")) {
671 UniValue v = prevOut["redeemScript"];
672 std::vector<uint8_t> rsData(ParseHexUV(v, "redeemScript"));
673 CScript redeemScript(rsData.begin(), rsData.end());
674 tempKeystore.AddCScript(redeemScript);
675 }
676 }
677
679
680 // Sign what we can:
681 for (size_t i = 0; i < mergedTx.vin.size(); i++) {
682 CTxIn &txin = mergedTx.vin[i];
683 const Coin &coin = view.AccessCoin(txin.prevout);
684 if (coin.IsSpent()) {
685 continue;
686 }
687
688 const CScript &prevPubKey = coin.GetTxOut().scriptPubKey;
689 const Amount amount = coin.GetTxOut().nValue;
690
691 SignatureData sigdata =
693 // Only sign SIGHASH_SINGLE if there's a corresponding output:
694 if ((sigHashType.getBaseType() != BaseSigHashType::SINGLE) ||
695 (i < mergedTx.vout.size())) {
698 &mergedTx, i, amount, sigHashType),
699 prevPubKey, sigdata);
700 }
701
702 UpdateInput(txin, sigdata);
703 }
704
705 tx = mergedTx;
706}
707
715
716static void MutateTx(CMutableTransaction &tx, const std::string &command,
717 const std::string &commandVal,
718 const CChainParams &chainParams) {
719 std::unique_ptr<Secp256k1Init> ecc;
720
721 if (command == "nversion") {
723 } else if (command == "locktime") {
725 } else if (command == "delin") {
727 } else if (command == "in") {
729 } else if (command == "delout") {
731 } else if (command == "outaddr") {
732 MutateTxAddOutAddr(tx, commandVal, chainParams);
733 } else if (command == "outpubkey") {
734 ecc.reset(new Secp256k1Init());
736 } else if (command == "outmultisig") {
737 ecc.reset(new Secp256k1Init());
739 } else if (command == "outscript") {
741 } else if (command == "outdata") {
743 } else if (command == "sign") {
744 ecc.reset(new Secp256k1Init());
746 } else if (command == "load") {
748 } else if (command == "set") {
750 } else {
751 throw std::runtime_error("unknown command");
752 }
753}
754
755static void OutputTxJSON(const CTransaction &tx) {
757 TxToUniv(tx, BlockHash(), entry);
758
759 std::string jsonOutput = entry.write(4);
760 tfm::format(std::cout, "%s\n", jsonOutput);
761}
762
763static void OutputTxHash(const CTransaction &tx) {
764 // the hex-encoded transaction id.
765 std::string strHexHash = tx.GetId().GetHex();
766
767 tfm::format(std::cout, "%s\n", strHexHash);
768}
769
770static void OutputTxHex(const CTransaction &tx) {
771 std::string strHex = EncodeHexTx(tx);
772
773 tfm::format(std::cout, "%s\n", strHex);
774}
775
776static void OutputTx(const CTransaction &tx) {
777 if (gArgs.GetBoolArg("-json", false)) {
778 OutputTxJSON(tx);
779 } else if (gArgs.GetBoolArg("-txid", false)) {
780 OutputTxHash(tx);
781 } else {
782 OutputTxHex(tx);
783 }
784}
785
786static std::string readStdin() {
787 char buf[4096];
788 std::string ret;
789
790 while (!feof(stdin)) {
791 size_t bread = fread(buf, 1, sizeof(buf), stdin);
792 ret.append(buf, bread);
793 if (bread < sizeof(buf)) {
794 break;
795 }
796 }
797
798 if (ferror(stdin)) {
799 throw std::runtime_error("error reading stdin");
800 }
801
802 return TrimString(ret);
803}
804
805static int CommandLineRawTx(int argc, char *argv[],
806 const CChainParams &chainParams) {
807 std::string strPrint;
808 int nRet = 0;
809 try {
810 // Skip switches; Permit common stdin convention "-"
811 while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
812 argc--;
813 argv++;
814 }
815
817 int startArg;
818
819 if (!fCreateBlank) {
820 // require at least one param
821 if (argc < 2) {
822 throw std::runtime_error("too few parameters");
823 }
824
825 // param: hex-encoded bitcoin transaction
826 std::string strHexTx(argv[1]);
827
828 // "-" implies standard input
829 if (strHexTx == "-") {
831 }
832
833 if (!DecodeHexTx(tx, strHexTx)) {
834 throw std::runtime_error("invalid transaction encoding");
835 }
836
837 startArg = 2;
838 } else {
839 startArg = 1;
840 }
841
842 for (int i = startArg; i < argc; i++) {
843 std::string arg = argv[i];
844 std::string key, value;
845 size_t eqpos = arg.find('=');
846 if (eqpos == std::string::npos) {
847 key = arg;
848 } else {
849 key = arg.substr(0, eqpos);
850 value = arg.substr(eqpos + 1);
851 }
852
853 MutateTx(tx, key, value, chainParams);
854 }
855
857 } catch (const std::exception &e) {
858 strPrint = std::string("error: ") + e.what();
860 } catch (const UniValue &e) {
861 strPrint = std::string("error code: ") + e["code"].getValStr() +
862 " message: " + e["message"].getValStr();
864 } catch (...) {
865 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
866 throw;
867 }
868
869 if (strPrint != "") {
870 tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
871 }
872
873 return nRet;
874}
875
876int main(int argc, char *argv[]) {
878
879 try {
880 int ret = AppInitRawTx(argc, argv);
881 if (ret != CONTINUE_EXECUTION) {
882 return ret;
883 }
884 } catch (const std::exception &e) {
885 PrintExceptionContinue(&e, "AppInitRawTx()");
886 return EXIT_FAILURE;
887 } catch (...) {
888 PrintExceptionContinue(nullptr, "AppInitRawTx()");
889 return EXIT_FAILURE;
890 }
891
892 int ret = EXIT_FAILURE;
893 try {
895 } catch (const std::exception &e) {
896 PrintExceptionContinue(&e, "CommandLineRawTx()");
897 } catch (...) {
898 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
899 }
900
901 return ret;
902}
bool HelpRequested(const ArgsManager &args)
Definition args.cpp:732
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition args.cpp:737
ArgsManager gArgs
Definition args.cpp:38
bool IsSwitchChar(char c)
Definition args.h:47
int main(void)
Definition bench.c:157
static void OutputTxHash(const CTransaction &tx)
static const unsigned int N_SIGHASH_OPTS
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
static const int CONTINUE_EXECUTION
static const struct @0 sigHashOptions[N_SIGHASH_OPTS]
static std::string readStdin()
static int CommandLineRawTx(int argc, char *argv[], const CChainParams &chainParams)
static void OutputTxJSON(const CTransaction &tx)
static void RegisterSet(const std::string &strInput)
static void RegisterSetJson(const std::string &key, const std::string &rawJson)
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
static void MutateTxDelOutput(CMutableTransaction &tx, const std::string &strOutIdx)
const char * flagStr
static Amount ExtractAndValidateValue(const std::string &strValue)
static std::map< std::string, UniValue > registers
static void MutateTxAddOutAddr(CMutableTransaction &tx, const std::string &strInput, const CChainParams &chainParams)
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
static bool fCreateBlank
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
static void OutputTxHex(const CTransaction &tx)
static void RegisterLoad(const std::string &strInput)
static void MutateTxDelInput(CMutableTransaction &tx, const std::string &strInIdx)
static int AppInitRawTx(int argc, char *argv[])
static void MutateTxAddInput(CMutableTransaction &tx, const std::string &strInput)
int flags
static bool findSigHashFlags(SigHashType &sigHashType, const std::string &flagStr)
static void SetupBitcoinTxArgs(ArgsManager &argsman)
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal, const CChainParams &chainParams)
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
static void OutputTx(const CTransaction &tx)
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given BIP70 chain name.
const CChainParams & Params()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
@ ALLOW_ANY
Definition args.h:103
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition args.cpp:201
std::string GetHelpMessage() const
Get the help string.
Definition args.cpp:653
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition args.cpp:381
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition args.cpp:556
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition args.cpp:793
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:80
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:221
Abstract view on the open txout dataset.
Definition coins.h:163
An encapsulated secp256k1 private key.
Definition key.h:28
bool IsValid() const
Check whether this private key is valid.
Definition key.h:97
A mutable version of CTransaction.
std::vector< CTxOut > vout
std::vector< CTxIn > vin
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:20
An encapsulated public key.
Definition pubkey.h:31
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition pubkey.cpp:256
Serialized script, used inside transaction inputs and outputs.
Definition script.h:431
bool IsPayToScriptHash() const
Definition script.cpp:373
The basic transaction that is broadcasted on the network and contained in blocks.
static constexpr int32_t MAX_VERSION
const TxId GetId() const
static constexpr int32_t MIN_VERSION
An input of a transaction.
Definition transaction.h:59
An output of a transaction.
CScript scriptPubKey
Amount nValue
A UTXO entry.
Definition coins.h:28
CTxOut & GetTxOut()
Definition coins.h:49
bool IsSpent() const
Definition coins.h:47
Users of this module must hold an ECCVerifyHandle.
Definition pubkey.h:223
Fillable signing provider that keeps keys in an address->secret map.
A signature creator for transactions.
Definition sign.h:38
ECCVerifyHandle globalVerifyHandle
Signature hash type wrapper class.
Definition sighashtype.h:37
BaseSigHashType getBaseType() const
Definition sighashtype.h:64
SigHashType withForkId(bool forkId=true) const
Definition sighashtype.h:54
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool read(std::string_view raw)
std::string GetHex() const
Definition uint256.cpp:16
size_type size() const
Definition prevector.h:394
256-bit opaque blob.
Definition uint256.h:129
std::string FormatFullVersion()
std::string LicenseInfo()
Returns licensing information (for -version)
static const uint64_t MAX_TX_SIZE
The maximum allowed size for a transaction, in bytes.
Definition consensus.h:14
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
CScript ParseScript(const std::string &s)
Definition core_read.cpp:60
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
std::vector< uint8_t > ParseHexUV(const UniValue &v, const std::string &strName)
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
void SetupCurrencyUnitOptions(ArgsManager &argsman)
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition exception.cpp:38
void ECC_Start()
Initialize the elliptic curve support.
Definition key.cpp:434
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition key.cpp:451
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition key_io.cpp:174
CKey DecodeSecret(const std::string &str)
Definition key_io.cpp:77
bool error(const char *fmt, const Args &...args)
Definition logging.h:226
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition moneystr.cpp:37
FILE * fopen(const fs::path &p, const char *mode)
Definition fs.cpp:30
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
Amount AmountFromValue(const UniValue &value)
Definition util.cpp:55
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition script.h:24
static const int MAX_SCRIPT_SIZE
Definition script.h:33
@ OP_RETURN
Definition script.h:84
static const int MAX_PUBKEYS_PER_MULTISIG
Definition script.h:30
static std::string ToString(const CService &ip)
Definition db.h:37
@ SIGHASH_FORKID
Definition sighashtype.h:18
@ SIGHASH_ANYONECANPAY
Definition sighashtype.h:19
@ SIGHASH_ALL
Definition sighashtype.h:15
@ SIGHASH_NONE
Definition sighashtype.h:16
@ SIGHASH_SINGLE
Definition sighashtype.h:17
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition sign.cpp:198
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition sign.cpp:331
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition sign.cpp:275
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition standard.cpp:249
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition standard.cpp:244
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition standard.h:85
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition string.h:38
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:22
static constexpr Amount zero() noexcept
Definition amount.h:32
A BlockHash is a unqiue identifier for a block.
Definition blockhash.h:13
A TxId is the identifier of a transaction.
Definition txid.h:14
void SetupEnvironment()
Definition system.cpp:70
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
template std::vector< std::byte > ParseHex(std::string_view)
bool ParseInt64(std::string_view str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.