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