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