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