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.
7 #include "chainparams.h"
8 #include "consensus/consensus.h"
9 #include "consensus/validation.h"
11 #include "crypto/equihash.h"
18 #include "rpcserver.h"
20 #include "validationinterface.h"
22 #include "wallet/wallet.h"
27 #include <boost/assign/list_of.hpp>
29 #include "json/json_spirit_utils.h"
30 #include "json/json_spirit_value.h"
32 using namespace json_spirit;
36 * Return average network hashes per second based on the last 'lookup' blocks,
37 * or over the difficulty averaging window if 'lookup' is nonpositive.
38 * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
40 int64_t GetNetworkHashPS(int lookup, int height) {
41 CBlockIndex *pb = chainActive.Tip();
43 if (height >= 0 && height < chainActive.Height())
44 pb = chainActive[height];
46 if (pb == NULL || !pb->nHeight)
49 // If lookup is nonpositive, then use difficulty averaging window.
51 lookup = Params().GetConsensus().nPowAveragingWindow;
53 // If lookup is larger than chain, then set it to chain length.
54 if (lookup > pb->nHeight)
57 CBlockIndex *pb0 = pb;
58 int64_t minTime = pb0->GetBlockTime();
59 int64_t maxTime = minTime;
60 for (int i = 0; i < lookup; i++) {
62 int64_t time = pb0->GetBlockTime();
63 minTime = std::min(time, minTime);
64 maxTime = std::max(time, maxTime);
67 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
68 if (minTime == maxTime)
71 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
72 int64_t timeDiff = maxTime - minTime;
74 return (int64_t)(workDiff.getdouble() / timeDiff);
77 Value getlocalsolps(const Array& params, bool fHelp)
82 "\nReturns the average local solutions per second since this node was started.\n"
83 "This is the same information shown on the metrics screen (if enabled).\n"
85 "xxx.xxxxx (numeric) Solutions per second average\n"
87 + HelpExampleCli("getlocalsolps", "")
88 + HelpExampleRpc("getlocalsolps", "")
92 return GetLocalSolPS();
95 Value getnetworksolps(const Array& params, bool fHelp)
97 if (fHelp || params.size() > 2)
99 "getnetworksolps ( blocks height )\n"
100 "\nReturns the estimated network solutions per second based on the last n blocks.\n"
101 "Pass in [blocks] to override # of blocks, -1 specifies over difficulty averaging window.\n"
102 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
104 "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks over difficulty averaging window.\n"
105 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
107 "x (numeric) Solutions per second estimated\n"
109 + HelpExampleCli("getnetworksolps", "")
110 + HelpExampleRpc("getnetworksolps", "")
114 return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
117 Value getnetworkhashps(const Array& params, bool fHelp)
119 if (fHelp || params.size() > 2)
121 "getnetworkhashps ( blocks height )\n"
122 "\nDEPRECATED - left for backwards-compatibility. Use getnetworksolps instead.\n"
123 "\nReturns the estimated network solutions per second based on the last n blocks.\n"
124 "Pass in [blocks] to override # of blocks, -1 specifies over difficulty averaging window.\n"
125 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
127 "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks over difficulty averaging window.\n"
128 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
130 "x (numeric) Solutions per second estimated\n"
132 + HelpExampleCli("getnetworkhashps", "")
133 + HelpExampleRpc("getnetworkhashps", "")
137 return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
141 Value getgenerate(const Array& params, bool fHelp)
143 if (fHelp || params.size() != 0)
146 "\nReturn if the server is set to generate coins or not. The default is false.\n"
147 "It is set with the command line argument -gen (or zcash.conf setting gen)\n"
148 "It can also be set with the setgenerate call.\n"
150 "true|false (boolean) If the server is set to generate coins or not\n"
152 + HelpExampleCli("getgenerate", "")
153 + HelpExampleRpc("getgenerate", "")
157 return GetBoolArg("-gen", false);
160 Value generate(const Array& params, bool fHelp)
162 if (fHelp || params.size() < 1 || params.size() > 1)
164 "generate numblocks\n"
165 "\nMine blocks immediately (before the RPC call returns)\n"
166 "\nNote: this function can only be used on the regtest network\n"
168 "1. numblocks (numeric) How many blocks are generated immediately.\n"
170 "[ blockhashes ] (array) hashes of blocks generated\n"
172 "\nGenerate 11 blocks\n"
173 + HelpExampleCli("generate", "11")
176 if (pwalletMain == NULL)
177 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
178 if (!Params().MineBlocksOnDemand())
179 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
181 int nHeightStart = 0;
184 int nGenerate = params[0].get_int();
185 CReserveKey reservekey(pwalletMain);
187 { // Don't keep cs_main locked
189 nHeightStart = chainActive.Height();
190 nHeight = nHeightStart;
191 nHeightEnd = nHeightStart+nGenerate;
193 unsigned int nExtraNonce = 0;
195 unsigned int n = Params().EquihashN();
196 unsigned int k = Params().EquihashK();
197 while (nHeight < nHeightEnd)
199 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
200 if (!pblocktemplate.get())
201 throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty");
202 CBlock *pblock = &pblocktemplate->block;
205 IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
209 crypto_generichash_blake2b_state eh_state;
210 EhInitialiseState(n, k, eh_state);
212 // I = the block header minus nonce and solution.
213 CEquihashInput I{*pblock};
214 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
218 crypto_generichash_blake2b_update(&eh_state, (unsigned char*)&ss[0], ss.size());
221 // Yes, there is a chance every nonce could fail to satisfy the -regtest
222 // target -- 1 in 2^(2^256). That ain't gonna happen
223 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
226 crypto_generichash_blake2b_state curr_state;
227 curr_state = eh_state;
228 crypto_generichash_blake2b_update(&curr_state,
229 pblock->nNonce.begin(),
230 pblock->nNonce.size());
232 // (x_1, x_2, ...) = A(I, V, n, k)
233 std::function<bool(std::vector<unsigned char>)> validBlock =
234 [&pblock](std::vector<unsigned char> soln) {
235 pblock->nSolution = soln;
236 solutionTargetChecks.increment();
237 return CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus());
239 bool found = EhBasicSolveUncancellable(n, k, curr_state, validBlock);
240 ehSolverRuns.increment();
246 CValidationState state;
247 if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
248 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
250 blockHashes.push_back(pblock->GetHash().GetHex());
256 Value setgenerate(const Array& params, bool fHelp)
258 if (fHelp || params.size() < 1 || params.size() > 2)
260 "setgenerate generate ( genproclimit )\n"
261 "\nSet 'generate' true or false to turn generation on or off.\n"
262 "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
263 "See the getgenerate call for the current setting.\n"
265 "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
266 "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
268 "\nSet the generation on with a limit of one processor\n"
269 + HelpExampleCli("setgenerate", "true 1") +
270 "\nCheck the setting\n"
271 + HelpExampleCli("getgenerate", "") +
272 "\nTurn off generation\n"
273 + HelpExampleCli("setgenerate", "false") +
275 + HelpExampleRpc("setgenerate", "true, 1")
278 if (pwalletMain == NULL)
279 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
280 if (Params().MineBlocksOnDemand())
281 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network");
283 bool fGenerate = true;
284 if (params.size() > 0)
285 fGenerate = params[0].get_bool();
287 int nGenProcLimit = -1;
288 if (params.size() > 1)
290 nGenProcLimit = params[1].get_int();
291 if (nGenProcLimit == 0)
295 mapArgs["-gen"] = (fGenerate ? "1" : "0");
296 mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
297 GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
304 Value getmininginfo(const Array& params, bool fHelp)
306 if (fHelp || params.size() != 0)
309 "\nReturns a json object containing mining-related information."
312 " \"blocks\": nnn, (numeric) The current block\n"
313 " \"currentblocksize\": nnn, (numeric) The last block size\n"
314 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
315 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
316 " \"errors\": \"...\" (string) Current errors\n"
317 " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
318 " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
319 " \"localsolps\": xxx.xxxxx (numeric) The average local solution rate in Sol/s since this node was started\n"
320 " \"networksolps\": x (numeric) The estimated network solution rate in Sol/s\n"
321 " \"pooledtx\": n (numeric) The size of the mem pool\n"
322 " \"testnet\": true|false (boolean) If using testnet or not\n"
323 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
326 + HelpExampleCli("getmininginfo", "")
327 + HelpExampleRpc("getmininginfo", "")
334 obj.push_back(Pair("blocks", (int)chainActive.Height()));
335 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
336 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
337 obj.push_back(Pair("difficulty", (double)GetNetworkDifficulty()));
338 obj.push_back(Pair("errors", GetWarnings("statusbar")));
339 obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
340 obj.push_back(Pair("localsolps" , getlocalsolps(params, false)));
341 obj.push_back(Pair("networksolps", getnetworksolps(params, false)));
342 obj.push_back(Pair("networkhashps", getnetworksolps(params, false)));
343 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
344 obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
345 obj.push_back(Pair("chain", Params().NetworkIDString()));
347 obj.push_back(Pair("generate", getgenerate(params, false)));
353 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
354 Value prioritisetransaction(const Array& params, bool fHelp)
356 if (fHelp || params.size() != 3)
358 "prioritisetransaction <txid> <priority delta> <fee delta>\n"
359 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
361 "1. \"txid\" (string, required) The transaction id.\n"
362 "2. priority delta (numeric, required) The priority to add or subtract.\n"
363 " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
364 " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
365 "3. fee delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
366 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
367 " considers the transaction as it would have paid a higher (or lower) fee.\n"
369 "true (boolean) Returns true\n"
371 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
372 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
377 uint256 hash = ParseHashStr(params[0].get_str(), "txid");
378 CAmount nAmount = params[2].get_int64();
380 mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
385 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
386 static Value BIP22ValidationResult(const CValidationState& state)
391 std::string strRejectReason = state.GetRejectReason();
393 throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
394 if (state.IsInvalid())
396 if (strRejectReason.empty())
398 return strRejectReason;
400 // Should be impossible
405 Value getblocktemplate(const Array& params, bool fHelp)
407 if (fHelp || params.size() > 1)
409 "getblocktemplate ( \"jsonrequestobject\" )\n"
410 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
411 "It returns data needed to construct a block to work on.\n"
412 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
415 "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
417 " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
418 " \"capabilities\":[ (array, optional) A list of strings\n"
419 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
427 " \"version\" : n, (numeric) The block version\n"
428 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
429 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
431 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
432 " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
433 " \"depends\" : [ (array) array of numbers \n"
434 " 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"
437 " \"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"
438 " \"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"
439 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
443 // " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
444 // " \"flags\" : \"flags\" (string) \n"
446 // " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
447 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
448 " \"target\" : \"xxxx\", (string) The hash target\n"
449 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
450 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
451 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
454 " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
455 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
456 " \"sizelimit\" : n, (numeric) limit of block size\n"
457 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
458 " \"bits\" : \"xxx\", (string) compressed target of next block\n"
459 " \"height\" : n (numeric) The height of the next block\n"
463 + HelpExampleCli("getblocktemplate", "")
464 + HelpExampleRpc("getblocktemplate", "")
469 // Wallet is required because we support coinbasetxn
470 if (pwalletMain == NULL) {
471 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
474 std::string strMode = "template";
475 Value lpval = Value::null;
476 // TODO: Re-enable coinbasevalue once a specification has been written
477 bool coinbasetxn = true;
478 if (params.size() > 0)
480 const Object& oparam = params[0].get_obj();
481 const Value& modeval = find_value(oparam, "mode");
482 if (modeval.type() == str_type)
483 strMode = modeval.get_str();
484 else if (modeval.type() == null_type)
489 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
490 lpval = find_value(oparam, "longpollid");
492 if (strMode == "proposal")
494 const Value& dataval = find_value(oparam, "data");
495 if (dataval.type() != str_type)
496 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
499 if (!DecodeHexBlk(block, dataval.get_str()))
500 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
502 uint256 hash = block.GetHash();
503 BlockMap::iterator mi = mapBlockIndex.find(hash);
504 if (mi != mapBlockIndex.end()) {
505 CBlockIndex *pindex = mi->second;
506 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
508 if (pindex->nStatus & BLOCK_FAILED_MASK)
509 return "duplicate-invalid";
510 return "duplicate-inconclusive";
513 CBlockIndex* const pindexPrev = chainActive.Tip();
514 // TestBlockValidity only supports blocks built on the current Tip
515 if (block.hashPrevBlock != pindexPrev->GetBlockHash())
516 return "inconclusive-not-best-prevblk";
517 CValidationState state;
518 TestBlockValidity(state, block, pindexPrev, false, true);
519 return BIP22ValidationResult(state);
523 if (strMode != "template")
524 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
527 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Zcash is not connected!");
529 if (IsInitialBlockDownload())
530 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Zcash is downloading blocks...");
532 static unsigned int nTransactionsUpdatedLast;
534 if (lpval.type() != null_type)
536 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
537 uint256 hashWatchedChain;
538 boost::system_time checktxtime;
539 unsigned int nTransactionsUpdatedLastLP;
541 if (lpval.type() == str_type)
543 // Format: <hashBestChain><nTransactionsUpdatedLast>
544 std::string lpstr = lpval.get_str();
546 hashWatchedChain.SetHex(lpstr.substr(0, 64));
547 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
551 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
552 hashWatchedChain = chainActive.Tip()->GetBlockHash();
553 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
556 // Release the wallet and main lock while waiting
557 LEAVE_CRITICAL_SECTION(cs_main);
559 checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
561 boost::unique_lock<boost::mutex> lock(csBestBlock);
562 while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
564 if (!cvBlockChange.timed_wait(lock, checktxtime))
566 // Timeout: Check transactions for update
567 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
569 checktxtime += boost::posix_time::seconds(10);
573 ENTER_CRITICAL_SECTION(cs_main);
576 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
577 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
581 static CBlockIndex* pindexPrev;
582 static int64_t nStart;
583 static CBlockTemplate* pblocktemplate;
584 if (pindexPrev != chainActive.Tip() ||
585 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
587 // Clear pindexPrev so future calls make a new block, despite any failures from here on
590 // Store the pindexBest used before CreateNewBlockWithKey, to avoid races
591 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
592 CBlockIndex* pindexPrevNew = chainActive.Tip();
598 delete pblocktemplate;
599 pblocktemplate = NULL;
601 CReserveKey reservekey(pwalletMain);
602 pblocktemplate = CreateNewBlockWithKey(reservekey);
604 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
606 // Need to update only after we know CreateNewBlockWithKey succeeded
607 pindexPrev = pindexPrevNew;
609 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
612 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
613 pblock->nNonce = uint256();
615 static const Array aCaps = boost::assign::list_of("proposal");
617 Value txCoinbase = Value::null;
619 map<uint256, int64_t> setTxIndex;
621 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
623 uint256 txHash = tx.GetHash();
624 setTxIndex[txHash] = i++;
626 if (tx.IsCoinBase() && !coinbasetxn)
631 entry.push_back(Pair("data", EncodeHexTx(tx)));
633 entry.push_back(Pair("hash", txHash.GetHex()));
636 BOOST_FOREACH (const CTxIn &in, tx.vin)
638 if (setTxIndex.count(in.prevout.hash))
639 deps.push_back(setTxIndex[in.prevout.hash]);
641 entry.push_back(Pair("depends", deps));
643 int index_in_template = i - 1;
644 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
645 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
647 if (tx.IsCoinBase()) {
648 // Show founders' reward if it is required
649 if (pblock->vtx[0].vout.size() > 1) {
650 // Correct this if GetBlockTemplate changes the order
651 entry.push_back(Pair("foundersreward", (int64_t)tx.vout[1].nValue));
653 entry.push_back(Pair("required", true));
656 transactions.push_back(entry);
661 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
663 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
665 static Array aMutable;
666 if (aMutable.empty())
668 aMutable.push_back("time");
669 aMutable.push_back("transactions");
670 aMutable.push_back("prevblock");
674 result.push_back(Pair("capabilities", aCaps));
675 result.push_back(Pair("version", pblock->nVersion));
676 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
677 result.push_back(Pair("transactions", transactions));
679 assert(txCoinbase.type() == obj_type);
680 result.push_back(Pair("coinbasetxn", txCoinbase));
682 result.push_back(Pair("coinbaseaux", aux));
683 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
685 result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
686 result.push_back(Pair("target", hashTarget.GetHex()));
687 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
688 result.push_back(Pair("mutable", aMutable));
689 result.push_back(Pair("noncerange", "00000000ffffffff"));
690 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
691 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
692 result.push_back(Pair("curtime", pblock->GetBlockTime()));
693 result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
694 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
700 class submitblock_StateCatcher : public CValidationInterface
705 CValidationState state;
707 submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {};
710 virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) {
711 if (block.GetHash() != hash)
718 Value submitblock(const Array& params, bool fHelp)
720 if (fHelp || params.size() < 1 || params.size() > 2)
722 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
723 "\nAttempts to submit new block to network.\n"
724 "The 'jsonparametersobject' parameter is currently ignored.\n"
725 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
728 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
729 "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
731 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
735 + HelpExampleCli("submitblock", "\"mydata\"")
736 + HelpExampleRpc("submitblock", "\"mydata\"")
740 if (!DecodeHexBlk(block, params[0].get_str()))
741 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
743 uint256 hash = block.GetHash();
744 bool fBlockPresent = false;
747 BlockMap::iterator mi = mapBlockIndex.find(hash);
748 if (mi != mapBlockIndex.end()) {
749 CBlockIndex *pindex = mi->second;
750 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
752 if (pindex->nStatus & BLOCK_FAILED_MASK)
753 return "duplicate-invalid";
754 // Otherwise, we might only have the header - process the block before returning
755 fBlockPresent = true;
759 CValidationState state;
760 submitblock_StateCatcher sc(block.GetHash());
761 RegisterValidationInterface(&sc);
762 bool fAccepted = ProcessNewBlock(state, NULL, &block, true, NULL);
763 UnregisterValidationInterface(&sc);
766 if (fAccepted && !sc.found)
767 return "duplicate-inconclusive";
773 return "inconclusive";
776 return BIP22ValidationResult(state);
779 Value estimatefee(const Array& params, bool fHelp)
781 if (fHelp || params.size() != 1)
783 "estimatefee nblocks\n"
784 "\nEstimates the approximate fee per kilobyte\n"
785 "needed for a transaction to begin confirmation\n"
786 "within nblocks blocks.\n"
788 "1. nblocks (numeric)\n"
790 "n : (numeric) estimated fee-per-kilobyte\n"
792 "-1.0 is returned if not enough transactions and\n"
793 "blocks have been observed to make an estimate.\n"
795 + HelpExampleCli("estimatefee", "6")
798 RPCTypeCheck(params, boost::assign::list_of(int_type));
800 int nBlocks = params[0].get_int();
804 CFeeRate feeRate = mempool.estimateFee(nBlocks);
805 if (feeRate == CFeeRate(0))
808 return ValueFromAmount(feeRate.GetFeePerK());
811 Value estimatepriority(const Array& params, bool fHelp)
813 if (fHelp || params.size() != 1)
815 "estimatepriority nblocks\n"
816 "\nEstimates the approximate priority\n"
817 "a zero-fee transaction needs to begin confirmation\n"
818 "within nblocks blocks.\n"
820 "1. nblocks (numeric)\n"
822 "n : (numeric) estimated priority\n"
824 "-1.0 is returned if not enough transactions and\n"
825 "blocks have been observed to make an estimate.\n"
827 + HelpExampleCli("estimatepriority", "6")
830 RPCTypeCheck(params, boost::assign::list_of(int_type));
832 int nBlocks = params[0].get_int();
836 return mempool.estimatePriority(nBlocks);
839 Value getblocksubsidy(const Array& params, bool fHelp)
841 if (fHelp || params.size() > 1)
843 "getblocksubsidy height\n"
844 "\nReturns block subsidy reward, taking into account the mining slow start and the founders reward, of block at index provided.\n"
846 "1. height (numeric, optional) The block height. If not provided, defaults to the current height of the chain.\n"
849 " \"miner\" : x.xxx (numeric) The mining reward amount in ZEC.\n"
850 " \"founders\" : x.xxx (numeric) The founders reward amount in ZEC.\n"
853 + HelpExampleCli("getblocksubsidy", "1000")
854 + HelpExampleRpc("getblockubsidy", "1000")
858 int nHeight = (params.size()==1) ? params[0].get_int() : chainActive.Height();
860 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
862 CAmount nReward = GetBlockSubsidy(nHeight, Params().GetConsensus());
863 CAmount nFoundersReward = 0;
864 if ((nHeight > 0) && (nHeight <= Params().GetConsensus().GetLastFoundersRewardBlockHeight())) {
865 nFoundersReward = nReward/5;
866 nReward -= nFoundersReward;
869 result.push_back(Pair("miner", ValueFromAmount(nReward)));
870 result.push_back(Pair("founders", ValueFromAmount(nFoundersReward)));