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