Bitcoin ABC 0.30.5
P2P Digital Currency
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
43static void SetupBitcoinTxArgs(ArgsManager &argsman) {
44 SetupHelpOptions(argsman);
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;
117 if (!gArgs.ParseParameters(argc, argv, 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")) {
140 strUsage += FormatParagraph(LicenseInfo());
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";
149 strUsage += gArgs.GetHelpMessage();
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
187 RegisterSetJson(key, valStr);
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
228 RegisterSetJson(key, valStr);
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) {
242 int64_t newVersion;
243 if (!ParseInt64(cmdVal, &newVersion) ||
244 newVersion < CTransaction::MIN_VERSION ||
245 newVersion > CTransaction::MAX_VERSION) {
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) {
255 int64_t newLocktime;
256 if (!ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL ||
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
315 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
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
340 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
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
379 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
380
381 // Extract REQUIRED
382 uint32_t required = stoul(vStrInputParts[1]);
383
384 // Extract NUMKEYS
385 uint32_t numkeys = stoul(vStrInputParts[2]);
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
392 if (required < 1 || required > MAX_PUBKEYS_PER_MULTISIG || numkeys < 1 ||
393 numkeys > MAX_PUBKEYS_PER_MULTISIG || numkeys < required) {
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
479 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
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
515 int64_t inIdx;
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
528 int64_t outIdx;
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:
583 CMutableTransaction mergedTx{tx};
584 const CMutableTransaction txv{tx};
585
586 CCoinsView viewDummy;
587 CCoinsViewCache view(&viewDummy);
588
589 if (!registers.count("privatekeys")) {
590 throw std::runtime_error("privatekeys register variable must be set.");
591 }
592
593 FillableSigningProvider tempKeystore;
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++) {
616 UniValue prevOut = prevtxsObj[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");
652 err = err + ScriptToAsmStr(coin.GetTxOut().scriptPubKey) +
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
678 const FillableSigningProvider &keystore = tempKeystore;
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 =
692 DataFromTransaction(mergedTx, i, coin.GetTxOut());
693 // Only sign SIGHASH_SINGLE if there's a corresponding output:
694 if ((sigHashType.getBaseType() != BaseSigHashType::SINGLE) ||
695 (i < mergedTx.vout.size())) {
696 ProduceSignature(keystore,
698 &mergedTx, i, amount, sigHashType),
699 prevPubKey, sigdata);
700 }
701
702 UpdateInput(txin, sigdata);
703 }
704
705 tx = mergedTx;
706}
707
710
711public:
714};
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") {
722 MutateTxVersion(tx, commandVal);
723 } else if (command == "locktime") {
724 MutateTxLocktime(tx, commandVal);
725 } else if (command == "delin") {
726 MutateTxDelInput(tx, commandVal);
727 } else if (command == "in") {
728 MutateTxAddInput(tx, commandVal);
729 } else if (command == "delout") {
730 MutateTxDelOutput(tx, commandVal);
731 } else if (command == "outaddr") {
732 MutateTxAddOutAddr(tx, commandVal, chainParams);
733 } else if (command == "outpubkey") {
734 ecc.reset(new Secp256k1Init());
735 MutateTxAddOutPubKey(tx, commandVal);
736 } else if (command == "outmultisig") {
737 ecc.reset(new Secp256k1Init());
738 MutateTxAddOutMultiSig(tx, commandVal);
739 } else if (command == "outscript") {
740 MutateTxAddOutScript(tx, commandVal);
741 } else if (command == "outdata") {
742 MutateTxAddOutData(tx, commandVal);
743 } else if (command == "sign") {
744 ecc.reset(new Secp256k1Init());
745 MutateTxSign(tx, commandVal);
746 } else if (command == "load") {
747 RegisterLoad(commandVal);
748 } else if (command == "set") {
749 RegisterSet(commandVal);
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 == "-") {
830 strHexTx = readStdin();
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
856 OutputTx(CTransaction(tx));
857 } catch (const std::exception &e) {
858 strPrint = std::string("error: ") + e.what();
859 nRet = EXIT_FAILURE;
860 } catch (const UniValue &e) {
861 strPrint = std::string("error code: ") + e["code"].getValStr() +
862 " message: " + e["message"].getValStr();
863 nRet = EXIT_FAILURE;
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 {
894 ret = CommandLineRawTx(argc, argv, Params());
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(int argc, char *argv[])
Definition: bitcoin-tx.cpp:876
static void OutputTxHash(const CTransaction &tx)
Definition: bitcoin-tx.cpp:763
static const unsigned int N_SIGHASH_OPTS
Definition: bitcoin-tx.cpp:538
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
Definition: bitcoin-tx.cpp:574
static const int CONTINUE_EXECUTION
Definition: bitcoin-tx.cpp:39
static const struct @0 sigHashOptions[N_SIGHASH_OPTS]
static std::string readStdin()
Definition: bitcoin-tx.cpp:786
static int CommandLineRawTx(int argc, char *argv[], const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:805
static void OutputTxJSON(const CTransaction &tx)
Definition: bitcoin-tx.cpp:755
static void RegisterSet(const std::string &strInput)
Definition: bitcoin-tx.cpp:176
static void RegisterSetJson(const std::string &key, const std::string &rawJson)
Definition: bitcoin-tx.cpp:165
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-tx.cpp:41
static void MutateTxDelOutput(CMutableTransaction &tx, const std::string &strOutIdx)
Definition: bitcoin-tx.cpp:525
const char * flagStr
Definition: bitcoin-tx.cpp:540
static Amount ExtractAndValidateValue(const std::string &strValue)
Definition: bitcoin-tx.cpp:231
static std::map< std::string, UniValue > registers
Definition: bitcoin-tx.cpp:38
static void MutateTxAddOutAddr(CMutableTransaction &tx, const std::string &strInput, const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:304
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:330
static bool fCreateBlank
Definition: bitcoin-tx.cpp:37
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:438
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:240
static void OutputTxHex(const CTransaction &tx)
Definition: bitcoin-tx.cpp:770
static void RegisterLoad(const std::string &strInput)
Definition: bitcoin-tx.cpp:190
static void MutateTxDelInput(CMutableTransaction &tx, const std::string &strInIdx)
Definition: bitcoin-tx.cpp:512
static int AppInitRawTx(int argc, char *argv[])
Definition: bitcoin-tx.cpp:111
static void MutateTxAddInput(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:265
int flags
Definition: bitcoin-tx.cpp:541
static bool findSigHashFlags(SigHashType &sigHashType, const std::string &flagStr)
Definition: bitcoin-tx.cpp:560
static void SetupBitcoinTxArgs(ArgsManager &argsman)
Definition: bitcoin-tx.cpp:43
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:368
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal, const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:716
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:470
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:253
static void OutputTx(const CTransaction &tx)
Definition: bitcoin-tx.cpp:776
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given BIP70 chain name.
Definition: chainparams.cpp:51
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:19
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
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:620
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
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:104
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:196
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.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
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
static constexpr int32_t MAX_VERSION
Definition: transaction.h:199
static constexpr int32_t MIN_VERSION
Definition: transaction.h:199
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
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.
virtual bool AddCScript(const CScript &redeemScript)
virtual bool AddKey(const CKey &key)
A signature creator for transactions.
Definition: sign.h:38
ECCVerifyHandle globalVerifyHandle
Definition: bitcoin-tx.cpp:709
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
bool checkObject(const std::map< std::string, UniValue::VType > &memberTypes) const
Definition: univalue.cpp:157
@ VOBJ
Definition: univalue.h:31
@ VSTR
Definition: univalue.h:33
@ VNUM
Definition: univalue.h:34
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
size_t size() const
Definition: univalue.h:92
bool read(std::string_view raw)
Int getInt() const
Definition: univalue.h:157
bool exists(const std::string &key) const
Definition: univalue.h:99
bool isObject() const
Definition: univalue.h:111
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)
Definition: core_write.cpp:217
CScript ParseScript(const std::string &s)
Definition: core_read.cpp:60
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:197
std::vector< uint8_t > ParseHexUV(const UniValue &v, const std::string &strName)
Definition: core_read.cpp:257
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:248
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:106
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:169
void SetupCurrencyUnitOptions(ArgsManager &argsman)
Definition: currencyunit.cpp:9
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.
Definition: tinyformat.h:1112
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
@ 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
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
Definition: amount.h:19
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...
Definition: tinyformat.h:1202
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.