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.

starwels-tx.cpp 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. // Copyright (c) 2009-2016 The Starwels 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/starwels-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 -ai 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 starwels-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
  49. _("Usage:") + "\n" +
  50. " starwels-tx [options] <hex-tx> [commands] " + _("Update hex-encoded starwels transaction") + "\n" +
  51. " starwels-tx [options] -create [commands] " + _("Create hex-encoded starwels 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. CStarwelsAddress 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. CStarwelsAddress 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. if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
  328. throw std::runtime_error(strprintf(
  329. "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
  330. }
  331. // Get the address for the redeem script, then call
  332. // GetScriptForDestination() to construct a P2SH scriptPubKey.
  333. CStarwelsAddress addr(scriptPubKey);
  334. scriptPubKey = GetScriptForDestination(addr.Get());
  335. }
  336. // construct TxOut, append to transaction output list
  337. CTxOut txout(value, scriptPubKey);
  338. tx.vout.push_back(txout);
  339. }
  340. static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
  341. {
  342. CAmount value = 0;
  343. // separate [VALUE:]DATA in string
  344. size_t pos = strInput.find(':');
  345. if (pos==0)
  346. throw std::runtime_error("TX output value not specified");
  347. if (pos != std::string::npos) {
  348. // Extract and validate VALUE
  349. value = ExtractAndValidateValue(strInput.substr(0, pos));
  350. }
  351. // extract and validate DATA
  352. std::string strData = strInput.substr(pos + 1, std::string::npos);
  353. if (!IsHex(strData))
  354. throw std::runtime_error("invalid TX output data");
  355. std::vector<unsigned char> data = ParseHex(strData);
  356. CTxOut txout(value, CScript() << OP_RETURN << data);
  357. tx.vout.push_back(txout);
  358. }
  359. static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
  360. {
  361. // separate VALUE:SCRIPT[:FLAGS]
  362. std::vector<std::string> vStrInputParts;
  363. boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
  364. if (vStrInputParts.size() < 2)
  365. throw std::runtime_error("TX output missing separator");
  366. // Extract and validate VALUE
  367. CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
  368. // extract and validate script
  369. std::string strScript = vStrInputParts[1];
  370. CScript scriptPubKey = ParseScript(strScript);
  371. // Extract FLAGS
  372. bool bSegWit = false;
  373. bool bScriptHash = false;
  374. if (vStrInputParts.size() == 3) {
  375. std::string flags = vStrInputParts.back();
  376. bSegWit = (flags.find("W") != std::string::npos);
  377. bScriptHash = (flags.find("S") != std::string::npos);
  378. }
  379. if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
  380. throw std::runtime_error(strprintf(
  381. "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
  382. }
  383. if (bSegWit) {
  384. scriptPubKey = GetScriptForWitness(scriptPubKey);
  385. }
  386. if (bScriptHash) {
  387. if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
  388. throw std::runtime_error(strprintf(
  389. "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
  390. }
  391. CStarwelsAddress addr(scriptPubKey);
  392. scriptPubKey = GetScriptForDestination(addr.Get());
  393. }
  394. // construct TxOut, append to transaction output list
  395. CTxOut txout(value, scriptPubKey);
  396. tx.vout.push_back(txout);
  397. }
  398. static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
  399. {
  400. // parse requested deletion index
  401. int inIdx = atoi(strInIdx);
  402. if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
  403. std::string strErr = "Invalid TX input index '" + strInIdx + "'";
  404. throw std::runtime_error(strErr.c_str());
  405. }
  406. // delete input from transaction
  407. tx.vin.erase(tx.vin.begin() + inIdx);
  408. }
  409. static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
  410. {
  411. // parse requested deletion index
  412. int outIdx = atoi(strOutIdx);
  413. if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
  414. std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
  415. throw std::runtime_error(strErr.c_str());
  416. }
  417. // delete output from transaction
  418. tx.vout.erase(tx.vout.begin() + outIdx);
  419. }
  420. static const unsigned int N_SIGHASH_OPTS = 6;
  421. static const struct {
  422. const char *flagStr;
  423. int flags;
  424. } sighashOptions[N_SIGHASH_OPTS] = {
  425. {"ALL", SIGHASH_ALL},
  426. {"NONE", SIGHASH_NONE},
  427. {"SINGLE", SIGHASH_SINGLE},
  428. {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
  429. {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
  430. {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
  431. };
  432. static bool findSighashFlags(int& flags, const std::string& flagStr)
  433. {
  434. flags = 0;
  435. for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
  436. if (flagStr == sighashOptions[i].flagStr) {
  437. flags = sighashOptions[i].flags;
  438. return true;
  439. }
  440. }
  441. return false;
  442. }
  443. static CAmount AmountFromValue(const UniValue& value)
  444. {
  445. if (!value.isNum() && !value.isStr())
  446. throw std::runtime_error("Amount is not a number or string");
  447. CAmount amount;
  448. if (!ParseFixedPoint(value.getValStr(), 8, &amount))
  449. throw std::runtime_error("Invalid amount");
  450. if (!MoneyRange(amount))
  451. throw std::runtime_error("Amount out of range");
  452. return amount;
  453. }
  454. static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
  455. {
  456. int nHashType = SIGHASH_ALL;
  457. if (flagStr.size() > 0)
  458. if (!findSighashFlags(nHashType, flagStr))
  459. throw std::runtime_error("unknown sighash flag/sign option");
  460. std::vector<CTransaction> txVariants;
  461. txVariants.push_back(tx);
  462. // mergedTx will end up with all the signatures; it
  463. // starts as a clone of the raw tx:
  464. CMutableTransaction mergedTx(txVariants[0]);
  465. bool fComplete = true;
  466. CCoinsView viewDummy;
  467. CCoinsViewCache view(&viewDummy);
  468. if (!registers.count("privatekeys"))
  469. throw std::runtime_error("privatekeys register variable must be set.");
  470. CBasicKeyStore tempKeystore;
  471. UniValue keysObj = registers["privatekeys"];
  472. for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
  473. if (!keysObj[kidx].isStr())
  474. throw std::runtime_error("privatekey not a std::string");
  475. CStarwelsSecret vchSecret;
  476. bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
  477. if (!fGood)
  478. throw std::runtime_error("privatekey not valid");
  479. CKey key = vchSecret.GetKey();
  480. tempKeystore.AddKey(key);
  481. }
  482. // Add previous txouts given in the RPC call:
  483. if (!registers.count("prevtxs"))
  484. throw std::runtime_error("prevtxs register variable must be set.");
  485. UniValue prevtxsObj = registers["prevtxs"];
  486. {
  487. for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
  488. UniValue prevOut = prevtxsObj[previdx];
  489. if (!prevOut.isObject())
  490. throw std::runtime_error("expected prevtxs internal object");
  491. std::map<std::string, UniValue::VType> types = {
  492. {"txid", UniValue::VSTR},
  493. {"vout", UniValue::VNUM},
  494. {"scriptPubKey", UniValue::VSTR},
  495. };
  496. if (!prevOut.checkObject(types))
  497. throw std::runtime_error("prevtxs internal object typecheck fail");
  498. uint256 txid = ParseHashUV(prevOut["txid"], "txid");
  499. int nOut = atoi(prevOut["vout"].getValStr());
  500. if (nOut < 0)
  501. throw std::runtime_error("vout must be positive");
  502. COutPoint out(txid, nOut);
  503. std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
  504. CScript scriptPubKey(pkData.begin(), pkData.end());
  505. {
  506. const Coin& coin = view.AccessCoin(out);
  507. if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
  508. std::string err("Previous output scriptPubKey mismatch:\n");
  509. err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
  510. ScriptToAsmStr(scriptPubKey);
  511. throw std::runtime_error(err);
  512. }
  513. Coin newcoin;
  514. newcoin.out.scriptPubKey = scriptPubKey;
  515. newcoin.out.nValue = 0;
  516. if (prevOut.exists("amount")) {
  517. newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
  518. }
  519. newcoin.nHeight = 1;
  520. view.AddCoin(out, std::move(newcoin), true);
  521. }
  522. // if redeemScript given and private keys given,
  523. // add redeemScript to the tempKeystore so it can be signed:
  524. if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
  525. prevOut.exists("redeemScript")) {
  526. UniValue v = prevOut["redeemScript"];
  527. std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
  528. CScript redeemScript(rsData.begin(), rsData.end());
  529. tempKeystore.AddCScript(redeemScript);
  530. }
  531. }
  532. }
  533. const CKeyStore& keystore = tempKeystore;
  534. bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
  535. // Sign what we can:
  536. for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
  537. CTxIn& txin = mergedTx.vin[i];
  538. const Coin& coin = view.AccessCoin(txin.prevout);
  539. if (coin.IsSpent()) {
  540. fComplete = false;
  541. continue;
  542. }
  543. const CScript& prevPubKey = coin.out.scriptPubKey;
  544. const CAmount& amount = coin.out.nValue;
  545. SignatureData sigdata;
  546. // Only sign SIGHASH_SINGLE if there's a corresponding output:
  547. if (!fHashSingle || (i < mergedTx.vout.size()))
  548. ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
  549. // ... and merge in other signatures:
  550. for (const CTransaction& txv : txVariants)
  551. sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
  552. UpdateTransaction(mergedTx, i, sigdata);
  553. if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
  554. fComplete = false;
  555. }
  556. if (fComplete) {
  557. // do nothing... for now
  558. // perhaps store this for later optional JSON output
  559. }
  560. tx = mergedTx;
  561. }
  562. class Secp256k1Init
  563. {
  564. ECCVerifyHandle globalVerifyHandle;
  565. public:
  566. Secp256k1Init() {
  567. ECC_Start();
  568. }
  569. ~Secp256k1Init() {
  570. ECC_Stop();
  571. }
  572. };
  573. static void MutateTx(CMutableTransaction& tx, const std::string& command,
  574. const std::string& commandVal)
  575. {
  576. std::unique_ptr<Secp256k1Init> ecc;
  577. if (command == "nversion")
  578. MutateTxVersion(tx, commandVal);
  579. else if (command == "locktime")
  580. MutateTxLocktime(tx, commandVal);
  581. else if (command == "replaceable") {
  582. MutateTxRBFOptIn(tx, commandVal);
  583. }
  584. else if (command == "delin")
  585. MutateTxDelInput(tx, commandVal);
  586. else if (command == "in")
  587. MutateTxAddInput(tx, commandVal);
  588. else if (command == "delout")
  589. MutateTxDelOutput(tx, commandVal);
  590. else if (command == "outaddr")
  591. MutateTxAddOutAddr(tx, commandVal);
  592. else if (command == "outpubkey") {
  593. if (!ecc) { ecc.reset(new Secp256k1Init()); }
  594. MutateTxAddOutPubKey(tx, commandVal);
  595. } else if (command == "outmultisig") {
  596. if (!ecc) { ecc.reset(new Secp256k1Init()); }
  597. MutateTxAddOutMultiSig(tx, commandVal);
  598. } else if (command == "outscript")
  599. MutateTxAddOutScript(tx, commandVal);
  600. else if (command == "outdata")
  601. MutateTxAddOutData(tx, commandVal);
  602. else if (command == "sign") {
  603. if (!ecc) { ecc.reset(new Secp256k1Init()); }
  604. MutateTxSign(tx, commandVal);
  605. }
  606. else if (command == "load")
  607. RegisterLoad(commandVal);
  608. else if (command == "set")
  609. RegisterSet(commandVal);
  610. else
  611. throw std::runtime_error("unknown command");
  612. }
  613. static void OutputTxJSON(const CTransaction& tx)
  614. {
  615. UniValue entry(UniValue::VOBJ);
  616. TxToUniv(tx, uint256(), entry);
  617. std::string jsonOutput = entry.write(4);
  618. fprintf(stdout, "%s\n", jsonOutput.c_str());
  619. }
  620. static void OutputTxHash(const CTransaction& tx)
  621. {
  622. std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
  623. fprintf(stdout, "%s\n", strHexHash.c_str());
  624. }
  625. static void OutputTxHex(const CTransaction& tx)
  626. {
  627. std::string strHex = EncodeHexTx(tx);
  628. fprintf(stdout, "%s\n", strHex.c_str());
  629. }
  630. static void OutputTx(const CTransaction& tx)
  631. {
  632. if (gArgs.GetBoolArg("-json", false))
  633. OutputTxJSON(tx);
  634. else if (gArgs.GetBoolArg("-txid", false))
  635. OutputTxHash(tx);
  636. else
  637. OutputTxHex(tx);
  638. }
  639. static std::string readStdin()
  640. {
  641. char buf[4096];
  642. std::string ret;
  643. while (!feof(stdin)) {
  644. size_t bread = fread(buf, 1, sizeof(buf), stdin);
  645. ret.append(buf, bread);
  646. if (bread < sizeof(buf))
  647. break;
  648. }
  649. if (ferror(stdin))
  650. throw std::runtime_error("error reading stdin");
  651. boost::algorithm::trim_right(ret);
  652. return ret;
  653. }
  654. static int CommandLineRawTx(int argc, char* argv[])
  655. {
  656. std::string strPrint;
  657. int nRet = 0;
  658. try {
  659. // Skip switches; Permit common stdin convention "-"
  660. while (argc > 1 && IsSwitchChar(argv[1][0]) &&
  661. (argv[1][1] != 0)) {
  662. argc--;
  663. argv++;
  664. }
  665. CMutableTransaction tx;
  666. int startArg;
  667. if (!fCreateBlank) {
  668. // require at least one param
  669. if (argc < 2)
  670. throw std::runtime_error("too few parameters");
  671. // param: hex-encoded starwels transaction
  672. std::string strHexTx(argv[1]);
  673. if (strHexTx == "-") // "-" implies standard input
  674. strHexTx = readStdin();
  675. if (!DecodeHexTx(tx, strHexTx, true))
  676. throw std::runtime_error("invalid transaction encoding");
  677. startArg = 2;
  678. } else
  679. startArg = 1;
  680. for (int i = startArg; i < argc; i++) {
  681. std::string arg = argv[i];
  682. std::string key, value;
  683. size_t eqpos = arg.find('=');
  684. if (eqpos == std::string::npos)
  685. key = arg;
  686. else {
  687. key = arg.substr(0, eqpos);
  688. value = arg.substr(eqpos + 1);
  689. }
  690. MutateTx(tx, key, value);
  691. }
  692. OutputTx(tx);
  693. }
  694. catch (const boost::thread_interrupted&) {
  695. throw;
  696. }
  697. catch (const std::exception& e) {
  698. strPrint = std::string("error: ") + e.what();
  699. nRet = EXIT_FAILURE;
  700. }
  701. catch (...) {
  702. PrintExceptionContinue(nullptr, "CommandLineRawTx()");
  703. throw;
  704. }
  705. if (strPrint != "") {
  706. fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
  707. }
  708. return nRet;
  709. }
  710. int main(int argc, char* argv[])
  711. {
  712. SetupEnvironment();
  713. try {
  714. int ret = AppInitRawTx(argc, argv);
  715. if (ret != CONTINUE_EXECUTION)
  716. return ret;
  717. }
  718. catch (const std::exception& e) {
  719. PrintExceptionContinue(&e, "AppInitRawTx()");
  720. return EXIT_FAILURE;
  721. } catch (...) {
  722. PrintExceptionContinue(nullptr, "AppInitRawTx()");
  723. return EXIT_FAILURE;
  724. }
  725. int ret = EXIT_FAILURE;
  726. try {
  727. ret = CommandLineRawTx(argc, argv);
  728. }
  729. catch (const std::exception& e) {
  730. PrintExceptionContinue(&e, "CommandLineRawTx()");
  731. } catch (...) {
  732. PrintExceptionContinue(nullptr, "CommandLineRawTx()");
  733. }
  734. return ret;
  735. }