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