1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
9 #include "chainparams.h"
10 #include "consensus/consensus.h"
11 #include "consensus/params.h"
12 #include "consensus/validation.h"
15 #include "validation.h"
18 #include "policy/fees.h"
20 #include "rpc/blockchain.h"
21 #include "rpc/server.h"
22 #include "txmempool.h"
24 #include "utilstrencodings.h"
25 #include "validationinterface.h"
30 #include <boost/assign/list_of.hpp>
31 #include <boost/shared_ptr.hpp>
36 * Return average network hashes per second based on the last 'lookup' blocks,
37 * or from the last difficulty change if 'lookup' is nonpositive.
38 * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
40 UniValue
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 -1, then use blocks since last difficulty change.
51 lookup
= pb
->nHeight
% Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
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 workDiff
.getdouble() / timeDiff
;
77 UniValue
getnetworkhashps(const JSONRPCRequest
& request
)
79 if (request
.fHelp
|| request
.params
.size() > 2)
80 throw std::runtime_error(
81 "getnetworkhashps ( nblocks height )\n"
82 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
83 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
84 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
86 "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
87 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
89 "x (numeric) Hashes per second estimated\n"
91 + HelpExampleCli("getnetworkhashps", "")
92 + HelpExampleRpc("getnetworkhashps", "")
96 return GetNetworkHashPS(request
.params
.size() > 0 ? request
.params
[0].get_int() : 120, request
.params
.size() > 1 ? request
.params
[1].get_int() : -1);
99 UniValue
generateBlocks(boost::shared_ptr
<CReserveScript
> coinbaseScript
, int nGenerate
, uint64_t nMaxTries
, bool keepScript
)
101 static const int nInnerLoopCount
= 0x10000;
102 int nHeightStart
= 0;
106 { // Don't keep cs_main locked
108 nHeightStart
= chainActive
.Height();
109 nHeight
= nHeightStart
;
110 nHeightEnd
= nHeightStart
+nGenerate
;
112 unsigned int nExtraNonce
= 0;
113 UniValue
blockHashes(UniValue::VARR
);
114 while (nHeight
< nHeightEnd
)
116 std::unique_ptr
<CBlockTemplate
> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript
->reserveScript
));
117 if (!pblocktemplate
.get())
118 throw JSONRPCError(RPC_INTERNAL_ERROR
, "Couldn't create new block");
119 CBlock
*pblock
= &pblocktemplate
->block
;
122 IncrementExtraNonce(pblock
, chainActive
.Tip(), nExtraNonce
);
124 while (nMaxTries
> 0 && pblock
->nNonce
< nInnerLoopCount
&& !CheckProofOfWork(pblock
->GetHash(), pblock
->nBits
, Params().GetConsensus())) {
128 if (nMaxTries
== 0) {
131 if (pblock
->nNonce
== nInnerLoopCount
) {
134 std::shared_ptr
<const CBlock
> shared_pblock
= std::make_shared
<const CBlock
>(*pblock
);
135 if (!ProcessNewBlock(Params(), shared_pblock
, true, NULL
))
136 throw JSONRPCError(RPC_INTERNAL_ERROR
, "ProcessNewBlock, block not accepted");
138 blockHashes
.push_back(pblock
->GetHash().GetHex());
140 //mark script as important because it was used at least for one coinbase output if the script came from the wallet
143 coinbaseScript
->KeepScript();
149 UniValue
generate(const JSONRPCRequest
& request
)
151 if (request
.fHelp
|| request
.params
.size() < 1 || request
.params
.size() > 2)
152 throw std::runtime_error(
153 "generate nblocks ( maxtries )\n"
154 "\nMine up to nblocks blocks immediately (before the RPC call returns)\n"
156 "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
157 "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
159 "[ blockhashes ] (array) hashes of blocks generated\n"
161 "\nGenerate 11 blocks\n"
162 + HelpExampleCli("generate", "11")
165 int nGenerate
= request
.params
[0].get_int();
166 uint64_t nMaxTries
= 1000000;
167 if (request
.params
.size() > 1) {
168 nMaxTries
= request
.params
[1].get_int();
171 boost::shared_ptr
<CReserveScript
> coinbaseScript
;
172 GetMainSignals().ScriptForMining(coinbaseScript
);
174 // If the keypool is exhausted, no script is returned at all. Catch this.
176 throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT
, "Error: Keypool ran out, please call keypoolrefill first");
178 //throw an error if no script was provided
179 if (coinbaseScript
->reserveScript
.empty())
180 throw JSONRPCError(RPC_INTERNAL_ERROR
, "No coinbase script available (mining requires a wallet)");
182 return generateBlocks(coinbaseScript
, nGenerate
, nMaxTries
, true);
185 UniValue
generatetoaddress(const JSONRPCRequest
& request
)
187 if (request
.fHelp
|| request
.params
.size() < 2 || request
.params
.size() > 3)
188 throw std::runtime_error(
189 "generatetoaddress nblocks address (maxtries)\n"
190 "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
192 "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
193 "2. address (string, required) The address to send the newly generated bitcoin to.\n"
194 "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
196 "[ blockhashes ] (array) hashes of blocks generated\n"
198 "\nGenerate 11 blocks to myaddress\n"
199 + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
202 int nGenerate
= request
.params
[0].get_int();
203 uint64_t nMaxTries
= 1000000;
204 if (request
.params
.size() > 2) {
205 nMaxTries
= request
.params
[2].get_int();
208 CBitcoinAddress
address(request
.params
[1].get_str());
209 if (!address
.IsValid())
210 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Error: Invalid address");
212 boost::shared_ptr
<CReserveScript
> coinbaseScript(new CReserveScript());
213 coinbaseScript
->reserveScript
= GetScriptForDestination(address
.Get());
215 return generateBlocks(coinbaseScript
, nGenerate
, nMaxTries
, false);
218 UniValue
getmininginfo(const JSONRPCRequest
& request
)
220 if (request
.fHelp
|| request
.params
.size() != 0)
221 throw std::runtime_error(
223 "\nReturns a json object containing mining-related information."
226 " \"blocks\": nnn, (numeric) The current block\n"
227 " \"currentblocksize\": nnn, (numeric) The last block size\n"
228 " \"currentblockweight\": nnn, (numeric) The last block weight\n"
229 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
230 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
231 " \"errors\": \"...\" (string) Current errors\n"
232 " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
233 " \"pooledtx\": n (numeric) The size of the mempool\n"
234 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
237 + HelpExampleCli("getmininginfo", "")
238 + HelpExampleRpc("getmininginfo", "")
244 UniValue
obj(UniValue::VOBJ
);
245 obj
.push_back(Pair("blocks", (int)chainActive
.Height()));
246 obj
.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize
));
247 obj
.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight
));
248 obj
.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx
));
249 obj
.push_back(Pair("difficulty", (double)GetDifficulty()));
250 obj
.push_back(Pair("errors", GetWarnings("statusbar")));
251 obj
.push_back(Pair("networkhashps", getnetworkhashps(request
)));
252 obj
.push_back(Pair("pooledtx", (uint64_t)mempool
.size()));
253 obj
.push_back(Pair("chain", Params().NetworkIDString()));
258 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
259 UniValue
prioritisetransaction(const JSONRPCRequest
& request
)
261 if (request
.fHelp
|| request
.params
.size() != 2)
262 throw std::runtime_error(
263 "prioritisetransaction <txid> <fee delta>\n"
264 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
266 "1. \"txid\" (string, required) The transaction id.\n"
267 "2. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
268 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
269 " considers the transaction as it would have paid a higher (or lower) fee.\n"
271 "true (boolean) Returns true\n"
273 + HelpExampleCli("prioritisetransaction", "\"txid\" 10000")
274 + HelpExampleRpc("prioritisetransaction", "\"txid\", 10000")
279 uint256 hash
= ParseHashStr(request
.params
[0].get_str(), "txid");
280 CAmount nAmount
= request
.params
[1].get_int64();
282 mempool
.PrioritiseTransaction(hash
, nAmount
);
287 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
288 static UniValue
BIP22ValidationResult(const CValidationState
& state
)
293 std::string strRejectReason
= state
.GetRejectReason();
295 throw JSONRPCError(RPC_VERIFY_ERROR
, strRejectReason
);
296 if (state
.IsInvalid())
298 if (strRejectReason
.empty())
300 return strRejectReason
;
302 // Should be impossible
306 std::string
gbt_vb_name(const Consensus::DeploymentPos pos
) {
307 const struct BIP9DeploymentInfo
& vbinfo
= VersionBitsDeploymentInfo
[pos
];
308 std::string s
= vbinfo
.name
;
309 if (!vbinfo
.gbt_force
) {
310 s
.insert(s
.begin(), '!');
315 UniValue
getblocktemplate(const JSONRPCRequest
& request
)
317 if (request
.fHelp
|| request
.params
.size() > 1)
318 throw std::runtime_error(
319 "getblocktemplate ( TemplateRequest )\n"
320 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
321 "It returns data needed to construct a block to work on.\n"
322 "For full specification, see BIPs 22, 23, 9, and 145:\n"
323 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
324 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
325 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
326 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
329 "1. template_request (json object, optional) A json object in the following spec\n"
331 " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
332 " \"capabilities\":[ (array, optional) A list of strings\n"
333 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
336 " \"rules\":[ (array, optional) A list of strings\n"
337 " \"support\" (string) client side supported softfork deployment\n"
345 " \"version\" : n, (numeric) The preferred block version\n"
346 " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
347 " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
348 " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
351 " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
352 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
353 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
355 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
356 " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
357 " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
358 " \"depends\" : [ (array) array of numbers \n"
359 " 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"
362 " \"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"
363 " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
364 " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
365 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
369 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
370 " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
372 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
373 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
374 " \"target\" : \"xxxx\", (string) The hash target\n"
375 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
376 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
377 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
380 " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
381 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
382 " \"sizelimit\" : n, (numeric) limit of block size\n"
383 " \"weightlimit\" : n, (numeric) limit of block weight\n"
384 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
385 " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
386 " \"height\" : n (numeric) The height of the next block\n"
390 + HelpExampleCli("getblocktemplate", "")
391 + HelpExampleRpc("getblocktemplate", "")
396 std::string strMode
= "template";
397 UniValue lpval
= NullUniValue
;
398 std::set
<std::string
> setClientRules
;
399 int64_t nMaxVersionPreVB
= -1;
400 if (request
.params
.size() > 0)
402 const UniValue
& oparam
= request
.params
[0].get_obj();
403 const UniValue
& modeval
= find_value(oparam
, "mode");
405 strMode
= modeval
.get_str();
406 else if (modeval
.isNull())
411 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid mode");
412 lpval
= find_value(oparam
, "longpollid");
414 if (strMode
== "proposal")
416 const UniValue
& dataval
= find_value(oparam
, "data");
417 if (!dataval
.isStr())
418 throw JSONRPCError(RPC_TYPE_ERROR
, "Missing data String key for proposal");
421 if (!DecodeHexBlk(block
, dataval
.get_str()))
422 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "Block decode failed");
424 uint256 hash
= block
.GetHash();
425 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
426 if (mi
!= mapBlockIndex
.end()) {
427 CBlockIndex
*pindex
= mi
->second
;
428 if (pindex
->IsValid(BLOCK_VALID_SCRIPTS
))
430 if (pindex
->nStatus
& BLOCK_FAILED_MASK
)
431 return "duplicate-invalid";
432 return "duplicate-inconclusive";
435 CBlockIndex
* const pindexPrev
= chainActive
.Tip();
436 // TestBlockValidity only supports blocks built on the current Tip
437 if (block
.hashPrevBlock
!= pindexPrev
->GetBlockHash())
438 return "inconclusive-not-best-prevblk";
439 CValidationState state
;
440 TestBlockValidity(state
, Params(), block
, pindexPrev
, false, true);
441 return BIP22ValidationResult(state
);
444 const UniValue
& aClientRules
= find_value(oparam
, "rules");
445 if (aClientRules
.isArray()) {
446 for (unsigned int i
= 0; i
< aClientRules
.size(); ++i
) {
447 const UniValue
& v
= aClientRules
[i
];
448 setClientRules
.insert(v
.get_str());
451 // NOTE: It is important that this NOT be read if versionbits is supported
452 const UniValue
& uvMaxVersion
= find_value(oparam
, "maxversion");
453 if (uvMaxVersion
.isNum()) {
454 nMaxVersionPreVB
= uvMaxVersion
.get_int64();
459 if (strMode
!= "template")
460 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid mode");
463 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED
, "Error: Peer-to-peer functionality missing or disabled");
465 if (g_connman
->GetNodeCount(CConnman::CONNECTIONS_ALL
) == 0)
466 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED
, "Bitcoin is not connected!");
468 if (IsInitialBlockDownload())
469 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD
, "Bitcoin is downloading blocks...");
471 static unsigned int nTransactionsUpdatedLast
;
475 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
476 uint256 hashWatchedChain
;
477 boost::system_time checktxtime
;
478 unsigned int nTransactionsUpdatedLastLP
;
482 // Format: <hashBestChain><nTransactionsUpdatedLast>
483 std::string lpstr
= lpval
.get_str();
485 hashWatchedChain
.SetHex(lpstr
.substr(0, 64));
486 nTransactionsUpdatedLastLP
= atoi64(lpstr
.substr(64));
490 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
491 hashWatchedChain
= chainActive
.Tip()->GetBlockHash();
492 nTransactionsUpdatedLastLP
= nTransactionsUpdatedLast
;
495 // Release the wallet and main lock while waiting
496 LEAVE_CRITICAL_SECTION(cs_main
);
498 checktxtime
= boost::get_system_time() + boost::posix_time::minutes(1);
500 boost::unique_lock
<boost::mutex
> lock(csBestBlock
);
501 while (chainActive
.Tip()->GetBlockHash() == hashWatchedChain
&& IsRPCRunning())
503 if (!cvBlockChange
.timed_wait(lock
, checktxtime
))
505 // Timeout: Check transactions for update
506 if (mempool
.GetTransactionsUpdated() != nTransactionsUpdatedLastLP
)
508 checktxtime
+= boost::posix_time::seconds(10);
512 ENTER_CRITICAL_SECTION(cs_main
);
515 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED
, "Shutting down");
516 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
519 const struct BIP9DeploymentInfo
& segwit_info
= VersionBitsDeploymentInfo
[Consensus::DEPLOYMENT_SEGWIT
];
520 // If the caller is indicating segwit support, then allow CreateNewBlock()
521 // to select witness transactions, after segwit activates (otherwise
523 bool fSupportsSegwit
= setClientRules
.find(segwit_info
.name
) != setClientRules
.end();
526 static CBlockIndex
* pindexPrev
;
527 static int64_t nStart
;
528 static std::unique_ptr
<CBlockTemplate
> pblocktemplate
;
529 // Cache whether the last invocation was with segwit support, to avoid returning
530 // a segwit-block to a non-segwit caller.
531 static bool fLastTemplateSupportsSegwit
= true;
532 if (pindexPrev
!= chainActive
.Tip() ||
533 (mempool
.GetTransactionsUpdated() != nTransactionsUpdatedLast
&& GetTime() - nStart
> 5) ||
534 fLastTemplateSupportsSegwit
!= fSupportsSegwit
)
536 // Clear pindexPrev so future calls make a new block, despite any failures from here on
537 pindexPrev
= nullptr;
539 // Store the pindexBest used before CreateNewBlock, to avoid races
540 nTransactionsUpdatedLast
= mempool
.GetTransactionsUpdated();
541 CBlockIndex
* pindexPrevNew
= chainActive
.Tip();
543 fLastTemplateSupportsSegwit
= fSupportsSegwit
;
546 CScript scriptDummy
= CScript() << OP_TRUE
;
547 pblocktemplate
= BlockAssembler(Params()).CreateNewBlock(scriptDummy
, fSupportsSegwit
);
549 throw JSONRPCError(RPC_OUT_OF_MEMORY
, "Out of memory");
551 // Need to update only after we know CreateNewBlock succeeded
552 pindexPrev
= pindexPrevNew
;
554 CBlock
* pblock
= &pblocktemplate
->block
; // pointer for convenience
555 const Consensus::Params
& consensusParams
= Params().GetConsensus();
558 UpdateTime(pblock
, consensusParams
, pindexPrev
);
561 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
562 const bool fPreSegWit
= (THRESHOLD_ACTIVE
!= VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
));
564 UniValue
aCaps(UniValue::VARR
); aCaps
.push_back("proposal");
566 UniValue
transactions(UniValue::VARR
);
567 std::map
<uint256
, int64_t> setTxIndex
;
569 for (const auto& it
: pblock
->vtx
) {
570 const CTransaction
& tx
= *it
;
571 uint256 txHash
= tx
.GetHash();
572 setTxIndex
[txHash
] = i
++;
577 UniValue
entry(UniValue::VOBJ
);
579 entry
.push_back(Pair("data", EncodeHexTx(tx
)));
580 entry
.push_back(Pair("txid", txHash
.GetHex()));
581 entry
.push_back(Pair("hash", tx
.GetWitnessHash().GetHex()));
583 UniValue
deps(UniValue::VARR
);
584 BOOST_FOREACH (const CTxIn
&in
, tx
.vin
)
586 if (setTxIndex
.count(in
.prevout
.hash
))
587 deps
.push_back(setTxIndex
[in
.prevout
.hash
]);
589 entry
.push_back(Pair("depends", deps
));
591 int index_in_template
= i
- 1;
592 entry
.push_back(Pair("fee", pblocktemplate
->vTxFees
[index_in_template
]));
593 int64_t nTxSigOps
= pblocktemplate
->vTxSigOpsCost
[index_in_template
];
595 assert(nTxSigOps
% WITNESS_SCALE_FACTOR
== 0);
596 nTxSigOps
/= WITNESS_SCALE_FACTOR
;
598 entry
.push_back(Pair("sigops", nTxSigOps
));
599 entry
.push_back(Pair("weight", GetTransactionWeight(tx
)));
601 transactions
.push_back(entry
);
604 UniValue
aux(UniValue::VOBJ
);
605 aux
.push_back(Pair("flags", HexStr(COINBASE_FLAGS
.begin(), COINBASE_FLAGS
.end())));
607 arith_uint256 hashTarget
= arith_uint256().SetCompact(pblock
->nBits
);
609 UniValue
aMutable(UniValue::VARR
);
610 aMutable
.push_back("time");
611 aMutable
.push_back("transactions");
612 aMutable
.push_back("prevblock");
614 UniValue
result(UniValue::VOBJ
);
615 result
.push_back(Pair("capabilities", aCaps
));
617 UniValue
aRules(UniValue::VARR
);
618 UniValue
vbavailable(UniValue::VOBJ
);
619 for (int j
= 0; j
< (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS
; ++j
) {
620 Consensus::DeploymentPos pos
= Consensus::DeploymentPos(j
);
621 ThresholdState state
= VersionBitsState(pindexPrev
, consensusParams
, pos
, versionbitscache
);
623 case THRESHOLD_DEFINED
:
624 case THRESHOLD_FAILED
:
625 // Not exposed to GBT at all
627 case THRESHOLD_LOCKED_IN
:
628 // Ensure bit is set in block version
629 pblock
->nVersion
|= VersionBitsMask(consensusParams
, pos
);
630 // FALL THROUGH to get vbavailable set...
631 case THRESHOLD_STARTED
:
633 const struct BIP9DeploymentInfo
& vbinfo
= VersionBitsDeploymentInfo
[pos
];
634 vbavailable
.push_back(Pair(gbt_vb_name(pos
), consensusParams
.vDeployments
[pos
].bit
));
635 if (setClientRules
.find(vbinfo
.name
) == setClientRules
.end()) {
636 if (!vbinfo
.gbt_force
) {
637 // If the client doesn't support this, don't indicate it in the [default] version
638 pblock
->nVersion
&= ~VersionBitsMask(consensusParams
, pos
);
643 case THRESHOLD_ACTIVE
:
646 const struct BIP9DeploymentInfo
& vbinfo
= VersionBitsDeploymentInfo
[pos
];
647 aRules
.push_back(gbt_vb_name(pos
));
648 if (setClientRules
.find(vbinfo
.name
) == setClientRules
.end()) {
649 // Not supported by the client; make sure it's safe to proceed
650 if (!vbinfo
.gbt_force
) {
651 // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
652 throw JSONRPCError(RPC_INVALID_PARAMETER
, strprintf("Support for '%s' rule requires explicit client support", vbinfo
.name
));
659 result
.push_back(Pair("version", pblock
->nVersion
));
660 result
.push_back(Pair("rules", aRules
));
661 result
.push_back(Pair("vbavailable", vbavailable
));
662 result
.push_back(Pair("vbrequired", int(0)));
664 if (nMaxVersionPreVB
>= 2) {
665 // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
666 // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
667 // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
668 // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
669 aMutable
.push_back("version/force");
672 result
.push_back(Pair("previousblockhash", pblock
->hashPrevBlock
.GetHex()));
673 result
.push_back(Pair("transactions", transactions
));
674 result
.push_back(Pair("coinbaseaux", aux
));
675 result
.push_back(Pair("coinbasevalue", (int64_t)pblock
->vtx
[0]->vout
[0].nValue
));
676 result
.push_back(Pair("longpollid", chainActive
.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast
)));
677 result
.push_back(Pair("target", hashTarget
.GetHex()));
678 result
.push_back(Pair("mintime", (int64_t)pindexPrev
->GetMedianTimePast()+1));
679 result
.push_back(Pair("mutable", aMutable
));
680 result
.push_back(Pair("noncerange", "00000000ffffffff"));
681 int64_t nSigOpLimit
= MAX_BLOCK_SIGOPS_COST
;
683 assert(nSigOpLimit
% WITNESS_SCALE_FACTOR
== 0);
684 nSigOpLimit
/= WITNESS_SCALE_FACTOR
;
686 result
.push_back(Pair("sigoplimit", nSigOpLimit
));
688 result
.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_BASE_SIZE
));
690 result
.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SERIALIZED_SIZE
));
691 result
.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT
));
693 result
.push_back(Pair("curtime", pblock
->GetBlockTime()));
694 result
.push_back(Pair("bits", strprintf("%08x", pblock
->nBits
)));
695 result
.push_back(Pair("height", (int64_t)(pindexPrev
->nHeight
+1)));
697 if (!pblocktemplate
->vchCoinbaseCommitment
.empty() && fSupportsSegwit
) {
698 result
.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate
->vchCoinbaseCommitment
.begin(), pblocktemplate
->vchCoinbaseCommitment
.end())));
704 class submitblock_StateCatcher
: public CValidationInterface
709 CValidationState state
;
711 submitblock_StateCatcher(const uint256
&hashIn
) : hash(hashIn
), found(false), state() {}
714 virtual void BlockChecked(const CBlock
& block
, const CValidationState
& stateIn
) {
715 if (block
.GetHash() != hash
)
722 UniValue
submitblock(const JSONRPCRequest
& request
)
724 if (request
.fHelp
|| request
.params
.size() < 1 || request
.params
.size() > 2) {
725 throw std::runtime_error(
726 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
727 "\nAttempts to submit new block to network.\n"
728 "The 'jsonparametersobject' parameter is currently ignored.\n"
729 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
732 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
733 "2. \"parameters\" (string, optional) object of optional parameters\n"
735 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
739 + HelpExampleCli("submitblock", "\"mydata\"")
740 + HelpExampleRpc("submitblock", "\"mydata\"")
744 std::shared_ptr
<CBlock
> blockptr
= std::make_shared
<CBlock
>();
745 CBlock
& block
= *blockptr
;
746 if (!DecodeHexBlk(block
, request
.params
[0].get_str())) {
747 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "Block decode failed");
750 if (block
.vtx
.empty() || !block
.vtx
[0]->IsCoinBase()) {
751 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "Block does not start with a coinbase");
754 uint256 hash
= block
.GetHash();
755 bool fBlockPresent
= false;
758 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
759 if (mi
!= mapBlockIndex
.end()) {
760 CBlockIndex
*pindex
= mi
->second
;
761 if (pindex
->IsValid(BLOCK_VALID_SCRIPTS
)) {
764 if (pindex
->nStatus
& BLOCK_FAILED_MASK
) {
765 return "duplicate-invalid";
767 // Otherwise, we might only have the header - process the block before returning
768 fBlockPresent
= true;
774 BlockMap::iterator mi
= mapBlockIndex
.find(block
.hashPrevBlock
);
775 if (mi
!= mapBlockIndex
.end()) {
776 UpdateUncommittedBlockStructures(block
, mi
->second
, Params().GetConsensus());
780 submitblock_StateCatcher
sc(block
.GetHash());
781 RegisterValidationInterface(&sc
);
782 bool fAccepted
= ProcessNewBlock(Params(), blockptr
, true, NULL
);
783 UnregisterValidationInterface(&sc
);
785 if (fAccepted
&& !sc
.found
) {
786 return "duplicate-inconclusive";
791 return "inconclusive";
793 return BIP22ValidationResult(sc
.state
);
796 UniValue
estimatefee(const JSONRPCRequest
& request
)
798 if (request
.fHelp
|| request
.params
.size() != 1)
799 throw std::runtime_error(
800 "estimatefee nblocks\n"
801 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
802 "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
803 "as defined in BIP 141 (witness data is discounted).\n"
805 "1. nblocks (numeric, required)\n"
807 "n (numeric) estimated fee-per-kilobyte\n"
809 "A negative value is returned if not enough transactions and blocks\n"
810 "have been observed to make an estimate.\n"
811 "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
812 "a fee that is high enough to get reliably included in the next block.\n"
814 + HelpExampleCli("estimatefee", "6")
817 RPCTypeCheck(request
.params
, boost::assign::list_of(UniValue::VNUM
));
819 int nBlocks
= request
.params
[0].get_int();
823 CFeeRate feeRate
= ::feeEstimator
.estimateFee(nBlocks
);
824 if (feeRate
== CFeeRate(0))
827 return ValueFromAmount(feeRate
.GetFeePerK());
830 UniValue
estimatesmartfee(const JSONRPCRequest
& request
)
832 if (request
.fHelp
|| request
.params
.size() != 1)
833 throw std::runtime_error(
834 "estimatesmartfee nblocks\n"
835 "\nWARNING: This interface is unstable and may disappear or change!\n"
836 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
837 "confirmation within nblocks blocks if possible and return the number of blocks\n"
838 "for which the estimate is valid. Uses virtual transaction size as defined\n"
839 "in BIP 141 (witness data is discounted).\n"
841 "1. nblocks (numeric)\n"
844 " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
845 " \"blocks\" : n (numeric) block number where estimate was found\n"
848 "A negative value is returned if not enough transactions and blocks\n"
849 "have been observed to make an estimate for any number of blocks.\n"
850 "However it will not return a value below the mempool reject fee.\n"
852 + HelpExampleCli("estimatesmartfee", "6")
855 RPCTypeCheck(request
.params
, boost::assign::list_of(UniValue::VNUM
));
857 int nBlocks
= request
.params
[0].get_int();
859 UniValue
result(UniValue::VOBJ
);
861 CFeeRate feeRate
= ::feeEstimator
.estimateSmartFee(nBlocks
, &answerFound
, ::mempool
);
862 result
.push_back(Pair("feerate", feeRate
== CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate
.GetFeePerK())));
863 result
.push_back(Pair("blocks", answerFound
));
867 static const CRPCCommand commands
[] =
868 { // category name actor (function) okSafeMode
869 // --------------------- ------------------------ ----------------------- ----------
870 { "mining", "getnetworkhashps", &getnetworkhashps
, true, {"nblocks","height"} },
871 { "mining", "getmininginfo", &getmininginfo
, true, {} },
872 { "mining", "prioritisetransaction", &prioritisetransaction
, true, {"txid","fee_delta"} },
873 { "mining", "getblocktemplate", &getblocktemplate
, true, {"template_request"} },
874 { "mining", "submitblock", &submitblock
, true, {"hexdata","parameters"} },
876 { "generating", "generate", &generate
, true, {"nblocks","maxtries"} },
877 { "generating", "generatetoaddress", &generatetoaddress
, true, {"nblocks","address","maxtries"} },
879 { "util", "estimatefee", &estimatefee
, true, {"nblocks"} },
880 { "util", "estimatesmartfee", &estimatesmartfee
, true, {"nblocks"} },
883 void RegisterMiningRPCCommands(CRPCTable
&t
)
885 for (unsigned int vcidx
= 0; vcidx
< ARRAYLEN(commands
); vcidx
++)
886 t
.appendCommand(commands
[vcidx
].name
, &commands
[vcidx
]);