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