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