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.
8 #include "chainparams.h"
9 #include "consensus/consensus.h"
10 #include "consensus/validation.h"
17 #include "rpcserver.h"
18 #include "txmempool.h"
20 #include "utilstrencodings.h"
21 #include "validationinterface.h"
25 #include <boost/assign/list_of.hpp>
26 #include <boost/shared_ptr.hpp>
33 * Return average network hashes per second based on the last 'lookup' blocks,
34 * or from the last difficulty change if 'lookup' is nonpositive.
35 * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
37 UniValue
GetNetworkHashPS(int lookup
, int height
) {
38 CBlockIndex
*pb
= chainActive
.Tip();
40 if (height
>= 0 && height
< chainActive
.Height())
41 pb
= chainActive
[height
];
43 if (pb
== NULL
|| !pb
->nHeight
)
46 // If lookup is -1, then use blocks since last difficulty change.
48 lookup
= pb
->nHeight
% Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
50 // If lookup is larger than chain, then set it to chain length.
51 if (lookup
> pb
->nHeight
)
54 CBlockIndex
*pb0
= pb
;
55 int64_t minTime
= pb0
->GetBlockTime();
56 int64_t maxTime
= minTime
;
57 for (int i
= 0; i
< lookup
; i
++) {
59 int64_t time
= pb0
->GetBlockTime();
60 minTime
= std::min(time
, minTime
);
61 maxTime
= std::max(time
, maxTime
);
64 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
65 if (minTime
== maxTime
)
68 arith_uint256 workDiff
= pb
->nChainWork
- pb0
->nChainWork
;
69 int64_t timeDiff
= maxTime
- minTime
;
71 return (int64_t)(workDiff
.getdouble() / timeDiff
);
74 UniValue
getnetworkhashps(const UniValue
& params
, bool fHelp
)
76 if (fHelp
|| params
.size() > 2)
78 "getnetworkhashps ( blocks height )\n"
79 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
80 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
81 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
83 "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
84 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
86 "x (numeric) Hashes per second estimated\n"
88 + HelpExampleCli("getnetworkhashps", "")
89 + HelpExampleRpc("getnetworkhashps", "")
93 return GetNetworkHashPS(params
.size() > 0 ? params
[0].get_int() : 120, params
.size() > 1 ? params
[1].get_int() : -1);
96 UniValue
getgenerate(const UniValue
& params
, bool fHelp
)
98 if (fHelp
|| params
.size() != 0)
101 "\nReturn if the server is set to generate coins or not. The default is false.\n"
102 "It is set with the command line argument -gen (or " + std::string(BITCOIN_CONF_FILENAME
) + " setting gen)\n"
103 "It can also be set with the setgenerate call.\n"
105 "true|false (boolean) If the server is set to generate coins or not\n"
107 + HelpExampleCli("getgenerate", "")
108 + HelpExampleRpc("getgenerate", "")
112 return GetBoolArg("-gen", DEFAULT_GENERATE
);
115 UniValue
generate(const UniValue
& params
, bool fHelp
)
117 if (fHelp
|| params
.size() < 1 || params
.size() > 1)
119 "generate numblocks\n"
120 "\nMine blocks immediately (before the RPC call returns)\n"
121 "\nNote: this function can only be used on the regtest network\n"
123 "1. numblocks (numeric, required) How many blocks are generated immediately.\n"
125 "[ blockhashes ] (array) hashes of blocks generated\n"
127 "\nGenerate 11 blocks\n"
128 + HelpExampleCli("generate", "11")
131 if (!Params().MineBlocksOnDemand())
132 throw JSONRPCError(RPC_METHOD_NOT_FOUND
, "This method can only be used on regtest");
134 int nHeightStart
= 0;
137 int nGenerate
= params
[0].get_int();
139 boost::shared_ptr
<CReserveScript
> coinbaseScript
;
140 GetMainSignals().ScriptForMining(coinbaseScript
);
142 // If the keypool is exhausted, no script is returned at all. Catch this.
144 throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT
, "Error: Keypool ran out, please call keypoolrefill first");
146 //throw an error if no script was provided
147 if (coinbaseScript
->reserveScript
.empty())
148 throw JSONRPCError(RPC_INTERNAL_ERROR
, "No coinbase script available (mining requires a wallet)");
150 { // Don't keep cs_main locked
152 nHeightStart
= chainActive
.Height();
153 nHeight
= nHeightStart
;
154 nHeightEnd
= nHeightStart
+nGenerate
;
156 unsigned int nExtraNonce
= 0;
157 UniValue
blockHashes(UniValue::VARR
);
158 while (nHeight
< nHeightEnd
)
160 auto_ptr
<CBlockTemplate
> pblocktemplate(CreateNewBlock(Params(), coinbaseScript
->reserveScript
));
161 if (!pblocktemplate
.get())
162 throw JSONRPCError(RPC_INTERNAL_ERROR
, "Couldn't create new block");
163 CBlock
*pblock
= &pblocktemplate
->block
;
166 IncrementExtraNonce(pblock
, chainActive
.Tip(), nExtraNonce
);
168 while (!CheckProofOfWork(pblock
->GetHash(), pblock
->nBits
, Params().GetConsensus())) {
169 // Yes, there is a chance every nonce could fail to satisfy the -regtest
170 // target -- 1 in 2^(2^32). That ain't gonna happen.
173 CValidationState state
;
174 if (!ProcessNewBlock(state
, Params(), NULL
, pblock
, true, NULL
))
175 throw JSONRPCError(RPC_INTERNAL_ERROR
, "ProcessNewBlock, block not accepted");
177 blockHashes
.push_back(pblock
->GetHash().GetHex());
179 //mark script as important because it was used at least for one coinbase output
180 coinbaseScript
->KeepScript();
185 UniValue
setgenerate(const UniValue
& params
, bool fHelp
)
187 if (fHelp
|| params
.size() < 1 || params
.size() > 2)
189 "setgenerate generate ( genproclimit )\n"
190 "\nSet 'generate' true or false to turn generation on or off.\n"
191 "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
192 "See the getgenerate call for the current setting.\n"
194 "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
195 "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
197 "\nSet the generation on with a limit of one processor\n"
198 + HelpExampleCli("setgenerate", "true 1") +
199 "\nCheck the setting\n"
200 + HelpExampleCli("getgenerate", "") +
201 "\nTurn off generation\n"
202 + HelpExampleCli("setgenerate", "false") +
204 + HelpExampleRpc("setgenerate", "true, 1")
207 if (Params().MineBlocksOnDemand())
208 throw JSONRPCError(RPC_METHOD_NOT_FOUND
, "Use the generate method instead of setgenerate on this network");
210 bool fGenerate
= true;
211 if (params
.size() > 0)
212 fGenerate
= params
[0].get_bool();
214 int nGenProcLimit
= GetArg("-genproclimit", DEFAULT_GENERATE_THREADS
);
215 if (params
.size() > 1)
217 nGenProcLimit
= params
[1].get_int();
218 if (nGenProcLimit
== 0)
222 mapArgs
["-gen"] = (fGenerate
? "1" : "0");
223 mapArgs
["-genproclimit"] = itostr(nGenProcLimit
);
224 GenerateBitcoins(fGenerate
, nGenProcLimit
, Params());
229 UniValue
getmininginfo(const UniValue
& params
, bool fHelp
)
231 if (fHelp
|| params
.size() != 0)
234 "\nReturns a json object containing mining-related information."
237 " \"blocks\": nnn, (numeric) The current block\n"
238 " \"currentblocksize\": nnn, (numeric) The last block size\n"
239 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
240 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
241 " \"errors\": \"...\" (string) Current errors\n"
242 " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
243 " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
244 " \"pooledtx\": n (numeric) The size of the mem pool\n"
245 " \"testnet\": true|false (boolean) If using testnet or not\n"
246 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
249 + HelpExampleCli("getmininginfo", "")
250 + HelpExampleRpc("getmininginfo", "")
256 UniValue
obj(UniValue::VOBJ
);
257 obj
.push_back(Pair("blocks", (int)chainActive
.Height()));
258 obj
.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize
));
259 obj
.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx
));
260 obj
.push_back(Pair("difficulty", (double)GetDifficulty()));
261 obj
.push_back(Pair("errors", GetWarnings("statusbar")));
262 obj
.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", DEFAULT_GENERATE_THREADS
)));
263 obj
.push_back(Pair("networkhashps", getnetworkhashps(params
, false)));
264 obj
.push_back(Pair("pooledtx", (uint64_t)mempool
.size()));
265 obj
.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
266 obj
.push_back(Pair("chain", Params().NetworkIDString()));
267 obj
.push_back(Pair("generate", getgenerate(params
, false)));
272 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
273 UniValue
prioritisetransaction(const UniValue
& params
, bool fHelp
)
275 if (fHelp
|| params
.size() != 3)
277 "prioritisetransaction <txid> <priority delta> <fee delta>\n"
278 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
280 "1. \"txid\" (string, required) The transaction id.\n"
281 "2. priority delta (numeric, required) The priority to add or subtract.\n"
282 " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
283 " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
284 "3. fee delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
285 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
286 " considers the transaction as it would have paid a higher (or lower) fee.\n"
288 "true (boolean) Returns true\n"
290 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
291 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
296 uint256 hash
= ParseHashStr(params
[0].get_str(), "txid");
297 CAmount nAmount
= params
[2].get_int64();
299 mempool
.PrioritiseTransaction(hash
, params
[0].get_str(), params
[1].get_real(), nAmount
);
304 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
305 static UniValue
BIP22ValidationResult(const CValidationState
& state
)
310 std::string strRejectReason
= state
.GetRejectReason();
312 throw JSONRPCError(RPC_VERIFY_ERROR
, strRejectReason
);
313 if (state
.IsInvalid())
315 if (strRejectReason
.empty())
317 return strRejectReason
;
319 // Should be impossible
323 UniValue
getblocktemplate(const UniValue
& params
, bool fHelp
)
325 if (fHelp
|| params
.size() > 1)
327 "getblocktemplate ( \"jsonrequestobject\" )\n"
328 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
329 "It returns data needed to construct a block to work on.\n"
330 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
333 "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
335 " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
336 " \"capabilities\":[ (array, optional) A list of strings\n"
337 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
345 " \"version\" : n, (numeric) The block version\n"
346 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
347 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
349 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
350 " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
351 " \"depends\" : [ (array) array of numbers \n"
352 " 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"
355 " \"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"
356 " \"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"
357 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
361 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
362 " \"flags\" : \"flags\" (string) \n"
364 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
365 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
366 " \"target\" : \"xxxx\", (string) The hash target\n"
367 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
368 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
369 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
372 " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
373 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
374 " \"sizelimit\" : n, (numeric) limit of block size\n"
375 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
376 " \"bits\" : \"xxx\", (string) compressed target of next block\n"
377 " \"height\" : n (numeric) The height of the next block\n"
381 + HelpExampleCli("getblocktemplate", "")
382 + HelpExampleRpc("getblocktemplate", "")
387 std::string strMode
= "template";
388 UniValue lpval
= NullUniValue
;
389 if (params
.size() > 0)
391 const UniValue
& oparam
= params
[0].get_obj();
392 const UniValue
& modeval
= find_value(oparam
, "mode");
394 strMode
= modeval
.get_str();
395 else if (modeval
.isNull())
400 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid mode");
401 lpval
= find_value(oparam
, "longpollid");
403 if (strMode
== "proposal")
405 const UniValue
& dataval
= find_value(oparam
, "data");
406 if (!dataval
.isStr())
407 throw JSONRPCError(RPC_TYPE_ERROR
, "Missing data String key for proposal");
410 if (!DecodeHexBlk(block
, dataval
.get_str()))
411 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "Block decode failed");
413 uint256 hash
= block
.GetHash();
414 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
415 if (mi
!= mapBlockIndex
.end()) {
416 CBlockIndex
*pindex
= mi
->second
;
417 if (pindex
->IsValid(BLOCK_VALID_SCRIPTS
))
419 if (pindex
->nStatus
& BLOCK_FAILED_MASK
)
420 return "duplicate-invalid";
421 return "duplicate-inconclusive";
424 CBlockIndex
* const pindexPrev
= chainActive
.Tip();
425 // TestBlockValidity only supports blocks built on the current Tip
426 if (block
.hashPrevBlock
!= pindexPrev
->GetBlockHash())
427 return "inconclusive-not-best-prevblk";
428 CValidationState state
;
429 TestBlockValidity(state
, Params(), block
, pindexPrev
, false, true);
430 return BIP22ValidationResult(state
);
434 if (strMode
!= "template")
435 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid mode");
438 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED
, "Bitcoin is not connected!");
440 if (IsInitialBlockDownload())
441 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD
, "Bitcoin is downloading blocks...");
443 static unsigned int nTransactionsUpdatedLast
;
447 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
448 uint256 hashWatchedChain
;
449 boost::system_time checktxtime
;
450 unsigned int nTransactionsUpdatedLastLP
;
454 // Format: <hashBestChain><nTransactionsUpdatedLast>
455 std::string lpstr
= lpval
.get_str();
457 hashWatchedChain
.SetHex(lpstr
.substr(0, 64));
458 nTransactionsUpdatedLastLP
= atoi64(lpstr
.substr(64));
462 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
463 hashWatchedChain
= chainActive
.Tip()->GetBlockHash();
464 nTransactionsUpdatedLastLP
= nTransactionsUpdatedLast
;
467 // Release the wallet and main lock while waiting
468 LEAVE_CRITICAL_SECTION(cs_main
);
470 checktxtime
= boost::get_system_time() + boost::posix_time::minutes(1);
472 boost::unique_lock
<boost::mutex
> lock(csBestBlock
);
473 while (chainActive
.Tip()->GetBlockHash() == hashWatchedChain
&& IsRPCRunning())
475 if (!cvBlockChange
.timed_wait(lock
, checktxtime
))
477 // Timeout: Check transactions for update
478 if (mempool
.GetTransactionsUpdated() != nTransactionsUpdatedLastLP
)
480 checktxtime
+= boost::posix_time::seconds(10);
484 ENTER_CRITICAL_SECTION(cs_main
);
487 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED
, "Shutting down");
488 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
492 static CBlockIndex
* pindexPrev
;
493 static int64_t nStart
;
494 static CBlockTemplate
* pblocktemplate
;
495 if (pindexPrev
!= chainActive
.Tip() ||
496 (mempool
.GetTransactionsUpdated() != nTransactionsUpdatedLast
&& GetTime() - nStart
> 5))
498 // Clear pindexPrev so future calls make a new block, despite any failures from here on
501 // Store the pindexBest used before CreateNewBlock, to avoid races
502 nTransactionsUpdatedLast
= mempool
.GetTransactionsUpdated();
503 CBlockIndex
* pindexPrevNew
= chainActive
.Tip();
509 delete pblocktemplate
;
510 pblocktemplate
= NULL
;
512 CScript scriptDummy
= CScript() << OP_TRUE
;
513 pblocktemplate
= CreateNewBlock(Params(), scriptDummy
);
515 throw JSONRPCError(RPC_OUT_OF_MEMORY
, "Out of memory");
517 // Need to update only after we know CreateNewBlock succeeded
518 pindexPrev
= pindexPrevNew
;
520 CBlock
* pblock
= &pblocktemplate
->block
; // pointer for convenience
523 UpdateTime(pblock
, Params().GetConsensus(), pindexPrev
);
526 UniValue
aCaps(UniValue::VARR
); aCaps
.push_back("proposal");
528 UniValue
transactions(UniValue::VARR
);
529 map
<uint256
, int64_t> setTxIndex
;
531 BOOST_FOREACH (const CTransaction
& tx
, pblock
->vtx
) {
532 uint256 txHash
= tx
.GetHash();
533 setTxIndex
[txHash
] = i
++;
538 UniValue
entry(UniValue::VOBJ
);
540 entry
.push_back(Pair("data", EncodeHexTx(tx
)));
542 entry
.push_back(Pair("hash", txHash
.GetHex()));
544 UniValue
deps(UniValue::VARR
);
545 BOOST_FOREACH (const CTxIn
&in
, tx
.vin
)
547 if (setTxIndex
.count(in
.prevout
.hash
))
548 deps
.push_back(setTxIndex
[in
.prevout
.hash
]);
550 entry
.push_back(Pair("depends", deps
));
552 int index_in_template
= i
- 1;
553 entry
.push_back(Pair("fee", pblocktemplate
->vTxFees
[index_in_template
]));
554 entry
.push_back(Pair("sigops", pblocktemplate
->vTxSigOps
[index_in_template
]));
556 transactions
.push_back(entry
);
559 UniValue
aux(UniValue::VOBJ
);
560 aux
.push_back(Pair("flags", HexStr(COINBASE_FLAGS
.begin(), COINBASE_FLAGS
.end())));
562 arith_uint256 hashTarget
= arith_uint256().SetCompact(pblock
->nBits
);
564 static UniValue
aMutable(UniValue::VARR
);
565 if (aMutable
.empty())
567 aMutable
.push_back("time");
568 aMutable
.push_back("transactions");
569 aMutable
.push_back("prevblock");
572 UniValue
result(UniValue::VOBJ
);
573 result
.push_back(Pair("capabilities", aCaps
));
574 result
.push_back(Pair("version", pblock
->nVersion
));
575 result
.push_back(Pair("previousblockhash", pblock
->hashPrevBlock
.GetHex()));
576 result
.push_back(Pair("transactions", transactions
));
577 result
.push_back(Pair("coinbaseaux", aux
));
578 result
.push_back(Pair("coinbasevalue", (int64_t)pblock
->vtx
[0].vout
[0].nValue
));
579 result
.push_back(Pair("longpollid", chainActive
.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast
)));
580 result
.push_back(Pair("target", hashTarget
.GetHex()));
581 result
.push_back(Pair("mintime", (int64_t)pindexPrev
->GetMedianTimePast()+1));
582 result
.push_back(Pair("mutable", aMutable
));
583 result
.push_back(Pair("noncerange", "00000000ffffffff"));
584 result
.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS
));
585 result
.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE
));
586 result
.push_back(Pair("curtime", pblock
->GetBlockTime()));
587 result
.push_back(Pair("bits", strprintf("%08x", pblock
->nBits
)));
588 result
.push_back(Pair("height", (int64_t)(pindexPrev
->nHeight
+1)));
593 class submitblock_StateCatcher
: public CValidationInterface
598 CValidationState state
;
600 submitblock_StateCatcher(const uint256
&hashIn
) : hash(hashIn
), found(false), state() {};
603 virtual void BlockChecked(const CBlock
& block
, const CValidationState
& stateIn
) {
604 if (block
.GetHash() != hash
)
611 UniValue
submitblock(const UniValue
& params
, bool fHelp
)
613 if (fHelp
|| params
.size() < 1 || params
.size() > 2)
615 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
616 "\nAttempts to submit new block to network.\n"
617 "The 'jsonparametersobject' parameter is currently ignored.\n"
618 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
621 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
622 "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
624 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
628 + HelpExampleCli("submitblock", "\"mydata\"")
629 + HelpExampleRpc("submitblock", "\"mydata\"")
633 if (!DecodeHexBlk(block
, params
[0].get_str()))
634 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "Block decode failed");
636 uint256 hash
= block
.GetHash();
637 bool fBlockPresent
= false;
640 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
641 if (mi
!= mapBlockIndex
.end()) {
642 CBlockIndex
*pindex
= mi
->second
;
643 if (pindex
->IsValid(BLOCK_VALID_SCRIPTS
))
645 if (pindex
->nStatus
& BLOCK_FAILED_MASK
)
646 return "duplicate-invalid";
647 // Otherwise, we might only have the header - process the block before returning
648 fBlockPresent
= true;
652 CValidationState state
;
653 submitblock_StateCatcher
sc(block
.GetHash());
654 RegisterValidationInterface(&sc
);
655 bool fAccepted
= ProcessNewBlock(state
, Params(), NULL
, &block
, true, NULL
);
656 UnregisterValidationInterface(&sc
);
659 if (fAccepted
&& !sc
.found
)
660 return "duplicate-inconclusive";
666 return "inconclusive";
669 return BIP22ValidationResult(state
);
672 UniValue
estimatefee(const UniValue
& params
, bool fHelp
)
674 if (fHelp
|| params
.size() != 1)
676 "estimatefee nblocks\n"
677 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
678 "confirmation within nblocks blocks.\n"
680 "1. nblocks (numeric)\n"
682 "n (numeric) estimated fee-per-kilobyte\n"
684 "A negative value is returned if not enough transactions and blocks\n"
685 "have been observed to make an estimate.\n"
687 + HelpExampleCli("estimatefee", "6")
690 RPCTypeCheck(params
, boost::assign::list_of(UniValue::VNUM
));
692 int nBlocks
= params
[0].get_int();
696 CFeeRate feeRate
= mempool
.estimateFee(nBlocks
);
697 if (feeRate
== CFeeRate(0))
700 return ValueFromAmount(feeRate
.GetFeePerK());
703 UniValue
estimatepriority(const UniValue
& params
, bool fHelp
)
705 if (fHelp
|| params
.size() != 1)
707 "estimatepriority nblocks\n"
708 "\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
709 "confirmation within nblocks blocks.\n"
711 "1. nblocks (numeric)\n"
713 "n (numeric) estimated priority\n"
715 "A negative value is returned if not enough transactions and blocks\n"
716 "have been observed to make an estimate.\n"
718 + HelpExampleCli("estimatepriority", "6")
721 RPCTypeCheck(params
, boost::assign::list_of(UniValue::VNUM
));
723 int nBlocks
= params
[0].get_int();
727 return mempool
.estimatePriority(nBlocks
);
730 UniValue
estimatesmartfee(const UniValue
& params
, bool fHelp
)
732 if (fHelp
|| params
.size() != 1)
734 "estimatesmartfee nblocks\n"
735 "\nWARNING: This interface is unstable and may disappear or change!\n"
736 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
737 "confirmation within nblocks blocks if possible and return the number of blocks\n"
738 "for which the estimate is valid.\n"
740 "1. nblocks (numeric)\n"
743 " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
744 " \"blocks\" : n (numeric) block number where estimate was found\n"
747 "A negative value is returned if not enough transactions and blocks\n"
748 "have been observed to make an estimate for any number of blocks.\n"
749 "However it will not return a value below the mempool reject fee.\n"
751 + HelpExampleCli("estimatesmartfee", "6")
754 RPCTypeCheck(params
, boost::assign::list_of(UniValue::VNUM
));
756 int nBlocks
= params
[0].get_int();
758 UniValue
result(UniValue::VOBJ
);
760 CFeeRate feeRate
= mempool
.estimateSmartFee(nBlocks
, &answerFound
);
761 result
.push_back(Pair("feerate", feeRate
== CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate
.GetFeePerK())));
762 result
.push_back(Pair("blocks", answerFound
));
766 UniValue
estimatesmartpriority(const UniValue
& params
, bool fHelp
)
768 if (fHelp
|| params
.size() != 1)
770 "estimatesmartpriority nblocks\n"
771 "\nWARNING: This interface is unstable and may disappear or change!\n"
772 "\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
773 "confirmation within nblocks blocks if possible and return the number of blocks\n"
774 "for which the estimate is valid.\n"
776 "1. nblocks (numeric)\n"
779 " \"priority\" : x.x, (numeric) estimated priority\n"
780 " \"blocks\" : n (numeric) block number where estimate was found\n"
783 "A negative value is returned if not enough transactions and blocks\n"
784 "have been observed to make an estimate for any number of blocks.\n"
785 "However if the mempool reject fee is set it will return 1e9 * MAX_MONEY.\n"
787 + HelpExampleCli("estimatesmartpriority", "6")
790 RPCTypeCheck(params
, boost::assign::list_of(UniValue::VNUM
));
792 int nBlocks
= params
[0].get_int();
794 UniValue
result(UniValue::VOBJ
);
796 double priority
= mempool
.estimateSmartPriority(nBlocks
, &answerFound
);
797 result
.push_back(Pair("priority", priority
));
798 result
.push_back(Pair("blocks", answerFound
));