Bitcoin ABC 0.34.2
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 uint32_t newVersion;
248 if (!ParseUInt32(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 = 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 auto txid{TxId::FromHex(vStrInputParts[0])};
281 if (!txid) {
282 throw std::runtime_error("invalid TX input txid");
283 }
284
285 static const unsigned int minTxOutSz = 9;
286 static const unsigned int maxVout = MAX_TX_SIZE / minTxOutSz;
287
288 // extract and validate vout
289 const std::string &strVout = vStrInputParts[1];
290 int64_t vout;
291 if (!ParseInt64(strVout, &vout) || vout < 0 ||
292 vout > static_cast<int64_t>(maxVout)) {
293 throw std::runtime_error("invalid TX input vout '" + strVout + "'");
294 }
295
296 // extract the optional sequence number
297 uint32_t nSequenceIn = std::numeric_limits<unsigned int>::max();
298 if (vStrInputParts.size() > 2) {
299 nSequenceIn = std::stoul(vStrInputParts[2]);
300 }
301
302 // append to transaction input list
303 CTxIn txin(*txid, vout, CScript(), nSequenceIn);
304 tx.vin.push_back(txin);
305}
306
308 const std::string &strInput,
309 const CChainParams &chainParams) {
310 // Separate into VALUE:ADDRESS
311 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
312
313 if (vStrInputParts.size() != 2) {
314 throw std::runtime_error("TX output missing or too many separators");
315 }
316
317 // Extract and validate VALUE
318 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
319
320 // extract and validate ADDRESS
321 const std::string &strAddr = vStrInputParts[1];
322 CTxDestination destination = DecodeDestination(strAddr, chainParams);
323 if (!IsValidDestination(destination)) {
324 throw std::runtime_error("invalid TX output address");
325 }
326 CScript scriptPubKey = GetScriptForDestination(destination);
327
328 // construct TxOut, append to transaction output list
329 CTxOut txout(value, scriptPubKey);
330 tx.vout.push_back(txout);
331}
332
334 const std::string &strInput) {
335 // Separate into VALUE:PUBKEY[:FLAGS]
336 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
337
338 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
339 throw std::runtime_error("TX output missing or too many separators");
340 }
341
342 // Extract and validate VALUE
343 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
344
345 // Extract and validate PUBKEY
346 CPubKey pubkey(ParseHex(vStrInputParts[1]));
347 if (!pubkey.IsFullyValid()) {
348 throw std::runtime_error("invalid TX output pubkey");
349 }
350
351 CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
352
353 // Extract and validate FLAGS
354 bool bScriptHash = false;
355 if (vStrInputParts.size() == 3) {
356 const std::string &flags = vStrInputParts[2];
357 bScriptHash = (flags.find('S') != std::string::npos);
358 }
359
360 if (bScriptHash) {
361 // Get the ID for the script, and then construct a P2SH destination for
362 // it.
363 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
364 }
365
366 // construct TxOut, append to transaction output list
367 CTxOut txout(value, scriptPubKey);
368 tx.vout.push_back(txout);
369}
370
372 const std::string &strInput) {
373 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
374 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
375
376 // Check that there are enough parameters
377 if (vStrInputParts.size() < 3) {
378 throw std::runtime_error("Not enough multisig parameters");
379 }
380
381 // Extract and validate VALUE
382 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
383
384 // Extract REQUIRED
385 uint32_t required = stoul(vStrInputParts[1]);
386
387 // Extract NUMKEYS
388 uint32_t numkeys = stoul(vStrInputParts[2]);
389
390 // Validate there are the correct number of pubkeys
391 if (vStrInputParts.size() < numkeys + 3) {
392 throw std::runtime_error("incorrect number of multisig pubkeys");
393 }
394
395 if (required < 1 || required > MAX_PUBKEYS_PER_MULTISIG || numkeys < 1 ||
396 numkeys > MAX_PUBKEYS_PER_MULTISIG || numkeys < required) {
397 throw std::runtime_error("multisig parameter mismatch. Required " +
398 ToString(required) + " of " +
399 ToString(numkeys) + "signatures.");
400 }
401
402 // extract and validate PUBKEYs
403 std::vector<CPubKey> pubkeys;
404 for (int pos = 1; pos <= int(numkeys); pos++) {
405 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
406 if (!pubkey.IsFullyValid()) {
407 throw std::runtime_error("invalid TX output pubkey");
408 }
409
410 pubkeys.push_back(pubkey);
411 }
412
413 // Extract FLAGS
414 bool bScriptHash = false;
415 if (vStrInputParts.size() == numkeys + 4) {
416 const std::string &flags = vStrInputParts.back();
417 bScriptHash = (flags.find('S') != std::string::npos);
418 } else if (vStrInputParts.size() > numkeys + 4) {
419 // Validate that there were no more parameters passed
420 throw std::runtime_error("Too many parameters");
421 }
422
423 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
424
425 if (bScriptHash) {
426 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
427 throw std::runtime_error(
428 strprintf("redeemScript exceeds size limit: %d > %d",
429 scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
430 }
431 // Get the ID for the script, and then construct a P2SH destination for
432 // it.
433 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
434 }
435
436 // construct TxOut, append to transaction output list
437 CTxOut txout(value, scriptPubKey);
438 tx.vout.push_back(txout);
439}
440
442 const std::string &strInput) {
443 Amount value = Amount::zero();
444
445 // separate [VALUE:]DATA in string
446 size_t pos = strInput.find(':');
447
448 if (pos == 0) {
449 throw std::runtime_error("TX output value not specified");
450 }
451
452 if (pos == std::string::npos) {
453 pos = 0;
454 } else {
455 // Extract and validate VALUE
456 value = ExtractAndValidateValue(strInput.substr(0, pos));
457 ++pos;
458 }
459
460 // extract and validate DATA
461 const std::string strData{strInput.substr(pos, std::string::npos)};
462
463 if (!IsHex(strData)) {
464 throw std::runtime_error("invalid TX output data");
465 }
466
467 std::vector<uint8_t> data = ParseHex(strData);
468
469 CTxOut txout(value, CScript() << OP_RETURN << data);
470 tx.vout.push_back(txout);
471}
472
474 const std::string &strInput) {
475 // separate VALUE:SCRIPT[:FLAGS]
476 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
477 if (vStrInputParts.size() < 2) {
478 throw std::runtime_error("TX output missing separator");
479 }
480
481 // Extract and validate VALUE
482 Amount value = ExtractAndValidateValue(vStrInputParts[0]);
483
484 // extract and validate script
485 const std::string &strScript = vStrInputParts[1];
486 CScript scriptPubKey = ParseScript(strScript);
487
488 // Extract FLAGS
489 bool bScriptHash = false;
490 if (vStrInputParts.size() == 3) {
491 const std::string &flags = vStrInputParts.back();
492 bScriptHash = (flags.find('S') != std::string::npos);
493 }
494
495 if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
496 throw std::runtime_error(strprintf("script exceeds size limit: %d > %d",
497 scriptPubKey.size(),
499 }
500
501 if (bScriptHash) {
502 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
503 throw std::runtime_error(
504 strprintf("redeemScript exceeds size limit: %d > %d",
505 scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
506 }
507 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
508 }
509
510 // construct TxOut, append to transaction output list
511 CTxOut txout(value, scriptPubKey);
512 tx.vout.push_back(txout);
513}
514
516 const std::string &strInIdx) {
517 // parse requested deletion index
518 int64_t inIdx;
519 if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 ||
520 inIdx >= static_cast<int64_t>(tx.vin.size())) {
521 throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
522 }
523
524 // delete input from transaction
525 tx.vin.erase(tx.vin.begin() + inIdx);
526}
527
529 const std::string &strOutIdx) {
530 // parse requested deletion index
531 int64_t outIdx;
532 if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 ||
533 outIdx >= static_cast<int64_t>(tx.vout.size())) {
534 throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
535 }
536
537 // delete output from transaction
538 tx.vout.erase(tx.vout.begin() + outIdx);
539}
540
541static const unsigned int N_SIGHASH_OPTS = 12;
542static const struct {
543 const char *flagStr;
544 int flags;
546 {"ALL", SIGHASH_ALL},
547 {"NONE", SIGHASH_NONE},
548 {"SINGLE", SIGHASH_SINGLE},
549 {"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
550 {"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
551 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
552 {"ALL|FORKID", SIGHASH_ALL | SIGHASH_FORKID},
553 {"NONE|FORKID", SIGHASH_NONE | SIGHASH_FORKID},
554 {"SINGLE|FORKID", SIGHASH_SINGLE | SIGHASH_FORKID},
555 {"ALL|FORKID|ANYONECANPAY",
557 {"NONE|FORKID|ANYONECANPAY",
559 {"SINGLE|FORKID|ANYONECANPAY",
562
563static bool findSigHashFlags(SigHashType &sigHashType,
564 const std::string &flagStr) {
565 sigHashType = SigHashType();
566
567 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
568 if (flagStr == sigHashOptions[i].flagStr) {
569 sigHashType = SigHashType(sigHashOptions[i].flags);
570 return true;
571 }
572 }
573
574 return false;
575}
576
577static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr) {
578 SigHashType sigHashType = SigHashType().withForkId();
579
580 if ((flagStr.size() > 0) && !findSigHashFlags(sigHashType, flagStr)) {
581 throw std::runtime_error("unknown sighash flag/sign option");
582 }
583
584 // mergedTx will end up with all the signatures; it
585 // starts as a clone of the raw tx:
586 CMutableTransaction mergedTx{tx};
587 const CMutableTransaction txv{tx};
588
589 CCoinsView viewDummy;
590 CCoinsViewCache view(&viewDummy);
591
592 if (!registers.count("privatekeys")) {
593 throw std::runtime_error("privatekeys register variable must be set.");
594 }
595
596 FillableSigningProvider tempKeystore;
597 UniValue keysObj = registers["privatekeys"];
598
599 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
600 if (!keysObj[kidx].isStr()) {
601 throw std::runtime_error("privatekey not a std::string");
602 }
603
604 CKey key = DecodeSecret(keysObj[kidx].getValStr());
605 if (!key.IsValid()) {
606 throw std::runtime_error("privatekey not valid");
607 }
608 tempKeystore.AddKey(key);
609 }
610
611 // Add previous txouts given in the RPC call:
612 if (!registers.count("prevtxs")) {
613 throw std::runtime_error("prevtxs register variable must be set.");
614 }
615
616 UniValue prevtxsObj = registers["prevtxs"];
617
618 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
619 const UniValue &prevOut = prevtxsObj[previdx];
620 if (!prevOut.isObject()) {
621 throw std::runtime_error("expected prevtxs internal object");
622 }
623
624 std::map<std::string, UniValue::VType> types = {
625 {"txid", UniValue::VSTR},
626 {"vout", UniValue::VNUM},
627 {"scriptPubKey", UniValue::VSTR}};
628 if (!prevOut.checkObject(types)) {
629 throw std::runtime_error("prevtxs internal object typecheck fail");
630 }
631
632 auto txid{TxId::FromHex(prevOut["txid"].get_str())};
633 if (!txid) {
634 throw std::runtime_error("txid must be hexadecimal string (not '" +
635 prevOut["txid"].get_str() + "')");
636 }
637
638 const int nOut = prevOut["vout"].getInt<int>();
639 if (nOut < 0) {
640 throw std::runtime_error("vout cannot be negative");
641 }
642
643 COutPoint out(*txid, nOut);
644 std::vector<uint8_t> pkData(
645 ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
646 CScript scriptPubKey(pkData.begin(), pkData.end());
647
648 {
649 const Coin &coin = view.AccessCoin(out);
650 if (!coin.IsSpent() &&
651 coin.GetTxOut().scriptPubKey != scriptPubKey) {
652 std::string err("Previous output scriptPubKey mismatch:\n");
653 err = err + ScriptToAsmStr(coin.GetTxOut().scriptPubKey) +
654 "\nvs:\n" + ScriptToAsmStr(scriptPubKey);
655 throw std::runtime_error(err);
656 }
657
658 CTxOut txout;
659 txout.scriptPubKey = scriptPubKey;
660 txout.nValue = Amount::zero();
661 if (prevOut.exists("amount")) {
662 txout.nValue = AmountFromValue(prevOut["amount"]);
663 }
664
665 view.AddCoin(out, Coin(txout, 1, false), true);
666 }
667
668 // If redeemScript given and private keys given, add redeemScript to the
669 // tempKeystore so it can be signed:
670 if (scriptPubKey.IsPayToScriptHash() &&
671 prevOut.exists("redeemScript")) {
672 UniValue v = prevOut["redeemScript"];
673 std::vector<uint8_t> rsData(ParseHexUV(v, "redeemScript"));
674 CScript redeemScript(rsData.begin(), rsData.end());
675 tempKeystore.AddCScript(redeemScript);
676 }
677 }
678
679 const FillableSigningProvider &keystore = tempKeystore;
680
681 // Sign what we can:
682 for (size_t i = 0; i < mergedTx.vin.size(); i++) {
683 CTxIn &txin = mergedTx.vin[i];
684 const Coin &coin = view.AccessCoin(txin.prevout);
685 if (coin.IsSpent()) {
686 continue;
687 }
688
689 const CScript &prevPubKey = coin.GetTxOut().scriptPubKey;
690 const Amount amount = coin.GetTxOut().nValue;
691
692 SignatureData sigdata =
693 DataFromTransaction(mergedTx, i, coin.GetTxOut());
694 // Only sign SIGHASH_SINGLE if there's a corresponding output:
695 if ((sigHashType.getBaseType() != BaseSigHashType::SINGLE) ||
696 (i < mergedTx.vout.size())) {
697 ProduceSignature(keystore,
699 mergedTx, i, amount, sigHashType),
700 prevPubKey, sigdata);
701 }
702
703 UpdateInput(txin, sigdata);
704 }
705
706 tx = mergedTx;
707}
708
710public:
713};
714
715static void MutateTx(CMutableTransaction &tx, const std::string &command,
716 const std::string &commandVal,
717 const CChainParams &chainParams) {
718 std::unique_ptr<Secp256k1Init> ecc;
719
720 if (command == "nversion") {
721 MutateTxVersion(tx, commandVal);
722 } else if (command == "locktime") {
723 MutateTxLocktime(tx, commandVal);
724 } else if (command == "delin") {
725 MutateTxDelInput(tx, commandVal);
726 } else if (command == "in") {
727 MutateTxAddInput(tx, commandVal);
728 } else if (command == "delout") {
729 MutateTxDelOutput(tx, commandVal);
730 } else if (command == "outaddr") {
731 MutateTxAddOutAddr(tx, commandVal, chainParams);
732 } else if (command == "outpubkey") {
733 ecc.reset(new Secp256k1Init());
734 MutateTxAddOutPubKey(tx, commandVal);
735 } else if (command == "outmultisig") {
736 ecc.reset(new Secp256k1Init());
737 MutateTxAddOutMultiSig(tx, commandVal);
738 } else if (command == "outscript") {
739 MutateTxAddOutScript(tx, commandVal);
740 } else if (command == "outdata") {
741 MutateTxAddOutData(tx, commandVal);
742 } else if (command == "sign") {
743 ecc.reset(new Secp256k1Init());
744 MutateTxSign(tx, commandVal);
745 } else if (command == "load") {
746 RegisterLoad(commandVal);
747 } else if (command == "set") {
748 RegisterSet(commandVal);
749 } else {
750 throw std::runtime_error("unknown command");
751 }
752}
753
754static void OutputTxJSON(const CTransaction &tx) {
756 TxToUniv(tx, BlockHash(), entry);
757
758 std::string jsonOutput = entry.write(4);
759 tfm::format(std::cout, "%s\n", jsonOutput);
760}
761
762static void OutputTxHash(const CTransaction &tx) {
763 // the hex-encoded transaction id.
764 std::string strHexHash = tx.GetId().GetHex();
765
766 tfm::format(std::cout, "%s\n", strHexHash);
767}
768
769static void OutputTxHex(const CTransaction &tx) {
770 std::string strHex = EncodeHexTx(tx);
771
772 tfm::format(std::cout, "%s\n", strHex);
773}
774
775static void OutputTx(const CTransaction &tx) {
776 if (gArgs.GetBoolArg("-json", false)) {
777 OutputTxJSON(tx);
778 } else if (gArgs.GetBoolArg("-txid", false)) {
779 OutputTxHash(tx);
780 } else {
781 OutputTxHex(tx);
782 }
783}
784
785static std::string readStdin() {
786 char buf[4096];
787 std::string ret;
788
789 while (!feof(stdin)) {
790 size_t bread = fread(buf, 1, sizeof(buf), stdin);
791 ret.append(buf, bread);
792 if (bread < sizeof(buf)) {
793 break;
794 }
795 }
796
797 if (ferror(stdin)) {
798 throw std::runtime_error("error reading stdin");
799 }
800
801 return TrimString(ret);
802}
803
804static int CommandLineRawTx(int argc, char *argv[],
805 const CChainParams &chainParams) {
806 std::string strPrint;
807 int nRet = 0;
808 try {
809 // Skip switches; Permit common stdin convention "-"
810 while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
811 argc--;
812 argv++;
813 }
814
816 int startArg;
817
818 if (!fCreateBlank) {
819 // require at least one param
820 if (argc < 2) {
821 throw std::runtime_error("too few parameters");
822 }
823
824 // param: hex-encoded bitcoin transaction
825 std::string strHexTx(argv[1]);
826
827 // "-" implies standard input
828 if (strHexTx == "-") {
829 strHexTx = readStdin();
830 }
831
832 if (!DecodeHexTx(tx, strHexTx)) {
833 throw std::runtime_error("invalid transaction encoding");
834 }
835
836 startArg = 2;
837 } else {
838 startArg = 1;
839 }
840
841 for (int i = startArg; i < argc; i++) {
842 std::string arg = argv[i];
843 std::string key, value;
844 size_t eqpos = arg.find('=');
845 if (eqpos == std::string::npos) {
846 key = arg;
847 } else {
848 key = arg.substr(0, eqpos);
849 value = arg.substr(eqpos + 1);
850 }
851
852 MutateTx(tx, key, value, chainParams);
853 }
854
855 OutputTx(CTransaction(tx));
856 } catch (const std::exception &e) {
857 strPrint = std::string("error: ") + e.what();
858 nRet = EXIT_FAILURE;
859 } catch (const UniValue &e) {
860 strPrint = std::string("error code: ") + e["code"].getValStr() +
861 " message: " + e["message"].getValStr();
862 nRet = EXIT_FAILURE;
863 } catch (...) {
864 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
865 throw;
866 }
867
868 if (strPrint != "") {
869 tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
870 }
871
872 return nRet;
873}
874
875int main(int argc, char *argv[]) {
877
878 try {
879 int ret = AppInitRawTx(argc, argv);
880 if (ret != CONTINUE_EXECUTION) {
881 return ret;
882 }
883 } catch (const std::exception &e) {
884 PrintExceptionContinue(&e, "AppInitRawTx()");
885 return EXIT_FAILURE;
886 } catch (...) {
887 PrintExceptionContinue(nullptr, "AppInitRawTx()");
888 return EXIT_FAILURE;
889 }
890
891 int ret = EXIT_FAILURE;
892 try {
893 ret = CommandLineRawTx(argc, argv, Params());
894 } catch (const std::exception &e) {
895 PrintExceptionContinue(&e, "CommandLineRawTx()");
896 } catch (...) {
897 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
898 }
899
900 return ret;
901}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: addresstype.h:54
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:875
static void OutputTxHash(const CTransaction &tx)
Definition: bitcoin-tx.cpp:762
static const unsigned int N_SIGHASH_OPTS
Definition: bitcoin-tx.cpp:541
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
Definition: bitcoin-tx.cpp:577
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:785
static int CommandLineRawTx(int argc, char *argv[], const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:804
static void OutputTxJSON(const CTransaction &tx)
Definition: bitcoin-tx.cpp:754
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:528
const char * flagStr
Definition: bitcoin-tx.cpp:543
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:307
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:333
static bool fCreateBlank
Definition: bitcoin-tx.cpp:42
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:441
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:245
static void OutputTxHex(const CTransaction &tx)
Definition: bitcoin-tx.cpp:769
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:515
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:544
static bool findSigHashFlags(SigHashType &sigHashType, const std::string &flagStr)
Definition: bitcoin-tx.cpp:563
static void SetupBitcoinTxArgs(ArgsManager &argsman)
Definition: bitcoin-tx.cpp:48
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:371
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal, const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:715
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:473
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:258
static void OutputTx(const CTransaction &tx)
Definition: bitcoin-tx.cpp:775
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:357
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:97
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:199
Abstract view on the open txout dataset.
Definition: coins.h:303
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 uint32_t MIN_VERSION
Definition: transaction.h:199
static constexpr uint32_t MAX_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:31
CTxOut & GetTxOut()
Definition: coins.h:52
bool IsSpent() const
Definition: coins.h:50
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:39
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
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:174
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:247
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:107
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:222
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:41
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:1113
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:63
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:156
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:84
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:69
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:27
static const int MAX_SCRIPT_SIZE
Definition: script.h:36
@ OP_RETURN
Definition: script.h:90
static const int MAX_PUBKEYS_PER_MULTISIG
Definition: script.h:33
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:210
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:343
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:287
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition: solver.cpp:148
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:143
Definition: amount.h:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
static std::optional< TxId > FromHex(std::string_view str)
Definition: txid.h:18
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:1203
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.
bool ParseUInt32(std::string_view str, uint32_t *out)
Convert decimal string to unsigned 32-bit integer with strict parse error feedback.