You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bitcoin-tx.cpp 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. // Copyright (c) 2009-2016 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. #if defined(HAVE_CONFIG_H)
  5. #include "config/bitcoin-config.h"
  6. #endif
  7. #include "base58.h"
  8. #include "clientversion.h"
  9. #include "coins.h"
  10. #include "consensus/consensus.h"
  11. #include "core_io.h"
  12. #include "keystore.h"
  13. #include "policy/policy.h"
  14. #include "policy/rbf.h"
  15. #include "primitives/transaction.h"
  16. #include "script/script.h"
  17. #include "script/sign.h"
  18. #include <univalue.h>
  19. #include "util.h"
  20. #include "utilmoneystr.h"
  21. #include "utilstrencodings.h"
  22. #include <stdio.h>
  23. #include <boost/algorithm/string.hpp>
  24. static bool fCreateBlank;
  25. static std::map<std::string,UniValue> registers;
  26. static const int CONTINUE_EXECUTION=-1;
  27. //
  28. // This function returns either one of EXIT_ codes when it's expected to stop the process or
  29. // CONTINUE_EXECUTION when it's expected to continue further.
  30. //
  31. static int AppInitRawTx(int argc, char* argv[])
  32. {
  33. //
  34. // Parameters
  35. //
  36. gArgs.ParseParameters(argc, argv);
  37. // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
  38. try {
  39. SelectParams(ChainNameFromCommandLine());
  40. } catch (const std::exception& e) {
  41. fprintf(stderr, "Error: %s\n", e.what());
  42. return EXIT_FAILURE;
  43. }
  44. fCreateBlank = gArgs.GetBoolArg("-create", false);
  45. if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help"))
  46. {
  47. // First part of help message is specific to this utility
  48. std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
  49. _("Usage:") + "\n" +
  50. " bitcoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded bitcoin transaction") + "\n" +
  51. " bitcoin-tx [options] -create [commands] " + _("Create hex-encoded bitcoin transaction") + "\n" +
  52. "\n";
  53. fprintf(stdout, "%s", strUsage.c_str());
  54. strUsage = HelpMessageGroup(_("Options:"));
  55. strUsage += HelpMessageOpt("-?", _("This help message"));
  56. strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
  57. strUsage += HelpMessageOpt("-json", _("Select JSON output"));
  58. strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
  59. AppendParamsHelpMessages(strUsage);
  60. fprintf(stdout, "%s", strUsage.c_str());
  61. strUsage = HelpMessageGroup(_("Commands:"));
  62. strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
  63. strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
  64. strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
  65. strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
  66. strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
  67. strUsage += HelpMessageOpt("replaceable(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)"));
  68. strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
  69. strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
  70. _("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
  71. _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
  72. strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
  73. strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
  74. _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
  75. _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
  76. strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
  77. _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
  78. _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
  79. strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
  80. _("This command requires JSON registers:") +
  81. _("prevtxs=JSON object") + ", " +
  82. _("privatekeys=JSON object") + ". " +
  83. _("See signrawtransaction docs for format of sighash flags, JSON objects."));
  84. fprintf(stdout, "%s", strUsage.c_str());
  85. strUsage = HelpMessageGroup(_("Register Commands:"));
  86. strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
  87. strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
  88. fprintf(stdout, "%s", strUsage.c_str());
  89. if (argc < 2) {
  90. fprintf(stderr, "Error: too few parameters\n");
  91. return EXIT_FAILURE;
  92. }
  93. return EXIT_SUCCESS;
  94. }
  95. return CONTINUE_EXECUTION;
  96. }
  97. static void RegisterSetJson(const std::string& key, const std::string& rawJson)
  98. {
  99. UniValue val;
  100. if (!val.read(rawJson)) {
  101. std::string strErr = "Cannot parse JSON for key " + key;
  102. throw std::runtime_error(strErr);
  103. }
  104. registers[key] = val;
  105. }
  106. static void RegisterSet(const std::string& strInput)
  107. {
  108. // separate NAME:VALUE in string
  109. size_t pos = strInput.find(':');
  110. if ((pos == std::string::npos) ||
  111. (pos == 0) ||
  112. (pos == (strInput.size() - 1)))
  113. throw std::runtime_error("Register input requires NAME:VALUE");
  114. std::string key = strInput.substr(0, pos);
  115. std::string valStr = strInput.substr(pos + 1, std::string::npos);
  116. RegisterSetJson(key, valStr);
  117. }
  118. static void RegisterLoad(const std::string& strInput)
  119. {
  120. // separate NAME:FILENAME in string
  121. size_t pos = strInput.find(':');
  122. if ((pos == std::string::npos) ||
  123. (pos == 0) ||
  124. (pos == (strInput.size() - 1)))
  125. throw std::runtime_error("Register load requires NAME:FILENAME");
  126. std::string key = strInput.substr(0, pos);
  127. std::string filename = strInput.substr(pos + 1, std::string::npos);
  128. FILE *f = fopen(filename.c_str(), "r");
  129. if (!f) {
  130. std::string strErr = "Cannot open file " + filename;
  131. throw std::runtime_error(strErr);
  132. }
  133. // load file chunks into one big buffer
  134. std::string valStr;
  135. while ((!feof(f)) && (!ferror(f))) {
  136. char buf[4096];
  137. int bread = fread(buf, 1, sizeof(buf), f);
  138. if (bread <= 0)
  139. break;
  140. valStr.insert(valStr.size(), buf, bread);
  141. }
  142. int error = ferror(f);
  143. fclose(f);
  144. if (error) {
  145. std::string strErr = "Error reading file " + filename;
  146. throw std::runtime_error(strErr);
  147. }
  148. // evaluate as JSON buffer register
  149. RegisterSetJson(key, valStr);
  150. }
  151. static CAmount ExtractAndValidateValue(const std::string& strValue)
  152. {
  153. CAmount value;
  154. if (!ParseMoney(strValue, value))
  155. throw std::runtime_error("invalid TX output value");
  156. return value;
  157. }
  158. static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
  159. {
  160. int64_t newVersion = atoi64(cmdVal);
  161. if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
  162. throw std::runtime_error("Invalid TX version requested");
  163. tx.nVersion = (int) newVersion;
  164. }
  165. static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
  166. {
  167. int64_t newLocktime = atoi64(cmdVal);
  168. if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
  169. throw std::runtime_error("Invalid TX locktime requested");
  170. tx.nLockTime = (unsigned int) newLocktime;
  171. }
  172. static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
  173. {
  174. // parse requested index
  175. int inIdx = atoi(strInIdx);
  176. if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
  177. throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
  178. }
  179. // set the nSequence to MAX_INT - 2 (= RBF opt in flag)
  180. int cnt = 0;
  181. for (CTxIn& txin : tx.vin) {
  182. if (strInIdx == "" || cnt == inIdx) {
  183. if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
  184. txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
  185. }
  186. }
  187. ++cnt;
  188. }
  189. }
  190. static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
  191. {
  192. std::vector<std::string> vStrInputParts;
  193. boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
  194. // separate TXID:VOUT in string
  195. if (vStrInputParts.size()<2)
  196. throw std::runtime_error("TX input missing separator");
  197. // extract and validate TXID
  198. std::string strTxid = vStrInputParts[0];
  199. if ((strTxid.size() != 64) || !IsHex(strTxid))
  200. throw std::runtime_error("invalid TX input txid");
  201. uint256 txid(uint256S(strTxid));
  202. static const unsigned int minTxOutSz = 9;
  203. static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz);
  204. // extract and validate vout
  205. std::string strVout = vStrInputParts[1];
  206. int vout = atoi(strVout);
  207. if ((vout < 0) || (vout > (int)maxVout))
  208. throw std::runtime_error("invalid TX input vout");
  209. // extract the optional sequence number
  210. uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
  211. if (vStrInputParts.size() > 2)
  212. nSequenceIn = std::stoul(vStrInputParts[2]);
  213. // append to transaction input list
  214. CTxIn txin(txid, vout, CScript(), nSequenceIn);
  215. tx.vin.push_back(txin);
  216. }
  217. static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
  218. {
  219. // Separate into VALUE:ADDRESS
  220. std::vector<std::string> vStrInputParts;
  221. boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
  222. if (vStrInputParts.size() != 2)
  223. throw std::runtime_error("TX output missing or too many separators");
  224. // Extract and validate VALUE
  225. CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
  226. // extract and validate ADDRESS
  227. std::string strAddr = vStrInputParts[1];
  228. CBitcoinAddress addr(strAddr);
  229. if (!addr.IsValid())
  230. throw std::runtime_error("invalid TX output address");
  231. // build standard output script via GetScriptForDestination()
  232. CScript scriptPubKey = GetScriptForDestination(addr.Get());
  233. // construct TxOut, append to transaction output list
  234. CTxOut txout(value, scriptPubKey);
  235. tx.vout.push_back(txout);
  236. }
  237. static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
  238. {
  239. // Separate into VALUE:PUBKEY[:FLAGS]
  240. std::vector<std::string> vStrInputParts;
  241. boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
  242. if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
  243. throw std::runtime_error("TX output missing or too many separators");
  244. // Extract and validate VALUE
  245. CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
  246. // Extract and validate PUBKEY
  247. CPubKey pubkey(ParseHex(vStrInputParts[1]));
  248. if (!pubkey.IsFullyValid())
  249. throw std::runtime_error("invalid TX output pubkey");
  250. CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
  251. // Extract and validate FLAGS
  252. bool bSegWit = false;
  253. bool bScriptHash = false;
  254. if (vStrInputParts.size() == 3) {
  255. std::string flags = vStrInputParts[2];
  256. bSegWit = (flags.find("W") != std::string::npos);
  257. bScriptHash = (flags.find("S") != std::string::npos);
  258. }
  259. if (bSegWit) {
  260. if (!pubkey.IsCompressed()) {
  261. throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
  262. }
  263. // Call GetScriptForWitness() to build a P2WSH scriptPubKey
  264. scriptPubKey = GetScriptForWitness(scriptPubKey);
  265. }
  266. if (bScriptHash) {
  267. // Get the address for the redeem script, then call
  268. // GetScriptForDestination() to construct a P2SH scriptPubKey.
  269. CBitcoinAddress redeemScriptAddr(scriptPubKey);
  270. scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get());
  271. }
  272. // construct TxOut, append to transaction output list
  273. CTxOut txout(value, scriptPubKey);
  274. tx.vout.push_back(txout);
  275. }
  276. static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
  277. {
  278. // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
  279. std::vector<std::string> vStrInputParts;
  280. boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
  281. // Check that there are enough parameters
  282. if (vStrInputParts.size()<3)
  283. throw std::runtime_error("Not enough multisig parameters");
  284. // Extract and validate VALUE
  285. CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
  286. // Extract REQUIRED
  287. uint32_t required = stoul(vStrInputParts[1]);
  288. // Extract NUMKEYS
  289. uint32_t numkeys = stoul(vStrInputParts[2]);
  290. // Validate there are the correct number of pubkeys
  291. if (vStrInputParts.size() < numkeys + 3)
  292. throw std::runtime_error("incorrect number of multisig pubkeys");
  293. if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
  294. throw std::runtime_error("multisig parameter mismatch. Required " \
  295. + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
  296. // extract and validate PUBKEYs
  297. std::vector<CPubKey> pubkeys;
  298. for(int pos = 1; pos <= int(numkeys); pos++) {
  299. CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
  300. if (!pubkey.IsFullyValid())
  301. throw std::runtime_error("invalid TX output pubkey");
  302. pubkeys.push_back(pubkey);
  303. }
  304. // Extract FLAGS
  305. bool bSegWit = false;
  306. bool bScriptHash = false;
  307. if (vStrInputParts.size() == numkeys + 4) {
  308. std::string flags = vStrInputParts.back();
  309. bSegWit = (flags.find("W") != std::string::npos);
  310. bScriptHash = (flags.find("S") != std::string::npos);
  311. }
  312. else if (vStrInputParts.size() > numkeys + 4) {
  313. // Validate that there were no more parameters passed
  314. throw std::runtime_error("Too many parameters");
  315. }
  316. CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
  317. if (bSegWit) {
  318. for (CPubKey& pubkey : pubkeys) {
  319. if (!pubkey.IsCompressed()) {
  320. throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
  321. }
  322. }
  323. // Call GetScriptForWitness() to build a P2WSH scriptPubKey
  324. scriptPubKey = GetScriptForWitness(scriptPubKey);
  325. }
  326. if (bScriptHash) {
  327. // Get the address for the redeem script, then call
  328. // GetScriptForDestination() to construct a P2SH scriptPubKey.
  329. CBitcoinAddress addr(scriptPubKey);
  330. scriptPubKey = GetScriptForDestination(addr.Get());
  331. }
  332. // construct TxOut, append to transaction output list
  333. CTxOut txout(value, scriptPubKey);
  334. tx.vout.push_back(txout);
  335. }
  336. static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
  337. {
  338. CAmount value = 0;
  339. // separate [VALUE:]DATA in string
  340. size_t pos = strInput.find(':');
  341. if (pos==0)
  342. throw std::runtime_error("TX output value not specified");
  343. if (pos != std::string::npos) {
  344. // Extract and validate VALUE
  345. value = ExtractAndValidateValue(strInput.substr(0, pos));
  346. }
  347. // extract and validate DATA
  348. std::string strData = strInput.substr(pos + 1, std::string::npos);
  349. if (!IsHex(strData))
  350. throw std::runtime_error("invalid TX output data");
  351. std::vector<unsigned char> data = ParseHex(strData);
  352. CTxOut txout(value, CScript() << OP_RETURN << data);
  353. tx.vout.push_back(txout);
  354. }
  355. static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
  356. {
  357. // separate VALUE:SCRIPT[:FLAGS]
  358. std::vector<std::string> vStrInputParts;
  359. boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
  360. if (vStrInputParts.size() < 2)
  361. throw std::runtime_error("TX output missing separator");
  362. // Extract and validate VALUE
  363. CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
  364. // extract and validate script
  365. std::string strScript = vStrInputParts[1];
  366. CScript scriptPubKey = ParseScript(strScript);
  367. // Extract FLAGS
  368. bool bSegWit = false;
  369. bool bScriptHash = false;
  370. if (vStrInputParts.size() == 3) {
  371. std::string flags = vStrInputParts.back();
  372. bSegWit = (flags.find("W") != std::string::npos);
  373. bScriptHash = (flags.find("S") != std::string::npos);
  374. }
  375. if (bSegWit) {
  376. scriptPubKey = GetScriptForWitness(scriptPubKey);
  377. }
  378. if (bScriptHash) {
  379. CBitcoinAddress addr(scriptPubKey);
  380. scriptPubKey = GetScriptForDestination(addr.Get());
  381. }
  382. // construct TxOut, append to transaction output list
  383. CTxOut txout(value, scriptPubKey);
  384. tx.vout.push_back(txout);
  385. }
  386. static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
  387. {
  388. // parse requested deletion index
  389. int inIdx = atoi(strInIdx);
  390. if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
  391. std::string strErr = "Invalid TX input index '" + strInIdx + "'";
  392. throw std::runtime_error(strErr.c_str());
  393. }
  394. // delete input from transaction
  395. tx.vin.erase(tx.vin.begin() + inIdx);
  396. }
  397. static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
  398. {
  399. // parse requested deletion index
  400. int outIdx = atoi(strOutIdx);
  401. if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
  402. std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
  403. throw std::runtime_error(strErr.c_str());
  404. }
  405. // delete output from transaction
  406. tx.vout.erase(tx.vout.begin() + outIdx);
  407. }
  408. static const unsigned int N_SIGHASH_OPTS = 6;
  409. static const struct {
  410. const char *flagStr;
  411. int flags;
  412. } sighashOptions[N_SIGHASH_OPTS] = {
  413. {"ALL", SIGHASH_ALL},
  414. {"NONE", SIGHASH_NONE},
  415. {"SINGLE", SIGHASH_SINGLE},
  416. {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
  417. {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
  418. {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
  419. };
  420. static bool findSighashFlags(int& flags, const std::string& flagStr)
  421. {
  422. flags = 0;
  423. for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
  424. if (flagStr == sighashOptions[i].flagStr) {
  425. flags = sighashOptions[i].flags;
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. static CAmount AmountFromValue(const UniValue& value)
  432. {
  433. if (!value.isNum() && !value.isStr())
  434. throw std::runtime_error("Amount is not a number or string");
  435. CAmount amount;
  436. if (!ParseFixedPoint(value.getValStr(), 8, &amount))
  437. throw std::runtime_error("Invalid amount");
  438. if (!MoneyRange(amount))
  439. throw std::runtime_error("Amount out of range");
  440. return amount;
  441. }
  442. static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
  443. {
  444. int nHashType = SIGHASH_ALL;
  445. if (flagStr.size() > 0)
  446. if (!findSighashFlags(nHashType, flagStr))
  447. throw std::runtime_error("unknown sighash flag/sign option");
  448. std::vector<CTransaction> txVariants;
  449. txVariants.push_back(tx);
  450. // mergedTx will end up with all the signatures; it
  451. // starts as a clone of the raw tx:
  452. CMutableTransaction mergedTx(txVariants[0]);
  453. bool fComplete = true;
  454. CCoinsView viewDummy;
  455. CCoinsViewCache view(&viewDummy);
  456. if (!registers.count("privatekeys"))
  457. throw std::runtime_error("privatekeys register variable must be set.");
  458. CBasicKeyStore tempKeystore;
  459. UniValue keysObj = registers["privatekeys"];
  460. for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
  461. if (!keysObj[kidx].isStr())
  462. throw std::runtime_error("privatekey not a std::string");
  463. CBitcoinSecret vchSecret;
  464. bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
  465. if (!fGood)
  466. throw std::runtime_error("privatekey not valid");
  467. CKey key = vchSecret.GetKey();
  468. tempKeystore.AddKey(key);
  469. }
  470. // Add previous txouts given in the RPC call:
  471. if (!registers.count("prevtxs"))
  472. throw std::runtime_error("prevtxs register variable must be set.");
  473. UniValue prevtxsObj = registers["prevtxs"];
  474. {
  475. for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
  476. UniValue prevOut = prevtxsObj[previdx];
  477. if (!prevOut.isObject())
  478. throw std::runtime_error("expected prevtxs internal object");
  479. std::map<std::string, UniValue::VType> types = {
  480. {"txid", UniValue::VSTR},
  481. {"vout", UniValue::VNUM},
  482. {"scriptPubKey", UniValue::VSTR},
  483. };
  484. if (!prevOut.checkObject(types))
  485. throw std::runtime_error("prevtxs internal object typecheck fail");
  486. uint256 txid = ParseHashUV(prevOut["txid"], "txid");
  487. int nOut = atoi(prevOut["vout"].getValStr());
  488. if (nOut < 0)
  489. throw std::runtime_error("vout must be positive");
  490. COutPoint out(txid, nOut);
  491. std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
  492. CScript scriptPubKey(pkData.begin(), pkData.end());
  493. {
  494. const Coin& coin = view.AccessCoin(out);
  495. if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
  496. std::string err("Previous output scriptPubKey mismatch:\n");
  497. err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
  498. ScriptToAsmStr(scriptPubKey);
  499. throw std::runtime_error(err);
  500. }
  501. Coin newcoin;
  502. newcoin.out.scriptPubKey = scriptPubKey;
  503. newcoin.out.nValue = 0;
  504. if (prevOut.exists("amount")) {
  505. newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
  506. }
  507. newcoin.nHeight = 1;
  508. view.AddCoin(out, std::move(newcoin), true);
  509. }
  510. // if redeemScript given and private keys given,
  511. // add redeemScript to the tempKeystore so it can be signed:
  512. if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
  513. prevOut.exists("redeemScript")) {
  514. UniValue v = prevOut["redeemScript"];
  515. std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
  516. CScript redeemScript(rsData.begin(), rsData.end());
  517. tempKeystore.AddCScript(redeemScript);
  518. }
  519. }
  520. }
  521. const CKeyStore& keystore = tempKeystore;
  522. bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
  523. // Sign what we can:
  524. for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
  525. CTxIn& txin = mergedTx.vin[i];
  526. const Coin& coin = view.AccessCoin(txin.prevout);
  527. if (coin.IsSpent()) {
  528. fComplete = false;
  529. continue;
  530. }
  531. const CScript& prevPubKey = coin.out.scriptPubKey;
  532. const CAmount& amount = coin.out.nValue;
  533. SignatureData sigdata;
  534. // Only sign SIGHASH_SINGLE if there's a corresponding output:
  535. if (!fHashSingle || (i < mergedTx.vout.size()))
  536. ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
  537. // ... and merge in other signatures:
  538. for (const CTransaction& txv : txVariants)
  539. sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
  540. UpdateTransaction(mergedTx, i, sigdata);
  541. if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
  542. fComplete = false;
  543. }
  544. if (fComplete) {
  545. // do nothing... for now
  546. // perhaps store this for later optional JSON output
  547. }
  548. tx = mergedTx;
  549. }
  550. class Secp256k1Init
  551. {
  552. ECCVerifyHandle globalVerifyHandle;
  553. public:
  554. Secp256k1Init() {
  555. ECC_Start();
  556. }
  557. ~Secp256k1Init() {
  558. ECC_Stop();
  559. }
  560. };
  561. static void MutateTx(CMutableTransaction& tx, const std::string& command,
  562. const std::string& commandVal)
  563. {
  564. std::unique_ptr<Secp256k1Init> ecc;
  565. if (command == "nversion")
  566. MutateTxVersion(tx, commandVal);
  567. else if (command == "locktime")
  568. MutateTxLocktime(tx, commandVal);
  569. else if (command == "replaceable") {
  570. MutateTxRBFOptIn(tx, commandVal);
  571. }
  572. else if (command == "delin")
  573. MutateTxDelInput(tx, commandVal);
  574. else if (command == "in")
  575. MutateTxAddInput(tx, commandVal);
  576. else if (command == "delout")
  577. MutateTxDelOutput(tx, commandVal);
  578. else if (command == "outaddr")
  579. MutateTxAddOutAddr(tx, commandVal);
  580. else if (command == "outpubkey") {
  581. if (!ecc) { ecc.reset(new Secp256k1Init()); }
  582. MutateTxAddOutPubKey(tx, commandVal);
  583. } else if (command == "outmultisig") {
  584. if (!ecc) { ecc.reset(new Secp256k1Init()); }
  585. MutateTxAddOutMultiSig(tx, commandVal);
  586. } else if (command == "outscript")
  587. MutateTxAddOutScript(tx, commandVal);
  588. else if (command == "outdata")
  589. MutateTxAddOutData(tx, commandVal);
  590. else if (command == "sign") {
  591. if (!ecc) { ecc.reset(new Secp256k1Init()); }
  592. MutateTxSign(tx, commandVal);
  593. }
  594. else if (command == "load")
  595. RegisterLoad(commandVal);
  596. else if (command == "set")
  597. RegisterSet(commandVal);
  598. else
  599. throw std::runtime_error("unknown command");
  600. }
  601. static void OutputTxJSON(const CTransaction& tx)
  602. {
  603. UniValue entry(UniValue::VOBJ);
  604. TxToUniv(tx, uint256(), entry);
  605. std::string jsonOutput = entry.write(4);
  606. fprintf(stdout, "%s\n", jsonOutput.c_str());
  607. }
  608. static void OutputTxHash(const CTransaction& tx)
  609. {
  610. std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
  611. fprintf(stdout, "%s\n", strHexHash.c_str());
  612. }
  613. static void OutputTxHex(const CTransaction& tx)
  614. {
  615. std::string strHex = EncodeHexTx(tx);
  616. fprintf(stdout, "%s\n", strHex.c_str());
  617. }
  618. static void OutputTx(const CTransaction& tx)
  619. {
  620. if (gArgs.GetBoolArg("-json", false))
  621. OutputTxJSON(tx);
  622. else if (gArgs.GetBoolArg("-txid", false))
  623. OutputTxHash(tx);
  624. else
  625. OutputTxHex(tx);
  626. }
  627. static std::string readStdin()
  628. {
  629. char buf[4096];
  630. std::string ret;
  631. while (!feof(stdin)) {
  632. size_t bread = fread(buf, 1, sizeof(buf), stdin);
  633. ret.append(buf, bread);
  634. if (bread < sizeof(buf))
  635. break;
  636. }
  637. if (ferror(stdin))
  638. throw std::runtime_error("error reading stdin");
  639. boost::algorithm::trim_right(ret);
  640. return ret;
  641. }
  642. static int CommandLineRawTx(int argc, char* argv[])
  643. {
  644. std::string strPrint;
  645. int nRet = 0;
  646. try {
  647. // Skip switches; Permit common stdin convention "-"
  648. while (argc > 1 && IsSwitchChar(argv[1][0]) &&
  649. (argv[1][1] != 0)) {
  650. argc--;
  651. argv++;
  652. }
  653. CMutableTransaction tx;
  654. int startArg;
  655. if (!fCreateBlank) {
  656. // require at least one param
  657. if (argc < 2)
  658. throw std::runtime_error("too few parameters");
  659. // param: hex-encoded bitcoin transaction
  660. std::string strHexTx(argv[1]);
  661. if (strHexTx == "-") // "-" implies standard input
  662. strHexTx = readStdin();
  663. if (!DecodeHexTx(tx, strHexTx, true))
  664. throw std::runtime_error("invalid transaction encoding");
  665. startArg = 2;
  666. } else
  667. startArg = 1;
  668. for (int i = startArg; i < argc; i++) {
  669. std::string arg = argv[i];
  670. std::string key, value;
  671. size_t eqpos = arg.find('=');
  672. if (eqpos == std::string::npos)
  673. key = arg;
  674. else {
  675. key = arg.substr(0, eqpos);
  676. value = arg.substr(eqpos + 1);
  677. }
  678. MutateTx(tx, key, value);
  679. }
  680. OutputTx(tx);
  681. }
  682. catch (const boost::thread_interrupted&) {
  683. throw;
  684. }
  685. catch (const std::exception& e) {
  686. strPrint = std::string("error: ") + e.what();
  687. nRet = EXIT_FAILURE;
  688. }
  689. catch (...) {
  690. PrintExceptionContinue(nullptr, "CommandLineRawTx()");
  691. throw;
  692. }
  693. if (strPrint != "") {
  694. fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
  695. }
  696. return nRet;
  697. }
  698. int main(int argc, char* argv[])
  699. {
  700. SetupEnvironment();
  701. try {
  702. int ret = AppInitRawTx(argc, argv);
  703. if (ret != CONTINUE_EXECUTION)
  704. return ret;
  705. }
  706. catch (const std::exception& e) {
  707. PrintExceptionContinue(&e, "AppInitRawTx()");
  708. return EXIT_FAILURE;
  709. } catch (...) {
  710. PrintExceptionContinue(nullptr, "AppInitRawTx()");
  711. return EXIT_FAILURE;
  712. }
  713. int ret = EXIT_FAILURE;
  714. try {
  715. ret = CommandLineRawTx(argc, argv);
  716. }
  717. catch (const std::exception& e) {
  718. PrintExceptionContinue(&e, "CommandLineRawTx()");
  719. } catch (...) {
  720. PrintExceptionContinue(nullptr, "CommandLineRawTx()");
  721. }
  722. return ret;
  723. }