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