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 26KB

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