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  pos = 0;
439  } else {
440  // Extract and validate VALUE
441  value = ExtractAndValidateValue(strInput.substr(0, pos));
442  ++pos;
443  }
444 
445  // extract and validate DATA
446  const std::string strData{strInput.substr(pos, std::string::npos)};
447 
448  if (!IsHex(strData))
449  throw std::runtime_error("invalid TX output data");
450 
451  std::vector<unsigned char> data = ParseHex(strData);
452 
453  CTxOut txout(value, CScript() << OP_RETURN << data);
454  tx.vout.push_back(txout);
455 }
456 
457 static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
458 {
459  // separate VALUE:SCRIPT[:FLAGS]
460  std::vector<std::string> vStrInputParts;
461  boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
462  if (vStrInputParts.size() < 2)
463  throw std::runtime_error("TX output missing separator");
464 
465  // Extract and validate VALUE
466  CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
467 
468  // extract and validate script
469  std::string strScript = vStrInputParts[1];
470  CScript scriptPubKey = ParseScript(strScript);
471 
472  // Extract FLAGS
473  bool bSegWit = false;
474  bool bScriptHash = false;
475  if (vStrInputParts.size() == 3) {
476  std::string flags = vStrInputParts.back();
477  bSegWit = (flags.find('W') != std::string::npos);
478  bScriptHash = (flags.find('S') != std::string::npos);
479  }
480 
481  if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
482  throw std::runtime_error(strprintf(
483  "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
484  }
485 
486  if (bSegWit) {
487  scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey));
488  }
489  if (bScriptHash) {
490  if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
491  throw std::runtime_error(strprintf(
492  "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
493  }
494  scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
495  }
496 
497  // construct TxOut, append to transaction output list
498  CTxOut txout(value, scriptPubKey);
499  tx.vout.push_back(txout);
500 }
501 
502 static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
503 {
504  // parse requested deletion index
505  int64_t inIdx;
506  if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size())) {
507  throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
508  }
509 
510  // delete input from transaction
511  tx.vin.erase(tx.vin.begin() + inIdx);
512 }
513 
514 static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
515 {
516  // parse requested deletion index
517  int64_t outIdx;
518  if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >= static_cast<int64_t>(tx.vout.size())) {
519  throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
520  }
521 
522  // delete output from transaction
523  tx.vout.erase(tx.vout.begin() + outIdx);
524 }
525 
526 static const unsigned int N_SIGHASH_OPTS = 7;
527 static const struct {
528  const char *flagStr;
529  int flags;
531  {"DEFAULT", SIGHASH_DEFAULT},
532  {"ALL", SIGHASH_ALL},
533  {"NONE", SIGHASH_NONE},
534  {"SINGLE", SIGHASH_SINGLE},
535  {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
536  {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
537  {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
538 };
539 
540 static bool findSighashFlags(int& flags, const std::string& flagStr)
541 {
542  flags = 0;
543 
544  for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
545  if (flagStr == sighashOptions[i].flagStr) {
546  flags = sighashOptions[i].flags;
547  return true;
548  }
549  }
550 
551  return false;
552 }
553 
554 static CAmount AmountFromValue(const UniValue& value)
555 {
556  if (!value.isNum() && !value.isStr())
557  throw std::runtime_error("Amount is not a number or string");
558  CAmount amount;
559  if (!ParseFixedPoint(value.getValStr(), 8, &amount))
560  throw std::runtime_error("Invalid amount");
561  if (!MoneyRange(amount))
562  throw std::runtime_error("Amount out of range");
563  return amount;
564 }
565 
566 static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
567 {
568  int nHashType = SIGHASH_ALL;
569 
570  if (flagStr.size() > 0)
571  if (!findSighashFlags(nHashType, flagStr))
572  throw std::runtime_error("unknown sighash flag/sign option");
573 
574  // mergedTx will end up with all the signatures; it
575  // starts as a clone of the raw tx:
576  CMutableTransaction mergedTx{tx};
577  const CMutableTransaction txv{tx};
578  CCoinsView viewDummy;
579  CCoinsViewCache view(&viewDummy);
580 
581  if (!registers.count("privatekeys"))
582  throw std::runtime_error("privatekeys register variable must be set.");
583  FillableSigningProvider tempKeystore;
584  UniValue keysObj = registers["privatekeys"];
585 
586  for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
587  if (!keysObj[kidx].isStr())
588  throw std::runtime_error("privatekey not a std::string");
589  CKey key = DecodeSecret(keysObj[kidx].getValStr());
590  if (!key.IsValid()) {
591  throw std::runtime_error("privatekey not valid");
592  }
593  tempKeystore.AddKey(key);
594  }
595 
596  // Add previous txouts given in the RPC call:
597  if (!registers.count("prevtxs"))
598  throw std::runtime_error("prevtxs register variable must be set.");
599  UniValue prevtxsObj = registers["prevtxs"];
600  {
601  for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
602  UniValue prevOut = prevtxsObj[previdx];
603  if (!prevOut.isObject())
604  throw std::runtime_error("expected prevtxs internal object");
605 
606  std::map<std::string, UniValue::VType> types = {
607  {"txid", UniValue::VSTR},
608  {"vout", UniValue::VNUM},
609  {"scriptPubKey", UniValue::VSTR},
610  };
611  if (!prevOut.checkObject(types))
612  throw std::runtime_error("prevtxs internal object typecheck fail");
613 
614  uint256 txid;
615  if (!ParseHashStr(prevOut["txid"].get_str(), txid)) {
616  throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')");
617  }
618 
619  const int nOut = prevOut["vout"].get_int();
620  if (nOut < 0)
621  throw std::runtime_error("vout cannot be negative");
622 
623  COutPoint out(txid, nOut);
624  std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
625  CScript scriptPubKey(pkData.begin(), pkData.end());
626 
627  {
628  const Coin& coin = view.AccessCoin(out);
629  if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
630  std::string err("Previous output scriptPubKey mismatch:\n");
631  err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
632  ScriptToAsmStr(scriptPubKey);
633  throw std::runtime_error(err);
634  }
635  Coin newcoin;
636  newcoin.out.scriptPubKey = scriptPubKey;
637  newcoin.out.nValue = MAX_MONEY;
638  if (prevOut.exists("amount")) {
639  newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
640  }
641  newcoin.nHeight = 1;
642  view.AddCoin(out, std::move(newcoin), true);
643  }
644 
645  // if redeemScript given and private keys given,
646  // add redeemScript to the tempKeystore so it can be signed:
647  if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
648  prevOut.exists("redeemScript")) {
649  UniValue v = prevOut["redeemScript"];
650  std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
651  CScript redeemScript(rsData.begin(), rsData.end());
652  tempKeystore.AddCScript(redeemScript);
653  }
654  }
655  }
656 
657  const FillableSigningProvider& keystore = tempKeystore;
658 
659  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
660 
661  // Sign what we can:
662  for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
663  CTxIn& txin = mergedTx.vin[i];
664  const Coin& coin = view.AccessCoin(txin.prevout);
665  if (coin.IsSpent()) {
666  continue;
667  }
668  const CScript& prevPubKey = coin.out.scriptPubKey;
669  const CAmount& amount = coin.out.nValue;
670 
671  SignatureData sigdata = DataFromTransaction(mergedTx, i, coin.out);
672  // Only sign SIGHASH_SINGLE if there's a corresponding output:
673  if (!fHashSingle || (i < mergedTx.vout.size()))
674  ProduceSignature(keystore, MutableTransactionSignatureCreator(&mergedTx, i, amount, nHashType), prevPubKey, sigdata);
675 
676  if (amount == MAX_MONEY && !sigdata.scriptWitness.IsNull()) {
677  throw std::runtime_error(strprintf("Missing amount for CTxOut with scriptPubKey=%s", HexStr(prevPubKey)));
678  }
679 
680  UpdateInput(txin, sigdata);
681  }
682 
683  tx = mergedTx;
684 }
685 
687 {
689 
690 public:
692  ECC_Start();
693  }
695  ECC_Stop();
696  }
697 };
698 
699 static void MutateTx(CMutableTransaction& tx, const std::string& command,
700  const std::string& commandVal)
701 {
702  std::unique_ptr<Secp256k1Init> ecc;
703 
704  if (command == "nversion")
705  MutateTxVersion(tx, commandVal);
706  else if (command == "locktime")
707  MutateTxLocktime(tx, commandVal);
708  else if (command == "replaceable") {
709  MutateTxRBFOptIn(tx, commandVal);
710  }
711 
712  else if (command == "delin")
713  MutateTxDelInput(tx, commandVal);
714  else if (command == "in")
715  MutateTxAddInput(tx, commandVal);
716 
717  else if (command == "delout")
718  MutateTxDelOutput(tx, commandVal);
719  else if (command == "outaddr")
720  MutateTxAddOutAddr(tx, commandVal);
721  else if (command == "outpubkey") {
722  ecc.reset(new Secp256k1Init());
723  MutateTxAddOutPubKey(tx, commandVal);
724  } else if (command == "outmultisig") {
725  ecc.reset(new Secp256k1Init());
726  MutateTxAddOutMultiSig(tx, commandVal);
727  } else if (command == "outscript")
728  MutateTxAddOutScript(tx, commandVal);
729  else if (command == "outdata")
730  MutateTxAddOutData(tx, commandVal);
731 
732  else if (command == "sign") {
733  ecc.reset(new Secp256k1Init());
734  MutateTxSign(tx, commandVal);
735  }
736 
737  else if (command == "load")
738  RegisterLoad(commandVal);
739 
740  else if (command == "set")
741  RegisterSet(commandVal);
742 
743  else
744  throw std::runtime_error("unknown command");
745 }
746 
747 static void OutputTxJSON(const CTransaction& tx)
748 {
749  UniValue entry(UniValue::VOBJ);
750  TxToUniv(tx, uint256(), entry);
751 
752  std::string jsonOutput = entry.write(4);
753  tfm::format(std::cout, "%s\n", jsonOutput);
754 }
755 
756 static void OutputTxHash(const CTransaction& tx)
757 {
758  std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
759 
760  tfm::format(std::cout, "%s\n", strHexHash);
761 }
762 
763 static void OutputTxHex(const CTransaction& tx)
764 {
765  std::string strHex = EncodeHexTx(tx);
766 
767  tfm::format(std::cout, "%s\n", strHex);
768 }
769 
770 static void OutputTx(const CTransaction& tx)
771 {
772  if (gArgs.GetBoolArg("-json", false))
773  OutputTxJSON(tx);
774  else if (gArgs.GetBoolArg("-txid", false))
775  OutputTxHash(tx);
776  else
777  OutputTxHex(tx);
778 }
779 
780 static std::string readStdin()
781 {
782  char buf[4096];
783  std::string ret;
784 
785  while (!feof(stdin)) {
786  size_t bread = fread(buf, 1, sizeof(buf), stdin);
787  ret.append(buf, bread);
788  if (bread < sizeof(buf))
789  break;
790  }
791 
792  if (ferror(stdin))
793  throw std::runtime_error("error reading stdin");
794 
795  return TrimString(ret);
796 }
797 
798 static int CommandLineRawTx(int argc, char* argv[])
799 {
800  std::string strPrint;
801  int nRet = 0;
802  try {
803  // Skip switches; Permit common stdin convention "-"
804  while (argc > 1 && IsSwitchChar(argv[1][0]) &&
805  (argv[1][1] != 0)) {
806  argc--;
807  argv++;
808  }
809 
811  int startArg;
812 
813  if (!fCreateBlank) {
814  // require at least one param
815  if (argc < 2)
816  throw std::runtime_error("too few parameters");
817 
818  // param: hex-encoded bitcoin transaction
819  std::string strHexTx(argv[1]);
820  if (strHexTx == "-") // "-" implies standard input
821  strHexTx = readStdin();
822 
823  if (!DecodeHexTx(tx, strHexTx, true))
824  throw std::runtime_error("invalid transaction encoding");
825 
826  startArg = 2;
827  } else
828  startArg = 1;
829 
830  for (int i = startArg; i < argc; i++) {
831  std::string arg = argv[i];
832  std::string key, value;
833  size_t eqpos = arg.find('=');
834  if (eqpos == std::string::npos)
835  key = arg;
836  else {
837  key = arg.substr(0, eqpos);
838  value = arg.substr(eqpos + 1);
839  }
840 
841  MutateTx(tx, key, value);
842  }
843 
844  OutputTx(CTransaction(tx));
845  }
846  catch (const std::exception& e) {
847  strPrint = std::string("error: ") + e.what();
848  nRet = EXIT_FAILURE;
849  }
850  catch (...) {
851  PrintExceptionContinue(nullptr, "CommandLineRawTx()");
852  throw;
853  }
854 
855  if (strPrint != "") {
856  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
857  }
858  return nRet;
859 }
860 
861 int main(int argc, char* argv[])
862 {
864 
865  try {
866  int ret = AppInitRawTx(argc, argv);
867  if (ret != CONTINUE_EXECUTION)
868  return ret;
869  }
870  catch (const std::exception& e) {
871  PrintExceptionContinue(&e, "AppInitRawTx()");
872  return EXIT_FAILURE;
873  } catch (...) {
874  PrintExceptionContinue(nullptr, "AppInitRawTx()");
875  return EXIT_FAILURE;
876  }
877 
878  int ret = EXIT_FAILURE;
879  try {
880  ret = CommandLineRawTx(argc, argv);
881  }
882  catch (const std::exception& e) {
883  PrintExceptionContinue(&e, "CommandLineRawTx()");
884  } catch (...) {
885  PrintExceptionContinue(nullptr, "CommandLineRawTx()");
886  }
887  return ret;
888 }
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:366
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:600
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:398
fs.h
findSighashFlags
static bool findSighashFlags(int &flags, const std::string &flagStr)
Definition: bitcoin-tx.cpp:540
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:27
flags
int flags
Definition: bitcoin-tx.cpp:529
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:668
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:368
IsHex
bool IsHex(const std::string &str)
Definition: strencodings.cpp:61
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
disable validation
Definition: system.h:172
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:987
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:494
SetupEnvironment
void SetupEnvironment()
Definition: system.cpp:1301
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:699
MoneyRange
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
CommandLineRawTx
static int CommandLineRawTx(int argc, char *argv[])
Definition: bitcoin-tx.cpp:798
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:770
RegisterSet
static void RegisterSet(const std::string &strInput)
Definition: bitcoin-tx.cpp:135
readStdin
static std::string readStdin()
Definition: bitcoin-tx.cpp:780
HelpRequested
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:737
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:742
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:279
rbf.h
CTxIn::SEQUENCE_FINAL
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:80
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:151
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:369
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:756
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:148
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:747
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:354
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:152
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:640
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:514
IsSwitchChar
bool IsSwitchChar(char c)
Definition: system.h:130
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:861
ArgsManager::ParseParameters
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:297
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:686
MutateTxAddOutScript
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:457
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:87
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:367
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:164
translation.h
flagStr
const char * flagStr
Definition: bitcoin-tx.cpp:528
MutateTxLocktime
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:210
Secp256k1Init::Secp256k1Init
Secp256k1Init()
Definition: bitcoin-tx.cpp:691
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:763
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:322
OptionsCategory::COMMANDS
@ COMMANDS
PrintExceptionContinue
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:779
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:694
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:364
MutateTxDelInput
static void MutateTxDelInput(CMutableTransaction &tx, const std::string &strInIdx)
Definition: bitcoin-tx.cpp:502
WitnessV0ScriptHash
Definition: standard.h:102
AmountFromValue
static CAmount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:554
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:511
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:688
MutateTxSign
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
Definition: bitcoin-tx.cpp:566
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:526
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