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.

rpcmining.cpp 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "rpcserver.h"
  6. #include "chainparams.h"
  7. #include "init.h"
  8. #include "net.h"
  9. #include "main.h"
  10. #include "miner.h"
  11. #include "pow.h"
  12. #ifdef ENABLE_WALLET
  13. #include "db.h"
  14. #include "wallet.h"
  15. #endif
  16. #include <stdint.h>
  17. #include <boost/assign/list_of.hpp>
  18. #include "json/json_spirit_utils.h"
  19. #include "json/json_spirit_value.h"
  20. using namespace json_spirit;
  21. using namespace std;
  22. // Return average network hashes per second based on the last 'lookup' blocks,
  23. // or from the last difficulty change if 'lookup' is nonpositive.
  24. // If 'height' is nonnegative, compute the estimate at the time when a given block was found.
  25. Value GetNetworkHashPS(int lookup, int height) {
  26. CBlockIndex *pb = chainActive.Tip();
  27. if (height >= 0 && height < chainActive.Height())
  28. pb = chainActive[height];
  29. if (pb == NULL || !pb->nHeight)
  30. return 0;
  31. // If lookup is -1, then use blocks since last difficulty change.
  32. if (lookup <= 0)
  33. lookup = pb->nHeight % 2016 + 1;
  34. // If lookup is larger than chain, then set it to chain length.
  35. if (lookup > pb->nHeight)
  36. lookup = pb->nHeight;
  37. CBlockIndex *pb0 = pb;
  38. int64_t minTime = pb0->GetBlockTime();
  39. int64_t maxTime = minTime;
  40. for (int i = 0; i < lookup; i++) {
  41. pb0 = pb0->pprev;
  42. int64_t time = pb0->GetBlockTime();
  43. minTime = std::min(time, minTime);
  44. maxTime = std::max(time, maxTime);
  45. }
  46. // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
  47. if (minTime == maxTime)
  48. return 0;
  49. uint256 workDiff = pb->nChainWork - pb0->nChainWork;
  50. int64_t timeDiff = maxTime - minTime;
  51. return (int64_t)(workDiff.getdouble() / timeDiff);
  52. }
  53. Value getnetworkhashps(const Array& params, bool fHelp)
  54. {
  55. if (fHelp || params.size() > 2)
  56. throw runtime_error(
  57. "getnetworkhashps ( blocks height )\n"
  58. "\nReturns the estimated network hashes per second based on the last n blocks.\n"
  59. "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
  60. "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
  61. "\nArguments:\n"
  62. "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
  63. "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
  64. "\nResult:\n"
  65. "x (numeric) Hashes per second estimated\n"
  66. "\nExamples:\n"
  67. + HelpExampleCli("getnetworkhashps", "")
  68. + HelpExampleRpc("getnetworkhashps", "")
  69. );
  70. return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
  71. }
  72. #ifdef ENABLE_WALLET
  73. Value getgenerate(const Array& params, bool fHelp)
  74. {
  75. if (fHelp || params.size() != 0)
  76. throw runtime_error(
  77. "getgenerate\n"
  78. "\nReturn if the server is set to generate coins or not. The default is false.\n"
  79. "It is set with the command line argument -gen (or bitcoin.conf setting gen)\n"
  80. "It can also be set with the setgenerate call.\n"
  81. "\nResult\n"
  82. "true|false (boolean) If the server is set to generate coins or not\n"
  83. "\nExamples:\n"
  84. + HelpExampleCli("getgenerate", "")
  85. + HelpExampleRpc("getgenerate", "")
  86. );
  87. return GetBoolArg("-gen", false);
  88. }
  89. Value setgenerate(const Array& params, bool fHelp)
  90. {
  91. if (fHelp || params.size() < 1 || params.size() > 2)
  92. throw runtime_error(
  93. "setgenerate generate ( genproclimit )\n"
  94. "\nSet 'generate' true or false to turn generation on or off.\n"
  95. "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
  96. "See the getgenerate call for the current setting.\n"
  97. "\nArguments:\n"
  98. "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
  99. "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
  100. " Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n"
  101. "\nExamples:\n"
  102. "\nSet the generation on with a limit of one processor\n"
  103. + HelpExampleCli("setgenerate", "true 1") +
  104. "\nCheck the setting\n"
  105. + HelpExampleCli("getgenerate", "") +
  106. "\nTurn off generation\n"
  107. + HelpExampleCli("setgenerate", "false") +
  108. "\nUsing json rpc\n"
  109. + HelpExampleRpc("setgenerate", "true, 1")
  110. );
  111. if (pwalletMain == NULL)
  112. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
  113. bool fGenerate = true;
  114. if (params.size() > 0)
  115. fGenerate = params[0].get_bool();
  116. int nGenProcLimit = -1;
  117. if (params.size() > 1)
  118. {
  119. nGenProcLimit = params[1].get_int();
  120. if (nGenProcLimit == 0)
  121. fGenerate = false;
  122. }
  123. // -regtest mode: don't return until nGenProcLimit blocks are generated
  124. if (fGenerate && Params().MineBlocksOnDemand())
  125. {
  126. int nHeightStart = 0;
  127. int nHeightEnd = 0;
  128. int nHeight = 0;
  129. int nGenerate = (nGenProcLimit > 0 ? nGenProcLimit : 1);
  130. { // Don't keep cs_main locked
  131. LOCK(cs_main);
  132. nHeightStart = chainActive.Height();
  133. nHeight = nHeightStart;
  134. nHeightEnd = nHeightStart+nGenerate;
  135. }
  136. int nHeightLast = -1;
  137. while (nHeight < nHeightEnd)
  138. {
  139. if (nHeightLast != nHeight)
  140. {
  141. nHeightLast = nHeight;
  142. GenerateBitcoins(fGenerate, pwalletMain, 1);
  143. }
  144. MilliSleep(1);
  145. { // Don't keep cs_main locked
  146. LOCK(cs_main);
  147. nHeight = chainActive.Height();
  148. }
  149. }
  150. }
  151. else // Not -regtest: start generate thread, return immediately
  152. {
  153. mapArgs["-gen"] = (fGenerate ? "1" : "0");
  154. mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
  155. GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
  156. }
  157. return Value::null;
  158. }
  159. Value gethashespersec(const Array& params, bool fHelp)
  160. {
  161. if (fHelp || params.size() != 0)
  162. throw runtime_error(
  163. "gethashespersec\n"
  164. "\nReturns a recent hashes per second performance measurement while generating.\n"
  165. "See the getgenerate and setgenerate calls to turn generation on and off.\n"
  166. "\nResult:\n"
  167. "n (numeric) The recent hashes per second when generation is on (will return 0 if generation is off)\n"
  168. "\nExamples:\n"
  169. + HelpExampleCli("gethashespersec", "")
  170. + HelpExampleRpc("gethashespersec", "")
  171. );
  172. if (GetTimeMillis() - nHPSTimerStart > 8000)
  173. return (int64_t)0;
  174. return (int64_t)dHashesPerSec;
  175. }
  176. #endif
  177. Value getmininginfo(const Array& params, bool fHelp)
  178. {
  179. if (fHelp || params.size() != 0)
  180. throw runtime_error(
  181. "getmininginfo\n"
  182. "\nReturns a json object containing mining-related information."
  183. "\nResult:\n"
  184. "{\n"
  185. " \"blocks\": nnn, (numeric) The current block\n"
  186. " \"currentblocksize\": nnn, (numeric) The last block size\n"
  187. " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
  188. " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
  189. " \"errors\": \"...\" (string) Current errors\n"
  190. " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
  191. " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
  192. " \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n"
  193. " \"pooledtx\": n (numeric) The size of the mem pool\n"
  194. " \"testnet\": true|false (boolean) If using testnet or not\n"
  195. " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
  196. "}\n"
  197. "\nExamples:\n"
  198. + HelpExampleCli("getmininginfo", "")
  199. + HelpExampleRpc("getmininginfo", "")
  200. );
  201. Object obj;
  202. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  203. obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
  204. obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
  205. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  206. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  207. obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
  208. obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
  209. obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
  210. obj.push_back(Pair("testnet", Params().NetworkID() == CBaseChainParams::TESTNET));
  211. obj.push_back(Pair("chain", Params().NetworkIDString()));
  212. #ifdef ENABLE_WALLET
  213. obj.push_back(Pair("generate", getgenerate(params, false)));
  214. obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
  215. #endif
  216. return obj;
  217. }
  218. Value prioritisetransaction(const Array& params, bool fHelp)
  219. {
  220. if (fHelp || params.size() != 3)
  221. throw runtime_error(
  222. "prioritisetransaction <txid> <priority delta> <fee delta>\n"
  223. "Accepts the transaction into mined blocks at a higher (or lower) priority");
  224. uint256 hash;
  225. hash.SetHex(params[0].get_str());
  226. mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), params[2].get_int64());
  227. return true;
  228. }
  229. Value getblocktemplate(const Array& params, bool fHelp)
  230. {
  231. if (fHelp || params.size() > 1)
  232. throw runtime_error(
  233. "getblocktemplate ( \"jsonrequestobject\" )\n"
  234. "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
  235. "It returns data needed to construct a block to work on.\n"
  236. "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
  237. "\nArguments:\n"
  238. "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
  239. " {\n"
  240. " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
  241. " \"capabilities\":[ (array, optional) A list of strings\n"
  242. " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
  243. " ,...\n"
  244. " ]\n"
  245. " }\n"
  246. "\n"
  247. "\nResult:\n"
  248. "{\n"
  249. " \"version\" : n, (numeric) The block version\n"
  250. " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
  251. " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
  252. " {\n"
  253. " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
  254. " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
  255. " \"depends\" : [ (array) array of numbers \n"
  256. " n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
  257. " ,...\n"
  258. " ],\n"
  259. " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
  260. " \"sigops\" : n, (numeric) total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume there aren't any\n"
  261. " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
  262. " }\n"
  263. " ,...\n"
  264. " ],\n"
  265. " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
  266. " \"flags\" : \"flags\" (string) \n"
  267. " },\n"
  268. " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
  269. " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
  270. " \"target\" : \"xxxx\", (string) The hash target\n"
  271. " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
  272. " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
  273. " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
  274. " ,...\n"
  275. " ],\n"
  276. " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
  277. " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
  278. " \"sizelimit\" : n, (numeric) limit of block size\n"
  279. " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
  280. " \"bits\" : \"xxx\", (string) compressed target of next block\n"
  281. " \"height\" : n (numeric) The height of the next block\n"
  282. "}\n"
  283. "\nExamples:\n"
  284. + HelpExampleCli("getblocktemplate", "")
  285. + HelpExampleRpc("getblocktemplate", "")
  286. );
  287. std::string strMode = "template";
  288. Value lpval = Value::null;
  289. if (params.size() > 0)
  290. {
  291. const Object& oparam = params[0].get_obj();
  292. const Value& modeval = find_value(oparam, "mode");
  293. if (modeval.type() == str_type)
  294. strMode = modeval.get_str();
  295. else if (modeval.type() == null_type)
  296. {
  297. /* Do nothing */
  298. }
  299. else
  300. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  301. lpval = find_value(oparam, "longpollid");
  302. }
  303. if (strMode != "template")
  304. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  305. if (vNodes.empty())
  306. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
  307. if (IsInitialBlockDownload())
  308. throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
  309. static unsigned int nTransactionsUpdatedLast;
  310. if (lpval.type() != null_type)
  311. {
  312. // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
  313. uint256 hashWatchedChain;
  314. boost::system_time checktxtime;
  315. unsigned int nTransactionsUpdatedLastLP;
  316. if (lpval.type() == str_type)
  317. {
  318. // Format: <hashBestChain><nTransactionsUpdatedLast>
  319. std::string lpstr = lpval.get_str();
  320. hashWatchedChain.SetHex(lpstr.substr(0, 64));
  321. nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
  322. }
  323. else
  324. {
  325. // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
  326. hashWatchedChain = chainActive.Tip()->GetBlockHash();
  327. nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
  328. }
  329. // Release the wallet and main lock while waiting
  330. #ifdef ENABLE_WALLET
  331. if(pwalletMain)
  332. LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet);
  333. #endif
  334. LEAVE_CRITICAL_SECTION(cs_main);
  335. {
  336. checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
  337. boost::unique_lock<boost::mutex> lock(csBestBlock);
  338. while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
  339. {
  340. if (!cvBlockChange.timed_wait(lock, checktxtime))
  341. {
  342. // Timeout: Check transactions for update
  343. if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
  344. break;
  345. checktxtime += boost::posix_time::seconds(10);
  346. }
  347. }
  348. }
  349. ENTER_CRITICAL_SECTION(cs_main);
  350. #ifdef ENABLE_WALLET
  351. if(pwalletMain)
  352. ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet);
  353. #endif
  354. if (!IsRPCRunning())
  355. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
  356. // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
  357. }
  358. // Update block
  359. static CBlockIndex* pindexPrev;
  360. static int64_t nStart;
  361. static CBlockTemplate* pblocktemplate;
  362. if (pindexPrev != chainActive.Tip() ||
  363. (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
  364. {
  365. // Clear pindexPrev so future calls make a new block, despite any failures from here on
  366. pindexPrev = NULL;
  367. // Store the pindexBest used before CreateNewBlock, to avoid races
  368. nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
  369. CBlockIndex* pindexPrevNew = chainActive.Tip();
  370. nStart = GetTime();
  371. // Create new block
  372. if(pblocktemplate)
  373. {
  374. delete pblocktemplate;
  375. pblocktemplate = NULL;
  376. }
  377. CScript scriptDummy = CScript() << OP_TRUE;
  378. pblocktemplate = CreateNewBlock(scriptDummy);
  379. if (!pblocktemplate)
  380. throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
  381. // Need to update only after we know CreateNewBlock succeeded
  382. pindexPrev = pindexPrevNew;
  383. }
  384. CBlock* pblock = &pblocktemplate->block; // pointer for convenience
  385. // Update nTime
  386. UpdateTime(*pblock, pindexPrev);
  387. pblock->nNonce = 0;
  388. Array transactions;
  389. map<uint256, int64_t> setTxIndex;
  390. int i = 0;
  391. BOOST_FOREACH (CTransaction& tx, pblock->vtx)
  392. {
  393. uint256 txHash = tx.GetHash();
  394. setTxIndex[txHash] = i++;
  395. if (tx.IsCoinBase())
  396. continue;
  397. Object entry;
  398. CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
  399. ssTx << tx;
  400. entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
  401. entry.push_back(Pair("hash", txHash.GetHex()));
  402. Array deps;
  403. BOOST_FOREACH (const CTxIn &in, tx.vin)
  404. {
  405. if (setTxIndex.count(in.prevout.hash))
  406. deps.push_back(setTxIndex[in.prevout.hash]);
  407. }
  408. entry.push_back(Pair("depends", deps));
  409. int index_in_template = i - 1;
  410. entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
  411. entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
  412. transactions.push_back(entry);
  413. }
  414. Object aux;
  415. aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
  416. uint256 hashTarget = uint256().SetCompact(pblock->nBits);
  417. static Array aMutable;
  418. if (aMutable.empty())
  419. {
  420. aMutable.push_back("time");
  421. aMutable.push_back("transactions");
  422. aMutable.push_back("prevblock");
  423. }
  424. Object result;
  425. result.push_back(Pair("version", pblock->nVersion));
  426. result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
  427. result.push_back(Pair("transactions", transactions));
  428. result.push_back(Pair("coinbaseaux", aux));
  429. result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
  430. result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
  431. result.push_back(Pair("target", hashTarget.GetHex()));
  432. result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
  433. result.push_back(Pair("mutable", aMutable));
  434. result.push_back(Pair("noncerange", "00000000ffffffff"));
  435. result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
  436. result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
  437. result.push_back(Pair("curtime", pblock->GetBlockTime()));
  438. result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
  439. result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
  440. return result;
  441. }
  442. Value submitblock(const Array& params, bool fHelp)
  443. {
  444. if (fHelp || params.size() < 1 || params.size() > 2)
  445. throw runtime_error(
  446. "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
  447. "\nAttempts to submit new block to network.\n"
  448. "The 'jsonparametersobject' parameter is currently ignored.\n"
  449. "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
  450. "\nArguments\n"
  451. "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
  452. "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
  453. " {\n"
  454. " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
  455. " }\n"
  456. "\nResult:\n"
  457. "\nExamples:\n"
  458. + HelpExampleCli("submitblock", "\"mydata\"")
  459. + HelpExampleRpc("submitblock", "\"mydata\"")
  460. );
  461. vector<unsigned char> blockData(ParseHex(params[0].get_str()));
  462. CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
  463. CBlock pblock;
  464. try {
  465. ssBlock >> pblock;
  466. }
  467. catch (std::exception &e) {
  468. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
  469. }
  470. CValidationState state;
  471. bool fAccepted = ProcessBlock(state, NULL, &pblock);
  472. if (!fAccepted)
  473. return "rejected"; // TODO: report validation state
  474. return Value::null;
  475. }
  476. Value estimatefee(const Array& params, bool fHelp)
  477. {
  478. if (fHelp || params.size() != 1)
  479. throw runtime_error(
  480. "estimatefee nblocks\n"
  481. "\nEstimates the approximate fee per kilobyte\n"
  482. "needed for a transaction to get confirmed\n"
  483. "within nblocks blocks.\n"
  484. "\nArguments:\n"
  485. "1. nblocks (numeric)\n"
  486. "\nResult:\n"
  487. "n : (numeric) estimated fee-per-kilobyte\n"
  488. "\n"
  489. "-1.0 is returned if not enough transactions and\n"
  490. "blocks have been observed to make an estimate.\n"
  491. "\nExample:\n"
  492. + HelpExampleCli("estimatefee", "6")
  493. );
  494. RPCTypeCheck(params, boost::assign::list_of(int_type));
  495. int nBlocks = params[0].get_int();
  496. if (nBlocks < 1)
  497. nBlocks = 1;
  498. CFeeRate feeRate = mempool.estimateFee(nBlocks);
  499. if (feeRate == CFeeRate(0))
  500. return -1.0;
  501. return ValueFromAmount(feeRate.GetFeePerK());
  502. }
  503. Value estimatepriority(const Array& params, bool fHelp)
  504. {
  505. if (fHelp || params.size() != 1)
  506. throw runtime_error(
  507. "estimatepriority nblocks\n"
  508. "\nEstimates the approximate priority\n"
  509. "a zero-fee transaction needs to get confirmed\n"
  510. "within nblocks blocks.\n"
  511. "\nArguments:\n"
  512. "1. nblocks (numeric)\n"
  513. "\nResult:\n"
  514. "n : (numeric) estimated priority\n"
  515. "\n"
  516. "-1.0 is returned if not enough transactions and\n"
  517. "blocks have been observed to make an estimate.\n"
  518. "\nExample:\n"
  519. + HelpExampleCli("estimatepriority", "6")
  520. );
  521. RPCTypeCheck(params, boost::assign::list_of(int_type));
  522. int nBlocks = params[0].get_int();
  523. if (nBlocks < 1)
  524. nBlocks = 1;
  525. return mempool.estimatePriority(nBlocks);
  526. }