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

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