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> // trim_right
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) ||
236  newVersion < CTransaction::MIN_VERSION ||
237  newVersion > CTransaction::MAX_VERSION) {
238  throw std::runtime_error("Invalid TX version requested: '" + cmdVal +
239  "'");
240  }
241 
242  tx.nVersion = int(newVersion);
243 }
244 
246  const std::string &cmdVal) {
247  int64_t newLocktime;
248  if (!ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL ||
249  newLocktime > 0xffffffffLL) {
250  throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal +
251  "'");
252  }
253 
254  tx.nLockTime = (unsigned int)newLocktime;
255 }
256 
258  const std::string &strInput) {
259  std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
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 = SplitString(strInput, ':');
301 
302  if (vStrInputParts.size() != 2) {
303  throw std::runtime_error("TX output missing or too many separators");
304  }
305 
306  // Extract and validate VALUE
307  Amount value = ExtractAndValidateValue(vStrInputParts[0]);
308 
309  // extract and validate ADDRESS
310  std::string strAddr = vStrInputParts[1];
311  CTxDestination destination = DecodeDestination(strAddr, chainParams);
312  if (!IsValidDestination(destination)) {
313  throw std::runtime_error("invalid TX output address");
314  }
315  CScript scriptPubKey = GetScriptForDestination(destination);
316 
317  // construct TxOut, append to transaction output list
318  CTxOut txout(value, scriptPubKey);
319  tx.vout.push_back(txout);
320 }
321 
323  const std::string &strInput) {
324  // Separate into VALUE:PUBKEY[:FLAGS]
325  std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
326 
327  if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) {
328  throw std::runtime_error("TX output missing or too many separators");
329  }
330 
331  // Extract and validate VALUE
332  Amount value = ExtractAndValidateValue(vStrInputParts[0]);
333 
334  // Extract and validate PUBKEY
335  CPubKey pubkey(ParseHex(vStrInputParts[1]));
336  if (!pubkey.IsFullyValid()) {
337  throw std::runtime_error("invalid TX output pubkey");
338  }
339 
340  CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
341 
342  // Extract and validate FLAGS
343  bool bScriptHash = false;
344  if (vStrInputParts.size() == 3) {
345  std::string flags = vStrInputParts[2];
346  bScriptHash = (flags.find('S') != std::string::npos);
347  }
348 
349  if (bScriptHash) {
350  // Get the ID for the script, and then construct a P2SH destination for
351  // it.
352  scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
353  }
354 
355  // construct TxOut, append to transaction output list
356  CTxOut txout(value, scriptPubKey);
357  tx.vout.push_back(txout);
358 }
359 
361  const std::string &strInput) {
362  // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
363  std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
364 
365  // Check that there are enough parameters
366  if (vStrInputParts.size() < 3) {
367  throw std::runtime_error("Not enough multisig parameters");
368  }
369 
370  // Extract and validate VALUE
371  Amount value = ExtractAndValidateValue(vStrInputParts[0]);
372 
373  // Extract REQUIRED
374  uint32_t required = stoul(vStrInputParts[1]);
375 
376  // Extract NUMKEYS
377  uint32_t numkeys = stoul(vStrInputParts[2]);
378 
379  // Validate there are the correct number of pubkeys
380  if (vStrInputParts.size() < numkeys + 3) {
381  throw std::runtime_error("incorrect number of multisig pubkeys");
382  }
383 
384  if (required < 1 || required > MAX_PUBKEYS_PER_MULTISIG || numkeys < 1 ||
385  numkeys > MAX_PUBKEYS_PER_MULTISIG || numkeys < required) {
386  throw std::runtime_error("multisig parameter mismatch. Required " +
387  ToString(required) + " of " +
388  ToString(numkeys) + "signatures.");
389  }
390 
391  // extract and validate PUBKEYs
392  std::vector<CPubKey> pubkeys;
393  for (int pos = 1; pos <= int(numkeys); pos++) {
394  CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
395  if (!pubkey.IsFullyValid()) {
396  throw std::runtime_error("invalid TX output pubkey");
397  }
398 
399  pubkeys.push_back(pubkey);
400  }
401 
402  // Extract FLAGS
403  bool bScriptHash = false;
404  if (vStrInputParts.size() == numkeys + 4) {
405  std::string flags = vStrInputParts.back();
406  bScriptHash = (flags.find('S') != std::string::npos);
407  } else if (vStrInputParts.size() > numkeys + 4) {
408  // Validate that there were no more parameters passed
409  throw std::runtime_error("Too many parameters");
410  }
411 
412  CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
413 
414  if (bScriptHash) {
415  if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
416  throw std::runtime_error(
417  strprintf("redeemScript exceeds size limit: %d > %d",
418  scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
419  }
420  // Get the ID for the script, and then construct a P2SH destination for
421  // it.
422  scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
423  }
424 
425  // construct TxOut, append to transaction output list
426  CTxOut txout(value, scriptPubKey);
427  tx.vout.push_back(txout);
428 }
429 
431  const std::string &strInput) {
432  Amount value = Amount::zero();
433 
434  // separate [VALUE:]DATA in string
435  size_t pos = strInput.find(':');
436 
437  if (pos == 0) {
438  throw std::runtime_error("TX output value not specified");
439  }
440 
441  if (pos == std::string::npos) {
442  pos = 0;
443  } else {
444  // Extract and validate VALUE
445  value = ExtractAndValidateValue(strInput.substr(0, pos));
446  ++pos;
447  }
448 
449  // extract and validate DATA
450  const std::string strData{strInput.substr(pos, std::string::npos)};
451 
452  if (!IsHex(strData)) {
453  throw std::runtime_error("invalid TX output data");
454  }
455 
456  std::vector<uint8_t> data = ParseHex(strData);
457 
458  CTxOut txout(value, CScript() << OP_RETURN << data);
459  tx.vout.push_back(txout);
460 }
461 
463  const std::string &strInput) {
464  // separate VALUE:SCRIPT[:FLAGS]
465  std::vector<std::string> vStrInputParts = SplitString(strInput, ':');
466  if (vStrInputParts.size() < 2) {
467  throw std::runtime_error("TX output missing separator");
468  }
469 
470  // Extract and validate VALUE
471  Amount value = ExtractAndValidateValue(vStrInputParts[0]);
472 
473  // extract and validate script
474  std::string strScript = vStrInputParts[1];
475  CScript scriptPubKey = ParseScript(strScript);
476 
477  // Extract FLAGS
478  bool bScriptHash = false;
479  if (vStrInputParts.size() == 3) {
480  std::string flags = vStrInputParts.back();
481  bScriptHash = (flags.find('S') != std::string::npos);
482  }
483 
484  if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
485  throw std::runtime_error(strprintf("script exceeds size limit: %d > %d",
486  scriptPubKey.size(),
487  MAX_SCRIPT_SIZE));
488  }
489 
490  if (bScriptHash) {
491  if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
492  throw std::runtime_error(
493  strprintf("redeemScript exceeds size limit: %d > %d",
494  scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
495  }
496  scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey));
497  }
498 
499  // construct TxOut, append to transaction output list
500  CTxOut txout(value, scriptPubKey);
501  tx.vout.push_back(txout);
502 }
503 
505  const std::string &strInIdx) {
506  // parse requested deletion index
507  int64_t inIdx;
508  if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 ||
509  inIdx >= static_cast<int64_t>(tx.vin.size())) {
510  throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
511  }
512 
513  // delete input from transaction
514  tx.vin.erase(tx.vin.begin() + inIdx);
515 }
516 
518  const std::string &strOutIdx) {
519  // parse requested deletion index
520  int64_t outIdx;
521  if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 ||
522  outIdx >= static_cast<int64_t>(tx.vout.size())) {
523  throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
524  }
525 
526  // delete output from transaction
527  tx.vout.erase(tx.vout.begin() + outIdx);
528 }
529 
530 static const unsigned int N_SIGHASH_OPTS = 12;
531 static const struct {
532  const char *flagStr;
533  int flags;
535  {"ALL", SIGHASH_ALL},
536  {"NONE", SIGHASH_NONE},
537  {"SINGLE", SIGHASH_SINGLE},
538  {"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY},
539  {"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY},
540  {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY},
541  {"ALL|FORKID", SIGHASH_ALL | SIGHASH_FORKID},
542  {"NONE|FORKID", SIGHASH_NONE | SIGHASH_FORKID},
543  {"SINGLE|FORKID", SIGHASH_SINGLE | SIGHASH_FORKID},
544  {"ALL|FORKID|ANYONECANPAY",
546  {"NONE|FORKID|ANYONECANPAY",
548  {"SINGLE|FORKID|ANYONECANPAY",
550 };
551 
552 static bool findSigHashFlags(SigHashType &sigHashType,
553  const std::string &flagStr) {
554  sigHashType = SigHashType();
555 
556  for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
557  if (flagStr == sigHashOptions[i].flagStr) {
558  sigHashType = SigHashType(sigHashOptions[i].flags);
559  return true;
560  }
561  }
562 
563  return false;
564 }
565 
566 static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr) {
567  SigHashType sigHashType = SigHashType().withForkId();
568 
569  if ((flagStr.size() > 0) && !findSigHashFlags(sigHashType, flagStr)) {
570  throw std::runtime_error("unknown sighash flag/sign option");
571  }
572 
573  // mergedTx will end up with all the signatures; it
574  // starts as a clone of the raw tx:
575  CMutableTransaction mergedTx{tx};
576  const CMutableTransaction txv{tx};
577 
578  CCoinsView viewDummy;
579  CCoinsViewCache view(&viewDummy);
580 
581  if (!registers.count("privatekeys")) {
582  throw std::runtime_error("privatekeys register variable must be set.");
583  }
584 
585  FillableSigningProvider tempKeystore;
586  UniValue keysObj = registers["privatekeys"];
587 
588  for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
589  if (!keysObj[kidx].isStr()) {
590  throw std::runtime_error("privatekey not a std::string");
591  }
592 
593  CKey key = DecodeSecret(keysObj[kidx].getValStr());
594  if (!key.IsValid()) {
595  throw std::runtime_error("privatekey not valid");
596  }
597  tempKeystore.AddKey(key);
598  }
599 
600  // Add previous txouts given in the RPC call:
601  if (!registers.count("prevtxs")) {
602  throw std::runtime_error("prevtxs register variable must be set.");
603  }
604 
605  UniValue prevtxsObj = registers["prevtxs"];
606 
607  for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
608  UniValue prevOut = prevtxsObj[previdx];
609  if (!prevOut.isObject()) {
610  throw std::runtime_error("expected prevtxs internal object");
611  }
612 
613  std::map<std::string, UniValue::VType> types = {
614  {"txid", UniValue::VSTR},
615  {"vout", UniValue::VNUM},
616  {"scriptPubKey", UniValue::VSTR}};
617  if (!prevOut.checkObject(types)) {
618  throw std::runtime_error("prevtxs internal object typecheck fail");
619  }
620 
621  uint256 hash;
622  if (!ParseHashStr(prevOut["txid"].get_str(), hash)) {
623  throw std::runtime_error("txid must be hexadecimal string (not '" +
624  prevOut["txid"].get_str() + "')");
625  }
626 
627  TxId txid(hash);
628 
629  const int nOut = prevOut["vout"].get_int();
630  if (nOut < 0) {
631  throw std::runtime_error("vout cannot be negative");
632  }
633 
634  COutPoint out(txid, nOut);
635  std::vector<uint8_t> pkData(
636  ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
637  CScript scriptPubKey(pkData.begin(), pkData.end());
638 
639  {
640  const Coin &coin = view.AccessCoin(out);
641  if (!coin.IsSpent() &&
642  coin.GetTxOut().scriptPubKey != scriptPubKey) {
643  std::string err("Previous output scriptPubKey mismatch:\n");
644  err = err + ScriptToAsmStr(coin.GetTxOut().scriptPubKey) +
645  "\nvs:\n" + ScriptToAsmStr(scriptPubKey);
646  throw std::runtime_error(err);
647  }
648 
649  CTxOut txout;
650  txout.scriptPubKey = scriptPubKey;
651  txout.nValue = Amount::zero();
652  if (prevOut.exists("amount")) {
653  txout.nValue = AmountFromValue(prevOut["amount"]);
654  }
655 
656  view.AddCoin(out, Coin(txout, 1, false), true);
657  }
658 
659  // If redeemScript given and private keys given, add redeemScript to the
660  // tempKeystore so it can be signed:
661  if (scriptPubKey.IsPayToScriptHash() &&
662  prevOut.exists("redeemScript")) {
663  UniValue v = prevOut["redeemScript"];
664  std::vector<uint8_t> rsData(ParseHexUV(v, "redeemScript"));
665  CScript redeemScript(rsData.begin(), rsData.end());
666  tempKeystore.AddCScript(redeemScript);
667  }
668  }
669 
670  const FillableSigningProvider &keystore = tempKeystore;
671 
672  // Sign what we can:
673  for (size_t i = 0; i < mergedTx.vin.size(); i++) {
674  CTxIn &txin = mergedTx.vin[i];
675  const Coin &coin = view.AccessCoin(txin.prevout);
676  if (coin.IsSpent()) {
677  continue;
678  }
679 
680  const CScript &prevPubKey = coin.GetTxOut().scriptPubKey;
681  const Amount amount = coin.GetTxOut().nValue;
682 
683  SignatureData sigdata =
684  DataFromTransaction(mergedTx, i, coin.GetTxOut());
685  // Only sign SIGHASH_SINGLE if there's a corresponding output:
686  if ((sigHashType.getBaseType() != BaseSigHashType::SINGLE) ||
687  (i < mergedTx.vout.size())) {
688  ProduceSignature(keystore,
690  &mergedTx, i, amount, sigHashType),
691  prevPubKey, sigdata);
692  }
693 
694  UpdateInput(txin, sigdata);
695  }
696 
697  tx = mergedTx;
698 }
699 
702 
703 public:
706 };
707 
708 static void MutateTx(CMutableTransaction &tx, const std::string &command,
709  const std::string &commandVal,
710  const CChainParams &chainParams) {
711  std::unique_ptr<Secp256k1Init> ecc;
712 
713  if (command == "nversion") {
714  MutateTxVersion(tx, commandVal);
715  } else if (command == "locktime") {
716  MutateTxLocktime(tx, commandVal);
717  } else if (command == "delin") {
718  MutateTxDelInput(tx, commandVal);
719  } else if (command == "in") {
720  MutateTxAddInput(tx, commandVal);
721  } else if (command == "delout") {
722  MutateTxDelOutput(tx, commandVal);
723  } else if (command == "outaddr") {
724  MutateTxAddOutAddr(tx, commandVal, chainParams);
725  } else if (command == "outpubkey") {
726  ecc.reset(new Secp256k1Init());
727  MutateTxAddOutPubKey(tx, commandVal);
728  } else if (command == "outmultisig") {
729  ecc.reset(new Secp256k1Init());
730  MutateTxAddOutMultiSig(tx, commandVal);
731  } else if (command == "outscript") {
732  MutateTxAddOutScript(tx, commandVal);
733  } else if (command == "outdata") {
734  MutateTxAddOutData(tx, commandVal);
735  } else if (command == "sign") {
736  ecc.reset(new Secp256k1Init());
737  MutateTxSign(tx, commandVal);
738  } else if (command == "load") {
739  RegisterLoad(commandVal);
740  } else if (command == "set") {
741  RegisterSet(commandVal);
742  } else {
743  throw std::runtime_error("unknown command");
744  }
745 }
746 
747 static void OutputTxJSON(const CTransaction &tx) {
748  UniValue entry(UniValue::VOBJ);
749  TxToUniv(tx, BlockHash(), entry);
750 
751  std::string jsonOutput = entry.write(4);
752  tfm::format(std::cout, "%s\n", jsonOutput);
753 }
754 
755 static void OutputTxHash(const CTransaction &tx) {
756  // the hex-encoded transaction id.
757  std::string strHexHash = tx.GetId().GetHex();
758 
759  tfm::format(std::cout, "%s\n", strHexHash);
760 }
761 
762 static void OutputTxHex(const CTransaction &tx) {
763  std::string strHex = EncodeHexTx(tx);
764 
765  tfm::format(std::cout, "%s\n", strHex);
766 }
767 
768 static void OutputTx(const CTransaction &tx) {
769  if (gArgs.GetBoolArg("-json", false)) {
770  OutputTxJSON(tx);
771  } else if (gArgs.GetBoolArg("-txid", false)) {
772  OutputTxHash(tx);
773  } else {
774  OutputTxHex(tx);
775  }
776 }
777 
778 static std::string readStdin() {
779  char buf[4096];
780  std::string ret;
781 
782  while (!feof(stdin)) {
783  size_t bread = fread(buf, 1, sizeof(buf), stdin);
784  ret.append(buf, bread);
785  if (bread < sizeof(buf)) {
786  break;
787  }
788  }
789 
790  if (ferror(stdin)) {
791  throw std::runtime_error("error reading stdin");
792  }
793 
794  boost::algorithm::trim_right(ret);
795 
796  return ret;
797 }
798 
799 static int CommandLineRawTx(int argc, char *argv[],
800  const CChainParams &chainParams) {
801  std::string strPrint;
802  int nRet = 0;
803  try {
804  // Skip switches; Permit common stdin convention "-"
805  while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
806  argc--;
807  argv++;
808  }
809 
811  int startArg;
812 
813  if (!fCreateBlank) {
814  // require at least one param
815  if (argc < 2) {
816  throw std::runtime_error("too few parameters");
817  }
818 
819  // param: hex-encoded bitcoin transaction
820  std::string strHexTx(argv[1]);
821 
822  // "-" implies standard input
823  if (strHexTx == "-") {
824  strHexTx = readStdin();
825  }
826 
827  if (!DecodeHexTx(tx, strHexTx)) {
828  throw std::runtime_error("invalid transaction encoding");
829  }
830 
831  startArg = 2;
832  } else {
833  startArg = 1;
834  }
835 
836  for (int i = startArg; i < argc; i++) {
837  std::string arg = argv[i];
838  std::string key, value;
839  size_t eqpos = arg.find('=');
840  if (eqpos == std::string::npos) {
841  key = arg;
842  } else {
843  key = arg.substr(0, eqpos);
844  value = arg.substr(eqpos + 1);
845  }
846 
847  MutateTx(tx, key, value, chainParams);
848  }
849 
850  OutputTx(CTransaction(tx));
851  } catch (const std::exception &e) {
852  strPrint = std::string("error: ") + e.what();
853  nRet = EXIT_FAILURE;
854  } catch (const UniValue &e) {
855  strPrint = std::string("error code: ") + e["code"].getValStr() +
856  " message: " + e["message"].getValStr();
857  nRet = EXIT_FAILURE;
858  } catch (...) {
859  PrintExceptionContinue(nullptr, "CommandLineRawTx()");
860  throw;
861  }
862 
863  if (strPrint != "") {
864  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
865  }
866 
867  return nRet;
868 }
869 
870 int main(int argc, char *argv[]) {
872 
873  try {
874  int ret = AppInitRawTx(argc, argv);
875  if (ret != CONTINUE_EXECUTION) {
876  return ret;
877  }
878  } catch (const std::exception &e) {
879  PrintExceptionContinue(&e, "AppInitRawTx()");
880  return EXIT_FAILURE;
881  } catch (...) {
882  PrintExceptionContinue(nullptr, "AppInitRawTx()");
883  return EXIT_FAILURE;
884  }
885 
886  int ret = EXIT_FAILURE;
887  try {
888  ret = CommandLineRawTx(argc, argv, Params());
889  } catch (const std::exception &e) {
890  PrintExceptionContinue(&e, "CommandLineRawTx()");
891  } catch (...) {
892  PrintExceptionContinue(nullptr, "CommandLineRawTx()");
893  }
894 
895  return ret;
896 }
int main(int argc, char *argv[])
Definition: bitcoin-tx.cpp:870
static void OutputTxHash(const CTransaction &tx)
Definition: bitcoin-tx.cpp:755
static const unsigned int N_SIGHASH_OPTS
Definition: bitcoin-tx.cpp:530
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
Definition: bitcoin-tx.cpp:566
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:778
static int CommandLineRawTx(int argc, char *argv[], const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:799
static void OutputTxJSON(const CTransaction &tx)
Definition: bitcoin-tx.cpp:747
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:517
const char * flagStr
Definition: bitcoin-tx.cpp:532
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:322
static bool fCreateBlank
Definition: bitcoin-tx.cpp:37
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:430
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:232
static void OutputTxHex(const CTransaction &tx)
Definition: bitcoin-tx.cpp:762
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:504
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:257
int flags
Definition: bitcoin-tx.cpp:533
static bool findSigHashFlags(SigHashType &sigHashType, const std::string &flagStr)
Definition: bitcoin-tx.cpp:552
static void SetupBitcoinTxArgs(ArgsManager &argsman)
Definition: bitcoin-tx.cpp:43
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:360
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal, const CChainParams &chainParams)
Definition: bitcoin-tx.cpp:708
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
Definition: bitcoin-tx.cpp:462
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
Definition: bitcoin-tx.cpp:245
static void OutputTx(const CTransaction &tx)
Definition: bitcoin-tx.cpp:768
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:161
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:321
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:761
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:664
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:728
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1122
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: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: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:226
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:701
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: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 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 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: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
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:92
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:840
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:845
ArgsManager gArgs
Definition: system.cpp:79
void SetupEnvironment()
Definition: system.cpp:1397
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:885
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
bool IsSwitchChar(char c)
Definition: system.h:108
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202