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