Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
bitcoin-tx.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <bitcoin-build-config.h> // IWYU pragma: keep
6
7#include <chainparamsbase.h>
8#include <clientversion.h>
9#include <coins.h>
10#include <common/args.h>
11#include <common/license_info.h>
12#include <common/system.h>
13#include <compat/compat.h>
14#include <consensus/amount.h>
15#include <consensus/consensus.h>
16#include <core_io.h>
17#include <crypto/sha256.h>
18#include <key_io.h>
19#include <policy/policy.h>
21#include <script/script.h>
22#include <script/sign.h>
24#include <univalue.h>
25#include <util/exception.h>
26#include <util/fs.h>
27#include <util/moneystr.h>
28#include <util/rbf.h>
29#include <util/strencodings.h>
30#include <util/string.h>
31#include <util/translation.h>
32
33#include <cstdio>
34#include <functional>
35#include <memory>
36
38using util::ToString;
41
42static bool fCreateBlank;
43static std::map<std::string,UniValue> registers;
44static const int CONTINUE_EXECUTION=-1;
45
47
49{
51
52 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
53 argsman.AddArg("-create", "Create new, empty TX.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
54 argsman.AddArg("-json", "Select JSON output", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
55 argsman.AddArg("-txid", "Output only the hex-encoded transaction id of the resultant transaction.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
57
58 argsman.AddArg("delin=N", "Delete input N from TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
59 argsman.AddArg("delout=N", "Delete output N from TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
60 argsman.AddArg("in=TXID:VOUT[:SEQUENCE_NUMBER]", "Add input to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
61 argsman.AddArg("locktime=N", "Set TX lock time to N", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
62 argsman.AddArg("nversion=N", "Set TX version to N", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
63 argsman.AddArg("outaddr=VALUE:ADDRESS", "Add address-based output to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
64 argsman.AddArg("outdata=[VALUE:]DATA", "Add data-based output to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
65 argsman.AddArg("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", "Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. "
66 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
67 "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
68 argsman.AddArg("outpubkey=VALUE:PUBKEY[:FLAGS]", "Add pay-to-pubkey output to TX. "
69 "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. "
70 "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
71 argsman.AddArg("outscript=VALUE:SCRIPT[:FLAGS]", "Add raw script output to TX. "
72 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
73 "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
74 argsman.AddArg("replaceable(=N)", "Sets Replace-By-Fee (RBF) opt-in sequence number for input N. "
75 "If N is not provided, the command attempts to opt-in all available inputs for RBF. "
76 "If the transaction has no inputs, this option is ignored.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
77 argsman.AddArg("sign=SIGHASH-FLAGS", "Add zero or more signatures to transaction. "
78 "This command requires JSON registers:"
79 "prevtxs=JSON object, "
80 "privatekeys=JSON object. "
81 "See signrawtransactionwithkey docs for format of sighash flags, JSON objects.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
82
83 argsman.AddArg("load=NAME:FILENAME", "Load JSON file FILENAME into register NAME", ArgsManager::ALLOW_ANY, OptionsCategory::REGISTER_COMMANDS);
84 argsman.AddArg("set=NAME:JSON-STRING", "Set register NAME to given JSON-STRING", ArgsManager::ALLOW_ANY, OptionsCategory::REGISTER_COMMANDS);
85}
86
87//
88// This function returns either one of EXIT_ codes when it's expected to stop the process or
89// CONTINUE_EXECUTION when it's expected to continue further.
90//
91static int AppInitRawTx(int argc, char* argv[])
92{
94 std::string error;
95 if (!gArgs.ParseParameters(argc, argv, error)) {
96 tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
97 return EXIT_FAILURE;
98 }
99
100 // Check for chain settings (Params() calls are only valid after this clause)
101 try {
103 } catch (const std::exception& e) {
104 tfm::format(std::cerr, "Error: %s\n", e.what());
105 return EXIT_FAILURE;
106 }
107
108 fCreateBlank = gArgs.GetBoolArg("-create", false);
109
110 if (argc < 2 || HelpRequested(gArgs) || gArgs.GetBoolArg("-version", false)) {
111 // First part of help message is specific to this utility
112 std::string strUsage = CLIENT_NAME " bitcoin-tx utility version " + FormatFullVersion() + "\n";
113
114 if (gArgs.GetBoolArg("-version", false)) {
116 } else {
117 strUsage += "\n"
118 "The bitcoin-tx tool is used for creating and modifying bitcoin transactions.\n\n"
119 "bitcoin-tx can be used with \"<hex-tx> [commands]\" to update a hex-encoded bitcoin transaction, or with \"-create [commands]\" to create a hex-encoded bitcoin transaction.\n"
120 "\n"
121 "Usage: bitcoin-tx [options] <hex-tx> [commands]\n"
122 "or: bitcoin-tx [options] -create [commands]\n"
123 "\n";
125 }
126
127 tfm::format(std::cout, "%s", strUsage);
128
129 if (argc < 2) {
130 tfm::format(std::cerr, "Error: too few parameters\n");
131 return EXIT_FAILURE;
132 }
133 return EXIT_SUCCESS;
134 }
135 return CONTINUE_EXECUTION;
136}
137
138static void RegisterSetJson(const std::string& key, const std::string& rawJson)
139{
140 UniValue val;
141 if (!val.read(rawJson)) {
142 std::string strErr = "Cannot parse JSON for key " + key;
143 throw std::runtime_error(strErr);
144 }
145
146 registers[key] = val;
147}
148
149static void RegisterSet(const std::string& strInput)
150{
151 // separate NAME:VALUE in string
152 size_t pos = strInput.find(':');
153 if ((pos == std::string::npos) ||
154 (pos == 0) ||
155 (pos == (strInput.size() - 1)))
156 throw std::runtime_error("Register input requires NAME:VALUE");
157
158 std::string key = strInput.substr(0, pos);
159 std::string valStr = strInput.substr(pos + 1, std::string::npos);
160
162}
163
164static void RegisterLoad(const std::string& strInput)
165{
166 // separate NAME:FILENAME in string
167 size_t pos = strInput.find(':');
168 if ((pos == std::string::npos) ||
169 (pos == 0) ||
170 (pos == (strInput.size() - 1)))
171 throw std::runtime_error("Register load requires NAME:FILENAME");
172
173 std::string key = strInput.substr(0, pos);
174 std::string filename = strInput.substr(pos + 1, std::string::npos);
175
176 FILE *f = fsbridge::fopen(filename.c_str(), "r");
177 if (!f) {
178 std::string strErr = "Cannot open file " + filename;
179 throw std::runtime_error(strErr);
180 }
181
182 // load file chunks into one big buffer
183 std::string valStr;
184 while ((!feof(f)) && (!ferror(f))) {
185 char buf[4096];
186 int bread = fread(buf, 1, sizeof(buf), f);
187 if (bread <= 0)
188 break;
189
190 valStr.insert(valStr.size(), buf, bread);
191 }
192
193 int error = ferror(f);
194 fclose(f);
195
196 if (error) {
197 std::string strErr = "Error reading file " + filename;
198 throw std::runtime_error(strErr);
199 }
200
201 // evaluate as JSON buffer register
203}
204
205static CAmount ExtractAndValidateValue(const std::string& strValue)
206{
207 if (std::optional<CAmount> parsed = ParseMoney(strValue)) {
208 return parsed.value();
209 } else {
210 throw std::runtime_error("invalid TX output value");
211 }
212}
213
214static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
215{
216 const auto ver{ToIntegral<uint32_t>(cmdVal)};
218 throw std::runtime_error("Invalid TX version requested: '" + cmdVal + "'");
219 }
220 tx.version = *ver;
221}
222
223static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
224{
226 if (!locktime) {
227 throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal + "'");
228 }
229 tx.nLockTime = *locktime;
230}
231
232static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
233{
234 const auto idx{ToIntegral<uint32_t>(strInIdx)};
235 if (strInIdx != "" && (!idx || *idx >= tx.vin.size())) {
236 throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
237 }
238
239 // set the nSequence to MAX_INT - 2 (= RBF opt in flag)
240 uint32_t cnt{0};
241 for (CTxIn& txin : tx.vin) {
242 if (strInIdx == "" || cnt == *idx) {
243 if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
244 txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
245 }
246 }
247 ++cnt;
248 }
249}
250
251template <typename T>
252static T TrimAndParse(const std::string& int_str, const std::string& err)
253{
254 const auto parsed{ToIntegral<T>(TrimStringView(int_str))};
255 if (!parsed.has_value()) {
256 throw std::runtime_error(err + " '" + int_str + "'");
257 }
258 return parsed.value();
259}
260
261static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
262{
263 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
264
265 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
266 throw std::runtime_error("Invalid format, expected in=TXID:VOUT[:SEQUENCE_NUMBER]");
267 }
268
269 // extract and validate TXID
270 auto txid{Txid::FromHex(vStrInputParts[0])};
271 if (!txid) {
272 throw std::runtime_error("invalid TX input txid");
273 }
274
275 static const unsigned int minTxOutSz = 9;
276 static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz);
277
278 // extract and validate vout
279 const std::string& strVout = vStrInputParts[1];
280 const auto vout{ToIntegral<uint32_t>(strVout)};
281 if (!vout || *vout > maxVout) {
282 throw std::runtime_error("invalid TX input vout '" + strVout + "'");
283 }
284
285 // extract the optional sequence number
287 if (vStrInputParts.size() > 2) {
288 nSequenceIn = TrimAndParse<uint32_t>(vStrInputParts.at(2), "invalid TX sequence id");
289 }
290
291 // append to transaction input list
292 CTxIn txin{*txid, *vout, CScript{}, nSequenceIn};
293 tx.vin.push_back(txin);
294}
295
296static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
297{
298 // Separate into VALUE:ADDRESS
299 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
300
301 if (vStrInputParts.size() != 2)
302 throw std::runtime_error("TX output missing or too many separators");
303
304 // Extract and validate VALUE
306
307 // extract and validate ADDRESS
308 const std::string& strAddr = vStrInputParts[1];
310 if (!IsValidDestination(destination)) {
311 throw std::runtime_error("invalid TX output address");
312 }
313 CScript scriptPubKey = GetScriptForDestination(destination);
314
315 // construct TxOut, append to transaction output list
316 CTxOut txout(value, scriptPubKey);
317 tx.vout.push_back(txout);
318}
319
320static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
321{
322 // Separate into VALUE:PUBKEY[:FLAGS]
323 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
324
325 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
326 throw std::runtime_error("TX output missing or too many separators");
327
328 // Extract and validate VALUE
330
331 // Extract and validate PUBKEY
332 CPubKey pubkey(ParseHex(vStrInputParts[1]));
333 if (!pubkey.IsFullyValid())
334 throw std::runtime_error("invalid TX output pubkey");
335 CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
336
337 // Extract and validate FLAGS
338 bool bSegWit = false;
339 bool bScriptHash = false;
340 if (vStrInputParts.size() == 3) {
341 const std::string& flags = vStrInputParts[2];
342 bSegWit = (flags.find('W') != std::string::npos);
343 bScriptHash = (flags.find('S') != std::string::npos);
344 }
345
346 if (bSegWit) {
347 if (!pubkey.IsCompressed()) {
348 throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
349 }
350 // Build a P2WPKH script
351 scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkey));
352 }
353 if (bScriptHash) {
354 // Get the ID for the script, and then construct a P2SH destination for it.
355 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
356 }
357
358 // construct TxOut, append to transaction output list
359 CTxOut txout(value, scriptPubKey);
360 tx.vout.push_back(txout);
361}
362
363static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
364{
365 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
366 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
367
368 // Check that there are enough parameters
369 if (vStrInputParts.size()<3)
370 throw std::runtime_error("Not enough multisig parameters");
371
372 // Extract and validate VALUE
374
375 // Extract REQUIRED
376 const uint32_t required{TrimAndParse<uint32_t>(vStrInputParts.at(1), "invalid multisig required number")};
377
378 // Extract NUMKEYS
379 const uint32_t numkeys{TrimAndParse<uint32_t>(vStrInputParts.at(2), "invalid multisig total number")};
380
381 // Validate there are the correct number of pubkeys
382 if (vStrInputParts.size() < numkeys + 3)
383 throw std::runtime_error("incorrect number of multisig pubkeys");
384
386 throw std::runtime_error("multisig parameter mismatch. Required " \
387 + ToString(required) + " of " + ToString(numkeys) + "signatures.");
388
389 // extract and validate PUBKEYs
390 std::vector<CPubKey> pubkeys;
391 for(int pos = 1; pos <= int(numkeys); pos++) {
392 CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
393 if (!pubkey.IsFullyValid())
394 throw std::runtime_error("invalid TX output pubkey");
395 pubkeys.push_back(pubkey);
396 }
397
398 // Extract FLAGS
399 bool bSegWit = false;
400 bool bScriptHash = false;
401 if (vStrInputParts.size() == numkeys + 4) {
402 const std::string& flags = vStrInputParts.back();
403 bSegWit = (flags.find('W') != std::string::npos);
404 bScriptHash = (flags.find('S') != std::string::npos);
405 }
406 else if (vStrInputParts.size() > numkeys + 4) {
407 // Validate that there were no more parameters passed
408 throw std::runtime_error("Too many parameters");
409 }
410
411 CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
412
413 if (bSegWit) {
414 for (const CPubKey& pubkey : pubkeys) {
415 if (!pubkey.IsCompressed()) {
416 throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
417 }
418 }
419 // Build a P2WSH with the multisig script
420 scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey));
421 }
422 if (bScriptHash) {
423 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
424 throw std::runtime_error(strprintf(
425 "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
426 }
427 // Get the ID for the script, and then construct a P2SH destination for it.
428 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
429 }
430
431 // construct TxOut, append to transaction output list
432 CTxOut txout(value, scriptPubKey);
433 tx.vout.push_back(txout);
434}
435
436static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
437{
438 CAmount value = 0;
439
440 // separate [VALUE:]DATA in string
441 size_t pos = strInput.find(':');
442
443 if (pos==0)
444 throw std::runtime_error("TX output value not specified");
445
446 if (pos == std::string::npos) {
447 pos = 0;
448 } else {
449 // Extract and validate VALUE
450 value = ExtractAndValidateValue(strInput.substr(0, pos));
451 ++pos;
452 }
453
454 // extract and validate DATA
455 const std::string strData{strInput.substr(pos, std::string::npos)};
456
457 if (!IsHex(strData))
458 throw std::runtime_error("invalid TX output data");
459
460 std::vector<unsigned char> data = ParseHex(strData);
461
462 CTxOut txout(value, CScript() << OP_RETURN << data);
463 tx.vout.push_back(txout);
464}
465
466static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
467{
468 std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
469 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
470 throw std::runtime_error("Invalid format, expected outscript=VALUE:SCRIPT[:FLAGS]");
471 }
472
473 // Extract and validate VALUE
475
476 // extract and validate script
477 const std::string& strScript = vStrInputParts[1];
478 CScript scriptPubKey = ParseScript(strScript);
479
480 // Extract FLAGS
481 bool bSegWit = false;
482 bool bScriptHash = false;
483 if (vStrInputParts.size() == 3) {
484 const std::string& flags = vStrInputParts.back();
485 bSegWit = (flags.find('W') != std::string::npos);
486 bScriptHash = (flags.find('S') != std::string::npos);
487 }
488
489 if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
490 throw std::runtime_error(strprintf(
491 "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
492 }
493
494 if (bSegWit) {
495 scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey));
496 }
497 if (bScriptHash) {
498 if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
499 throw std::runtime_error(strprintf(
500 "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
501 }
502 scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
503 }
504
505 // construct TxOut, append to transaction output list
506 CTxOut txout(value, scriptPubKey);
507 tx.vout.push_back(txout);
508}
509
510static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
511{
512 const auto idx{ToIntegral<uint32_t>(strInIdx)};
513 if (!idx || idx >= tx.vin.size()) {
514 throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
515 }
516 tx.vin.erase(tx.vin.begin() + *idx);
517}
518
519static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
520{
521 const auto idx{ToIntegral<uint32_t>(strOutIdx)};
522 if (!idx || idx >= tx.vout.size()) {
523 throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
524 }
525 tx.vout.erase(tx.vout.begin() + *idx);
526}
527
528static const unsigned int N_SIGHASH_OPTS = 7;
529static const struct {
530 const char *flagStr;
531 int flags;
533 {"DEFAULT", SIGHASH_DEFAULT},
534 {"ALL", SIGHASH_ALL},
535 {"NONE", SIGHASH_NONE},
536 {"SINGLE", SIGHASH_SINGLE},
537 {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
538 {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
539 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
541
542static bool findSighashFlags(int& flags, const std::string& flagStr)
543{
544 flags = 0;
545
546 for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
547 if (flagStr == sighashOptions[i].flagStr) {
548 flags = sighashOptions[i].flags;
549 return true;
550 }
551 }
552
553 return false;
554}
555
556static CAmount AmountFromValue(const UniValue& value)
557{
558 if (!value.isNum() && !value.isStr())
559 throw std::runtime_error("Amount is not a number or string");
560 int64_t amount;
561 if (!ParseFixedPoint(value.getValStr(), 8, &amount))
562 throw std::runtime_error("Invalid amount");
563 if (!MoneyRange(amount))
564 throw std::runtime_error("Amount out of range");
565 return amount;
566}
567
568static std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
569{
570 std::string strHex;
571 if (v.isStr())
572 strHex = v.getValStr();
573 if (!IsHex(strHex))
574 throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
575 return ParseHex(strHex);
576}
577
578static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
579{
581
582 if (flagStr.size() > 0)
584 throw std::runtime_error("unknown sighash flag/sign option");
585
586 // mergedTx will end up with all the signatures; it
587 // starts as a clone of the raw tx:
589 const CMutableTransaction txv{tx};
591
592 if (!registers.contains("privatekeys"))
593 throw std::runtime_error("privatekeys register variable must be set.");
595 UniValue keysObj = registers["privatekeys"];
596
597 for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
598 if (!keysObj[kidx].isStr())
599 throw std::runtime_error("privatekey not a std::string");
600 CKey key = DecodeSecret(keysObj[kidx].getValStr());
601 if (!key.IsValid()) {
602 throw std::runtime_error("privatekey not valid");
603 }
604 tempKeystore.AddKey(key);
605 }
606
607 // Add previous txouts given in the RPC call:
608 if (!registers.contains("prevtxs"))
609 throw std::runtime_error("prevtxs register variable must be set.");
610 UniValue prevtxsObj = registers["prevtxs"];
611 {
612 for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
614 if (!prevOut.isObject())
615 throw std::runtime_error("expected prevtxs internal object");
616
617 std::map<std::string, UniValue::VType> types = {
618 {"txid", UniValue::VSTR},
619 {"vout", UniValue::VNUM},
620 {"scriptPubKey", UniValue::VSTR},
621 };
622 if (!prevOut.checkObject(types))
623 throw std::runtime_error("prevtxs internal object typecheck fail");
624
625 auto txid{Txid::FromHex(prevOut["txid"].get_str())};
626 if (!txid) {
627 throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')");
628 }
629
630 const int nOut = prevOut["vout"].getInt<int>();
631 if (nOut < 0)
632 throw std::runtime_error("vout cannot be negative");
633
634 COutPoint out(*txid, nOut);
635 std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
636 CScript scriptPubKey(pkData.begin(), pkData.end());
637
638 {
639 const Coin& coin = view.AccessCoin(out);
640 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
641 std::string err("Previous output scriptPubKey mismatch:\n");
642 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
643 ScriptToAsmStr(scriptPubKey);
644 throw std::runtime_error(err);
645 }
647 newcoin.out.scriptPubKey = scriptPubKey;
648 newcoin.out.nValue = MAX_MONEY;
649 if (prevOut.exists("amount")) {
650 newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
651 }
652 newcoin.nHeight = 1;
653 view.AddCoin(out, std::move(newcoin), true);
654 }
655
656 // if redeemScript given and private keys given,
657 // add redeemScript to the tempKeystore so it can be signed:
658 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
659 prevOut.exists("redeemScript")) {
660 UniValue v = prevOut["redeemScript"];
661 std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
662 CScript redeemScript(rsData.begin(), rsData.end());
663 if (!tempKeystore.AddCScript(redeemScript)) {
664 throw std::runtime_error(strprintf("Error adding redeemscript=%s", HexStr(redeemScript)));
665 }
666 }
667 }
668 }
669
671
672 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
673
674 // Sign what we can:
675 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
676 CTxIn& txin = mergedTx.vin[i];
677 const Coin& coin = view.AccessCoin(txin.prevout);
678 if (coin.IsSpent()) {
679 continue;
680 }
681 const CScript& prevPubKey = coin.out.scriptPubKey;
682 const CAmount& amount = coin.out.nValue;
683
684 SignatureData sigdata = DataFromTransaction(mergedTx, i, coin.out);
685 // Only sign SIGHASH_SINGLE if there's a corresponding output:
686 if (!fHashSingle || (i < mergedTx.vout.size()))
688
689 if (amount == MAX_MONEY && !sigdata.scriptWitness.IsNull()) {
690 throw std::runtime_error(strprintf("Missing amount for CTxOut with scriptPubKey=%s", HexStr(prevPubKey)));
691 }
692
693 UpdateInput(txin, sigdata);
694 }
695
696 tx = mergedTx;
697}
698
699static void MutateTx(CMutableTransaction& tx, const std::string& command,
700 const std::string& commandVal)
701{
702 std::unique_ptr<ECC_Context> ecc;
703
704 if (command == "nversion")
706 else if (command == "locktime")
708 else if (command == "replaceable") {
710 }
711
712 else if (command == "delin")
714 else if (command == "in")
716
717 else if (command == "delout")
719 else if (command == "outaddr")
721 else if (command == "outpubkey") {
722 ecc.reset(new ECC_Context());
724 } else if (command == "outmultisig") {
725 ecc.reset(new ECC_Context());
727 } else if (command == "outscript")
729 else if (command == "outdata")
731
732 else if (command == "sign") {
733 ecc.reset(new ECC_Context());
735 }
736
737 else if (command == "load")
739
740 else if (command == "set")
742
743 else
744 throw std::runtime_error("unknown command");
745}
746
747static void OutputTxJSON(const CTransaction& tx)
748{
750 TxToUniv(tx, /*block_hash=*/uint256(), entry);
751
752 std::string jsonOutput = entry.write(4);
753 tfm::format(std::cout, "%s\n", jsonOutput);
754}
755
756static void OutputTxHash(const CTransaction& tx)
757{
758 std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
759
760 tfm::format(std::cout, "%s\n", strHexHash);
761}
762
763static void OutputTxHex(const CTransaction& tx)
764{
765 std::string strHex = EncodeHexTx(tx);
766
767 tfm::format(std::cout, "%s\n", strHex);
768}
769
770static void OutputTx(const CTransaction& tx)
771{
772 if (gArgs.GetBoolArg("-json", false))
773 OutputTxJSON(tx);
774 else if (gArgs.GetBoolArg("-txid", false))
775 OutputTxHash(tx);
776 else
777 OutputTxHex(tx);
778}
779
780static std::string readStdin()
781{
782 char buf[4096];
783 std::string ret;
784
785 while (!feof(stdin)) {
786 size_t bread = fread(buf, 1, sizeof(buf), stdin);
787 ret.append(buf, bread);
788 if (bread < sizeof(buf))
789 break;
790 }
791
792 if (ferror(stdin))
793 throw std::runtime_error("error reading stdin");
794
795 return TrimString(ret);
796}
797
798static int CommandLineRawTx(int argc, char* argv[])
799{
800 std::string strPrint;
801 int nRet = 0;
802 try {
803 // Skip switches; Permit common stdin convention "-"
804 while (argc > 1 && IsSwitchChar(argv[1][0]) &&
805 (argv[1][1] != 0)) {
806 argc--;
807 argv++;
808 }
809
811 int startArg;
812
813 if (!fCreateBlank) {
814 // require at least one param
815 if (argc < 2)
816 throw std::runtime_error("too few parameters");
817
818 // param: hex-encoded bitcoin transaction
819 std::string strHexTx(argv[1]);
820 if (strHexTx == "-") // "-" implies standard input
822
823 if (!DecodeHexTx(tx, strHexTx, true))
824 throw std::runtime_error("invalid transaction encoding");
825
826 startArg = 2;
827 } else
828 startArg = 1;
829
830 for (int i = startArg; i < argc; i++) {
831 std::string arg = argv[i];
832 std::string key, value;
833 size_t eqpos = arg.find('=');
834 if (eqpos == std::string::npos)
835 key = arg;
836 else {
837 key = arg.substr(0, eqpos);
838 value = arg.substr(eqpos + 1);
839 }
840
841 MutateTx(tx, key, value);
842 }
843
845 }
846 catch (const std::exception& e) {
847 strPrint = std::string("error: ") + e.what();
849 }
850 catch (...) {
851 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
852 throw;
853 }
854
855 if (strPrint != "") {
856 tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
857 }
858 return nRet;
859}
860
862{
865
866 try {
867 int ret = AppInitRawTx(argc, argv);
868 if (ret != CONTINUE_EXECUTION)
869 return ret;
870 }
871 catch (const std::exception& e) {
872 PrintExceptionContinue(&e, "AppInitRawTx()");
873 return EXIT_FAILURE;
874 } catch (...) {
875 PrintExceptionContinue(nullptr, "AppInitRawTx()");
876 return EXIT_FAILURE;
877 }
878
880 try {
882 }
883 catch (const std::exception& e) {
884 PrintExceptionContinue(&e, "CommandLineRawTx()");
885 } catch (...) {
886 PrintExceptionContinue(nullptr, "CommandLineRawTx()");
887 }
888 return ret;
889}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
bool HelpRequested(const ArgsManager &args)
Definition args.cpp:795
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition args.cpp:800
ArgsManager gArgs
Definition args.cpp:38
bool IsSwitchChar(char c)
Definition args.h:44
static bool findSighashFlags(int &flags, const std::string &flagStr)
static void OutputTxHash(const CTransaction &tx)
static const unsigned int N_SIGHASH_OPTS
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
static const int CONTINUE_EXECUTION
static std::string readStdin()
static void OutputTxJSON(const CTransaction &tx)
static void RegisterSet(const std::string &strInput)
static void RegisterSetJson(const std::string &key, const std::string &rawJson)
int ret
static CAmount ExtractAndValidateValue(const std::string &strValue)
static std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
static void MutateTxDelOutput(CMutableTransaction &tx, const std::string &strOutIdx)
const char * flagStr
static const struct @0 sighashOptions[N_SIGHASH_OPTS]
static CAmount AmountFromValue(const UniValue &value)
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal)
static T TrimAndParse(const std::string &int_str, const std::string &err)
SHA256AutoDetect()
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
static bool fCreateBlank
static void MutateTxRBFOptIn(CMutableTransaction &tx, const std::string &strInIdx)
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
static void MutateTxAddOutAddr(CMutableTransaction &tx, const std::string &strInput)
static int CommandLineRawTx(int argc, char *argv[])
const TranslateFn G_TRANSLATION_FUN
Translate string to current locale using Qt.
static void OutputTxHex(const CTransaction &tx)
static void RegisterLoad(const std::string &strInput)
static void MutateTxDelInput(CMutableTransaction &tx, const std::string &strInIdx)
static int AppInitRawTx(int argc, char *argv[])
static void MutateTxAddInput(CMutableTransaction &tx, const std::string &strInput)
int flags
static std::map< std::string, UniValue > registers
static void SetupBitcoinTxArgs(ArgsManager &argsman)
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
MAIN_FUNCTION
static void OutputTx(const CTransaction &tx)
SetupEnvironment()
Definition system.cpp:56
std::string strPrint
return EXIT_SUCCESS
const auto command
void SelectParams(const ChainType chain)
Sets the params returned by Params() to those for the given chain type.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
bool ParseParameters(int argc, const char *const argv[], std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition args.cpp:175
ChainType GetChainType() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type from the program arguments.
Definition args.cpp:893
@ ALLOW_ANY
disable validation
Definition args.h:109
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Definition args.cpp:560
std::string GetHelpMessage() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get the help string.
Definition args.cpp:703
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:437
An encapsulated private key.
Definition key.h:46
bool IsValid() const
Check whether this private key is valid.
Definition key.h:134
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:30
An encapsulated public key.
Definition pubkey.h:43
bool IsCompressed() const
Check whether this is a compressed public key.
Definition pubkey.h:209
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition pubkey.cpp:320
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
bool IsPayToScriptHash() const
Definition script.cpp:224
bool IsPayToWitnessScriptHash() const
Definition script.cpp:233
The basic transaction that is broadcasted on the network and contained in blocks.
const Txid & GetHash() const LIFETIMEBOUND
An input of a transaction.
Definition transaction.h:63
static constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition transaction.h:77
An output of a transaction.
CScript scriptPubKey
CAmount nValue
A UTXO entry.
Definition coins.h:46
CTxOut out
unspent transaction output
Definition coins.h:49
bool IsSpent() const
Either this coin never existed (see e.g.
Definition coins.h:94
static CoinsViewEmpty & Get()
Definition coins.cpp:29
RAII class initializing and deinitializing global state for elliptic curve support.
Definition key.h:364
Fillable signing provider that keeps keys in an address->secret map.
A signature creator for transactions.
Definition sign.h:54
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::string & getValStr() const
Definition univalue.h:68
bool isStr() const
Definition univalue.h:85
bool read(std::string_view json)
Parse JSON; set value to null on failure.
bool isNum() const
Definition univalue.h:86
size_type size() const
Definition prevector.h:247
static std::optional< transaction_identifier > FromHex(std::string_view hex)
256-bit opaque blob.
Definition uint256.h:196
std::string FormatFullVersion()
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
constexpr unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition consensus.h:15
constexpr int WITNESS_SCALE_FACTOR
Definition consensus.h:21
std::string EncodeHexTx(const CTransaction &tx)
Definition core_io.cpp:404
CScript ParseScript(const std::string &s)
Definition core_io.cpp:92
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
Definition core_io.cpp:225
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex, const CTxUndo *txundo, TxVerbosity verbosity, std::function< bool(const CTxOut &)> is_change_func)
Definition core_io.cpp:432
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
Definition core_io.cpp:359
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition exception.cpp:36
#define T(expected, seed, data)
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
@ SIGHASH_ANYONECANPAY
Definition interpreter.h:35
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition interpreter.h:37
@ SIGHASH_ALL
Definition interpreter.h:32
@ SIGHASH_NONE
Definition interpreter.h:33
@ SIGHASH_SINGLE
Definition interpreter.h:34
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition key_io.cpp:297
CKey DecodeSecret(const std::string &str)
Definition key_io.cpp:215
std::string LicenseInfo()
Returns licensing information (for -version)
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition moneystr.cpp:45
FILE * fopen(const fs::path &p, const char *mode)
Definition fs.cpp:23
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:153
std::string_view TrimStringView(std::string_view str LIFETIMEBOUND, std::string_view pattern=" \f\n\r\t\v")
Definition string.h:163
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition string.h:250
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition string.h:173
constexpr decltype(CTransaction::version) TX_MAX_STANDARD_VERSION
Definition policy.h:146
constexpr int MAX_SCRIPT_SIZE
Definition script.h:41
@ OP_RETURN
Definition script.h:112
constexpr unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition script.h:29
constexpr int MAX_PUBKEYS_PER_MULTISIG
Definition script.h:35
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:750
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition sign.cpp:923
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition sign.cpp:858
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
Definition solver.cpp:218
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition solver.cpp:213
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
A mutable version of CTransaction.
std::vector< CTxOut > vout
std::vector< CTxIn > vin
bool IsNull() const
Definition script.h:586
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
Definition sign.h:93
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
std::function< std::string(const char *)> TranslateFn
Translate a message to the native language of the user.
Definition translation.h:16
constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
Definition rbf.h:12
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool IsHex(std::string_view str)
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.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82