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