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