Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2020 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <base58.h>
8 #include <amount.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <consensus/consensus.h>
12 #include <consensus/params.h>
13 #include <consensus/validation.h>
14 #include <core_io.h>
15 #include <init.h>
16 #include <validation.h>
17 #include <miner.h>
18 #include <net.h>
19 #include <policy/fees.h>
20 #include <pow.h>
21 #include <rpc/blockchain.h>
22 #include <rpc/mining.h>
23 #include <rpc/server.h>
24 #include <spork.h>
25 #include <txmempool.h>
26 #include <util.h>
27 #include <utilstrencodings.h>
28 #include <validationinterface.h>
29 #include <warnings.h>
30 
34 
35 #include <evo/deterministicmns.h>
36 #include <evo/specialtx.h>
37 #include <evo/cbtx.h>
38 
39 #include <memory>
40 #include <stdint.h>
41 
42 unsigned int ParseConfirmTarget(const UniValue& value)
43 {
44  int target = value.get_int();
46  if (target < 1 || (unsigned int)target > max_target) {
47  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u - %u", 1, max_target));
48  }
49  return (unsigned int)target;
50 }
51 
57 UniValue GetNetworkHashPS(int lookup, int height) {
58  CBlockIndex *pb = chainActive.Tip();
59 
60  if (height >= 0 && height < chainActive.Height())
61  pb = chainActive[height];
62 
63  if (pb == nullptr || !pb->nHeight)
64  return 0;
65 
66  // If lookup is -1, then use blocks since last difficulty change.
67  if (lookup <= 0)
69 
70  // If lookup is larger than chain, then set it to chain length.
71  if (lookup > pb->nHeight)
72  lookup = pb->nHeight;
73 
74  CBlockIndex *pb0 = pb;
75  int64_t minTime = pb0->GetBlockTime();
76  int64_t maxTime = minTime;
77  for (int i = 0; i < lookup; i++) {
78  pb0 = pb0->pprev;
79  int64_t time = pb0->GetBlockTime();
80  minTime = std::min(time, minTime);
81  maxTime = std::max(time, maxTime);
82  }
83 
84  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
85  if (minTime == maxTime)
86  return 0;
87 
88  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
89  int64_t timeDiff = maxTime - minTime;
90 
91  return workDiff.getdouble() / timeDiff;
92 }
93 
95 {
96  if (request.fHelp || request.params.size() > 2)
97  throw std::runtime_error(
98  "getnetworkhashps ( nblocks height )\n"
99  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
100  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
101  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
102  "\nArguments:\n"
103  "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
104  "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
105  "\nResult:\n"
106  "x (numeric) Hashes per second estimated\n"
107  "\nExamples:\n"
108  + HelpExampleCli("getnetworkhashps", "")
109  + HelpExampleRpc("getnetworkhashps", "")
110  );
111 
112  LOCK(cs_main);
113  return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1);
114 }
115 
116 #if ENABLE_MINER
117 UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
118 {
119  static const int nInnerLoopCount = 0x10000;
120  int nHeightEnd = 0;
121  int nHeight = 0;
122 
123  { // Don't keep cs_main locked
124  LOCK(cs_main);
125  nHeight = chainActive.Height();
126  nHeightEnd = nHeight+nGenerate;
127  }
128  unsigned int nExtraNonce = 0;
129  UniValue blockHashes(UniValue::VARR);
130  while (nHeight < nHeightEnd)
131  {
132  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
133  if (!pblocktemplate.get())
134  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
135  CBlock *pblock = &pblocktemplate->block;
136  {
137  LOCK(cs_main);
138  IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
139  }
140  while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
141  ++pblock->nNonce;
142  --nMaxTries;
143  }
144  if (nMaxTries == 0) {
145  break;
146  }
147  if (pblock->nNonce == nInnerLoopCount) {
148  continue;
149  }
150  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
151  if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr))
152  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
153  ++nHeight;
154  blockHashes.push_back(pblock->GetHash().GetHex());
155 
156  //mark script as important because it was used at least for one coinbase output if the script came from the wallet
157  if (keepScript)
158  {
159  coinbaseScript->KeepScript();
160  }
161  }
162  return blockHashes;
163 }
164 
165 UniValue generatetoaddress(const JSONRPCRequest& request)
166 {
167  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
168  throw std::runtime_error(
169  "generatetoaddress nblocks address (maxtries)\n"
170  "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
171  "\nArguments:\n"
172  "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
173  "2. address (string, required) The address to send the newly generated Dash to.\n"
174  "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
175  "\nResult:\n"
176  "[ blockhashes ] (array) hashes of blocks generated\n"
177  "\nExamples:\n"
178  "\nGenerate 11 blocks to myaddress\n"
179  + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
180  );
181 
182  int nGenerate = request.params[0].get_int();
183  uint64_t nMaxTries = 1000000;
184  if (!request.params[2].isNull()) {
185  nMaxTries = request.params[2].get_int();
186  }
187 
188  CTxDestination destination = DecodeDestination(request.params[1].get_str());
189  if (!IsValidDestination(destination)) {
190  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
191  }
192 
193  std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
194  coinbaseScript->reserveScript = GetScriptForDestination(destination);
195 
196  return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
197 }
198 #endif // ENABLE_MINER
199 
201 {
202  if (request.fHelp || request.params.size() != 0)
203  throw std::runtime_error(
204  "getmininginfo\n"
205  "\nReturns a json object containing mining-related information."
206  "\nResult:\n"
207  "{\n"
208  " \"blocks\": nnn, (numeric) The current block\n"
209  " \"currentblocksize\": nnn, (numeric) The last block size\n"
210  " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
211  " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
212  " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
213  " \"pooledtx\": n (numeric) The size of the mempool\n"
214  " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
215  " \"warnings\": \"...\" (string) any network and blockchain warnings\n"
216  " \"errors\": \"...\" (string) DEPRECATED. Same as warnings. Only shown when dashd is started with -deprecatedrpc=getmininginfo\n"
217  "}\n"
218  "\nExamples:\n"
219  + HelpExampleCli("getmininginfo", "")
220  + HelpExampleRpc("getmininginfo", "")
221  );
222 
223 
224  LOCK(cs_main);
225 
227  obj.push_back(Pair("blocks", (int)chainActive.Height()));
228  obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
229  obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
230  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
231  obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
232  obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
233  obj.push_back(Pair("chain", Params().NetworkIDString()));
234  if (IsDeprecatedRPCEnabled("getmininginfo")) {
235  obj.push_back(Pair("errors", GetWarnings("statusbar")));
236  } else {
237  obj.push_back(Pair("warnings", GetWarnings("statusbar")));
238  }
239  return obj;
240 }
241 
242 
243 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
245 {
246  if (request.fHelp || request.params.size() != 2)
247  throw std::runtime_error(
248  "prioritisetransaction <txid> <fee delta>\n"
249  "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
250  "\nArguments:\n"
251  "1. \"txid\" (string, required) The transaction id.\n"
252  "2. fee_delta (numeric, required) The fee value (in duffs) to add (or subtract, if negative).\n"
253  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
254  " considers the transaction as it would have paid a higher (or lower) fee.\n"
255  "\nResult:\n"
256  "true (boolean) Returns true\n"
257  "\nExamples:\n"
258  + HelpExampleCli("prioritisetransaction", "\"txid\" 10000")
259  + HelpExampleRpc("prioritisetransaction", "\"txid\", 10000")
260  );
261 
262  LOCK(cs_main);
263 
264  uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
265  CAmount nAmount = request.params[1].get_int64();
266 
267  mempool.PrioritiseTransaction(hash, nAmount);
268  return true;
269 }
270 
271 
272 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
274 {
275  if (state.IsValid())
276  return NullUniValue;
277 
278  std::string strRejectReason = state.GetRejectReason();
279  if (state.IsError())
280  throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
281  if (state.IsInvalid())
282  {
283  if (strRejectReason.empty())
284  return "rejected";
285  return strRejectReason;
286  }
287  // Should be impossible
288  return "valid?";
289 }
290 
291 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
292  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
293  std::string s = vbinfo.name;
294  if (!vbinfo.gbt_force) {
295  s.insert(s.begin(), '!');
296  }
297  return s;
298 }
299 
301 {
302  if (request.fHelp || request.params.size() > 1)
303  throw std::runtime_error(
304  "getblocktemplate ( TemplateRequest )\n"
305  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
306  "It returns data needed to construct a block to work on.\n"
307  "For full specification, see BIPs 22, 23, and 9:\n"
308  " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
309  " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
310  " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
311 
312  "\nArguments:\n"
313  "1. template_request (json object, optional) A json object in the following spec\n"
314  " {\n"
315  " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
316  " \"capabilities\":[ (array, optional) A list of strings\n"
317  " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
318  " ,...\n"
319  " ],\n"
320  " \"rules\":[ (array, optional) A list of strings\n"
321  " \"support\" (string) client side supported softfork deployment\n"
322  " ,...\n"
323  " ]\n"
324  " }\n"
325  "\n"
326 
327  "\nResult:\n"
328  "{\n"
329  " \"capabilities\" : [ \"capability\", ... ], (array of strings) specific client side supported features\n"
330  " \"version\" : n, (numeric) The preferred block version\n"
331  " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
332  " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
333  " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
334  " ,...\n"
335  " },\n"
336  " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
337  " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
338  " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
339  " {\n"
340  " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
341  " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
342  " \"depends\" : [ (array) array of numbers \n"
343  " 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"
344  " ,...\n"
345  " ],\n"
346  " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in duffs); 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"
347  " \"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"
348  " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
349  " }\n"
350  " ,...\n"
351  " ],\n"
352  " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
353  " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
354  " },\n"
355  " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in duffs)\n"
356  " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
357  " \"target\" : \"xxxx\", (string) The hash target\n"
358  " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
359  " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
360  " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
361  " ,...\n"
362  " ],\n"
363  " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
364  " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
365  " \"sizelimit\" : n, (numeric) limit of block size\n"
366  " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
367  " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
368  " \"previousbits\" : \"xxxxxxxx\", (string) compressed target of current highest block\n"
369  " \"height\" : n (numeric) The height of the next block\n"
370  " \"masternode\" : [ (array) required masternode payments that must be included in the next block\n"
371  " {\n"
372  " \"payee\" : \"xxxx\", (string) payee address\n"
373  " \"script\" : \"xxxx\", (string) payee scriptPubKey\n"
374  " \"amount\": n (numeric) required amount to pay\n"
375  " }\n"
376  " },\n"
377  " \"masternode_payments_started\" : true|false, (boolean) true, if masternode payments started\n"
378  " \"masternode_payments_enforced\" : true|false, (boolean) true, if masternode payments are enforced\n"
379  " \"superblock\" : [ (array) required superblock payees that must be included in the next block\n"
380  " {\n"
381  " \"payee\" : \"xxxx\", (string) payee address\n"
382  " \"script\" : \"xxxx\", (string) payee scriptPubKey\n"
383  " \"amount\": n (numeric) required amount to pay\n"
384  " }\n"
385  " ,...\n"
386  " ],\n"
387  " \"superblocks_started\" : true|false, (boolean) true, if superblock payments started\n"
388  " \"superblocks_enabled\" : true|false, (boolean) true, if superblock payments are enabled\n"
389  " \"coinbase_payload\" : \"xxxxxxxx\" (string) coinbase transaction payload data encoded in hexadecimal\n"
390  "}\n"
391 
392  "\nExamples:\n"
393  + HelpExampleCli("getblocktemplate", "")
394  + HelpExampleRpc("getblocktemplate", "")
395  );
396 
397  LOCK(cs_main);
398 
399  std::string strMode = "template";
400  UniValue lpval = NullUniValue;
401  std::set<std::string> setClientRules;
402  int64_t nMaxVersionPreVB = -1;
403  if (!request.params[0].isNull())
404  {
405  const UniValue& oparam = request.params[0].get_obj();
406  const UniValue& modeval = find_value(oparam, "mode");
407  if (modeval.isStr())
408  strMode = modeval.get_str();
409  else if (modeval.isNull())
410  {
411  /* Do nothing */
412  }
413  else
414  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
415  lpval = find_value(oparam, "longpollid");
416 
417  if (strMode == "proposal")
418  {
419  const UniValue& dataval = find_value(oparam, "data");
420  if (!dataval.isStr())
421  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
422 
423  CBlock block;
424  if (!DecodeHexBlk(block, dataval.get_str()))
425  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
426 
427  uint256 hash = block.GetHash();
428  BlockMap::iterator mi = mapBlockIndex.find(hash);
429  if (mi != mapBlockIndex.end()) {
430  CBlockIndex *pindex = mi->second;
431  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
432  return "duplicate";
433  if (pindex->nStatus & BLOCK_FAILED_MASK)
434  return "duplicate-invalid";
435  return "duplicate-inconclusive";
436  }
437 
438  CBlockIndex* const pindexPrev = chainActive.Tip();
439  // TestBlockValidity only supports blocks built on the current Tip
440  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
441  return "inconclusive-not-best-prevblk";
442  CValidationState state;
443  TestBlockValidity(state, Params(), block, pindexPrev, false, true);
444  return BIP22ValidationResult(state);
445  }
446 
447  const UniValue& aClientRules = find_value(oparam, "rules");
448  if (aClientRules.isArray()) {
449  for (unsigned int i = 0; i < aClientRules.size(); ++i) {
450  const UniValue& v = aClientRules[i];
451  setClientRules.insert(v.get_str());
452  }
453  } else {
454  // NOTE: It is important that this NOT be read if versionbits is supported
455  const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
456  if (uvMaxVersion.isNum()) {
457  nMaxVersionPreVB = uvMaxVersion.get_int64();
458  }
459  }
460  }
461 
462  if (strMode != "template")
463  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
464 
465  if(!g_connman)
466  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
467 
468  if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
469  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Dash Core is not connected!");
470 
472  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Dash Core is downloading blocks...");
473 
474  // Get expected MN/superblock payees. The call to GetBlockTxOuts might fail on regtest/devnet or when
475  // testnet is reset. This is fine and we ignore failure (blocks will be accepted)
476  std::vector<CTxOut> voutMasternodePayments;
477  mnpayments.GetBlockTxOuts(chainActive.Height() + 1, 0, voutMasternodePayments);
478 
479  // next bock is a superblock and we need governance info to correctly construct it
483  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Dash Core is syncing with network...");
484 
485  static unsigned int nTransactionsUpdatedLast;
486 
487  if (!lpval.isNull())
488  {
489  // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
490  uint256 hashWatchedChain;
492  unsigned int nTransactionsUpdatedLastLP;
493 
494  if (lpval.isStr())
495  {
496  // Format: <hashBestChain><nTransactionsUpdatedLast>
497  std::string lpstr = lpval.get_str();
498 
499  hashWatchedChain.SetHex(lpstr.substr(0, 64));
500  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
501  }
502  else
503  {
504  // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
505  hashWatchedChain = chainActive.Tip()->GetBlockHash();
506  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
507  }
508 
509  // Release the wallet and main lock while waiting
511  {
512  checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
513 
515  while (g_best_block == hashWatchedChain && IsRPCRunning())
516  {
517  if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
518  {
519  // Timeout: Check transactions for update
520  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
521  break;
522  checktxtime += std::chrono::seconds(10);
523  }
524  }
525  }
527 
528  if (!IsRPCRunning())
529  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
530  // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
531  }
532 
533  // Update block
534  static CBlockIndex* pindexPrev;
535  static int64_t nStart;
536  static std::unique_ptr<CBlockTemplate> pblocktemplate;
537  if (pindexPrev != chainActive.Tip() ||
538  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
539  {
540  // Clear pindexPrev so future calls make a new block, despite any failures from here on
541  pindexPrev = nullptr;
542 
543  // Store the chainActive.Tip() used before CreateNewBlock, to avoid races
544  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
545  CBlockIndex* pindexPrevNew = chainActive.Tip();
546  nStart = GetTime();
547 
548  // Create new block
549  CScript scriptDummy = CScript() << OP_TRUE;
550  pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy);
551  if (!pblocktemplate)
552  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
553 
554  // Need to update only after we know CreateNewBlock succeeded
555  pindexPrev = pindexPrevNew;
556  }
557  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
558  const Consensus::Params& consensusParams = Params().GetConsensus();
559 
560  // Update nTime
561  UpdateTime(pblock, consensusParams, pindexPrev);
562  pblock->nNonce = 0;
563 
564  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
565 
566  UniValue transactions(UniValue::VARR);
567  std::map<uint256, int64_t> setTxIndex;
568  int i = 0;
569  for (const auto& it : pblock->vtx) {
570  const CTransaction& tx = *it;
571  uint256 txHash = tx.GetHash();
572  setTxIndex[txHash] = i++;
573 
574  if (tx.IsCoinBase())
575  continue;
576 
577  UniValue entry(UniValue::VOBJ);
578 
579  entry.push_back(Pair("data", EncodeHexTx(tx)));
580 
581  entry.push_back(Pair("hash", txHash.GetHex()));
582 
583  UniValue deps(UniValue::VARR);
584  for (const CTxIn &in : tx.vin)
585  {
586  if (setTxIndex.count(in.prevout.hash))
587  deps.push_back(setTxIndex[in.prevout.hash]);
588  }
589  entry.push_back(Pair("depends", deps));
590 
591  int index_in_template = i - 1;
592  entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
593  entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
594 
595  transactions.push_back(entry);
596  }
597 
600 
601  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
602 
603  UniValue aMutable(UniValue::VARR);
604  aMutable.push_back("time");
605  aMutable.push_back("transactions");
606  aMutable.push_back("prevblock");
607 
608  UniValue result(UniValue::VOBJ);
609  result.push_back(Pair("capabilities", aCaps));
610 
611  UniValue aRules(UniValue::VARR);
612  UniValue vbavailable(UniValue::VOBJ);
613  for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
615  ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
616  switch (state) {
617  case THRESHOLD_DEFINED:
618  case THRESHOLD_FAILED:
619  // Not exposed to GBT at all
620  break;
621  case THRESHOLD_LOCKED_IN:
622  // Ensure bit is set in block version
623  pblock->nVersion |= VersionBitsMask(consensusParams, pos);
624  // FALL THROUGH to get vbavailable set...
625  case THRESHOLD_STARTED:
626  {
627  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
628  vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
629  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
630  if (!vbinfo.gbt_force) {
631  // If the client doesn't support this, don't indicate it in the [default] version
632  pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
633  }
634  }
635  break;
636  }
637  case THRESHOLD_ACTIVE:
638  {
639  // Add to rules only
640  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
641  aRules.push_back(gbt_vb_name(pos));
642  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
643  // Not supported by the client; make sure it's safe to proceed
644  if (!vbinfo.gbt_force) {
645  // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
646  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
647  }
648  }
649  break;
650  }
651  }
652  }
653  result.push_back(Pair("version", pblock->nVersion));
654  result.push_back(Pair("rules", aRules));
655  result.push_back(Pair("vbavailable", vbavailable));
656  result.push_back(Pair("vbrequired", int(0)));
657 
658  if (nMaxVersionPreVB >= 2) {
659  // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
660  // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
661  // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
662  // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
663  aMutable.push_back("version/force");
664  }
665 
666  result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
667  result.push_back(Pair("transactions", transactions));
668  result.push_back(Pair("coinbaseaux", aux));
669  result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->GetValueOut()));
670  result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
671  result.push_back(Pair("target", hashTarget.GetHex()));
672  result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
673  result.push_back(Pair("mutable", aMutable));
674  result.push_back(Pair("noncerange", "00000000ffffffff"));
675  result.push_back(Pair("sigoplimit", (int64_t)MaxBlockSigOps(fDIP0001ActiveAtTip)));
676  result.push_back(Pair("sizelimit", (int64_t)MaxBlockSize(fDIP0001ActiveAtTip)));
677  result.push_back(Pair("curtime", pblock->GetBlockTime()));
678  result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
679  result.push_back(Pair("previousbits", strprintf("%08x", pblocktemplate->nPrevBits)));
680  result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
681 
682  UniValue masternodeObj(UniValue::VARR);
683  for (const auto& txout : pblocktemplate->voutMasternodePayments) {
684  CTxDestination dest;
685  ExtractDestination(txout.scriptPubKey, dest);
686 
688  obj.push_back(Pair("payee", EncodeDestination(dest).c_str()));
689  obj.push_back(Pair("script", HexStr(txout.scriptPubKey)));
690  obj.push_back(Pair("amount", txout.nValue));
691  masternodeObj.push_back(obj);
692  }
693 
694  result.push_back(Pair("masternode", masternodeObj));
695  result.push_back(Pair("masternode_payments_started", pindexPrev->nHeight + 1 > consensusParams.nMasternodePaymentsStartBlock));
696  result.push_back(Pair("masternode_payments_enforced", true));
697 
698  UniValue superblockObjArray(UniValue::VARR);
699  if(pblocktemplate->voutSuperblockPayments.size()) {
700  for (const auto& txout : pblocktemplate->voutSuperblockPayments) {
701  UniValue entry(UniValue::VOBJ);
702  CTxDestination dest;
703  ExtractDestination(txout.scriptPubKey, dest);
704  entry.push_back(Pair("payee", EncodeDestination(dest).c_str()));
705  entry.push_back(Pair("script", HexStr(txout.scriptPubKey)));
706  entry.push_back(Pair("amount", txout.nValue));
707  superblockObjArray.push_back(entry);
708  }
709  }
710  result.push_back(Pair("superblock", superblockObjArray));
711  result.push_back(Pair("superblocks_started", pindexPrev->nHeight + 1 > consensusParams.nSuperblockStartBlock));
712  result.push_back(Pair("superblocks_enabled", sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)));
713 
714  result.push_back(Pair("coinbase_payload", HexStr(pblock->vtx[0]->vExtraPayload)));
715 
716  return result;
717 }
718 
720 {
721 public:
723  bool found;
725 
726  explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
727 
728 protected:
729  void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
730  if (block.GetHash() != hash)
731  return;
732  found = true;
733  state = stateIn;
734  }
735 };
736 
738 {
739  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
740  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
741  throw std::runtime_error(
742  "submitblock \"hexdata\" ( \"dummy\" )\n"
743  "\nAttempts to submit new block to network.\n"
744  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
745 
746  "\nArguments:\n"
747  "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
748  "2. \"dummy\" (optional) dummy value, for compatibility with BIP22. This value is ignored.\n"
749  "\nResult:\n"
750  "\nExamples:\n"
751  + HelpExampleCli("submitblock", "\"mydata\"")
752  + HelpExampleRpc("submitblock", "\"mydata\"")
753  );
754  }
755 
756  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
757  CBlock& block = *blockptr;
758  if (!DecodeHexBlk(block, request.params[0].get_str())) {
759  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
760  }
761 
762  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
763  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
764  }
765 
766  uint256 hash = block.GetHash();
767  bool fBlockPresent = false;
768  {
769  LOCK(cs_main);
770  BlockMap::iterator mi = mapBlockIndex.find(hash);
771  if (mi != mapBlockIndex.end()) {
772  CBlockIndex *pindex = mi->second;
773  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
774  return "duplicate";
775  }
776  if (pindex->nStatus & BLOCK_FAILED_MASK) {
777  return "duplicate-invalid";
778  }
779  // Otherwise, we might only have the header - process the block before returning
780  fBlockPresent = true;
781  }
782  }
783 
784  submitblock_StateCatcher sc(block.GetHash());
786  bool fAccepted = ProcessNewBlock(Params(), blockptr, true, nullptr);
788  if (fBlockPresent) {
789  if (fAccepted && !sc.found) {
790  return "duplicate-inconclusive";
791  }
792  return "duplicate";
793  }
794  if (!sc.found) {
795  return "inconclusive";
796  }
797  return BIP22ValidationResult(sc.state);
798 }
799 
801 {
802  if (request.fHelp || request.params.size() != 1)
803  throw std::runtime_error(
804  "estimatefee nblocks\n"
805  "\nDEPRECATED. Please use estimatesmartfee for more intelligent estimates."
806  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
807  "confirmation within nblocks blocks.\n"
808  "\nArguments:\n"
809  "1. nblocks (numeric, required)\n"
810  "\nResult:\n"
811  "n (numeric) estimated fee-per-kilobyte\n"
812  "\n"
813  "A negative value is returned if not enough transactions and blocks\n"
814  "have been observed to make an estimate.\n"
815  "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
816  "a fee that is high enough to get reliably included in the next block.\n"
817  "\nExample:\n"
818  + HelpExampleCli("estimatefee", "6")
819  );
820 
821  if (!IsDeprecatedRPCEnabled("estimatefee")) {
822  throw JSONRPCError(RPC_METHOD_DEPRECATED, "estimatefee is deprecated and will be fully removed in v0.17. "
823  "To use estimatefee in v0.16, restart dashd with -deprecatedrpc=estimatefee.\n"
824  "Projects should transition to using estimatesmartfee before upgrading to v0.17");
825  }
826 
827  RPCTypeCheck(request.params, {UniValue::VNUM});
828 
829  int nBlocks = request.params[0].get_int();
830  if (nBlocks < 1)
831  nBlocks = 1;
832 
833  CFeeRate feeRate = ::feeEstimator.estimateFee(nBlocks);
834  if (feeRate == CFeeRate(0))
835  return -1.0;
836 
837  return ValueFromAmount(feeRate.GetFeePerK());
838 }
839 
841 {
842  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
843  throw std::runtime_error(
844  "estimatesmartfee conf_target (\"estimate_mode\")\n"
845  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
846  "confirmation within conf_target blocks if possible and return the number of blocks\n"
847  "for which the estimate is valid.\n"
848  "\nArguments:\n"
849  "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
850  "2. \"estimate_mode\" (string, optional, default=CONSERVATIVE) The fee estimate mode.\n"
851  " Whether to return a more conservative estimate which also satisfies\n"
852  " a longer history. A conservative estimate potentially returns a\n"
853  " higher feerate and is more likely to be sufficient for the desired\n"
854  " target, but is not as responsive to short term drops in the\n"
855  " prevailing fee market. Must be one of:\n"
856  " \"UNSET\" (defaults to CONSERVATIVE)\n"
857  " \"ECONOMICAL\"\n"
858  " \"CONSERVATIVE\"\n"
859  "\nResult:\n"
860  "{\n"
861  " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
862  " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
863  " \"blocks\" : n (numeric) block number where estimate was found\n"
864  "}\n"
865  "\n"
866  "The request target will be clamped between 2 and the highest target\n"
867  "fee estimation is able to return based on how long it has been running.\n"
868  "An error is returned if not enough transactions and blocks\n"
869  "have been observed to make an estimate for any number of blocks.\n"
870  "\nExample:\n"
871  + HelpExampleCli("estimatesmartfee", "6")
872  );
873 
874  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
876  unsigned int conf_target = ParseConfirmTarget(request.params[0]);
877  bool conservative = true;
878  if (!request.params[1].isNull()) {
879  FeeEstimateMode fee_mode;
880  if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
881  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
882  }
883  if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
884  }
885 
886  UniValue result(UniValue::VOBJ);
887  UniValue errors(UniValue::VARR);
888  FeeCalculation feeCalc;
889  CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative);
890  if (feeRate != CFeeRate(0)) {
891  result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
892  } else {
893  errors.push_back("Insufficient data or no feerate found");
894  result.push_back(Pair("errors", errors));
895  }
896  result.push_back(Pair("blocks", feeCalc.returnedTarget));
897  return result;
898 }
899 
901 {
902  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
903  throw std::runtime_error(
904  "estimaterawfee conf_target (threshold)\n"
905  "\nWARNING: This interface is unstable and may disappear or change!\n"
906  "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
907  " implementation of fee estimation. The parameters it can be called with\n"
908  " and the results it returns will change if the internal implementation changes.\n"
909  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
910  "confirmation within conf_target blocks if possible.\n"
911  "\nArguments:\n"
912  "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
913  "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
914  " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
915  " lower buckets. Default: 0.95\n"
916  "\nResult:\n"
917  "{\n"
918  " \"short\" : { (json object, optional) estimate for short time horizon\n"
919  " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
920  " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
921  " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
922  " \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
923  " \"startrange\" : x.x, (numeric) start of feerate range\n"
924  " \"endrange\" : x.x, (numeric) end of feerate range\n"
925  " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
926  " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
927  " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
928  " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
929  " },\n"
930  " \"fail\" : { ... }, (json object, optional) information about the highest range of feerates to fail to meet the threshold\n"
931  " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
932  " },\n"
933  " \"medium\" : { ... }, (json object, optional) estimate for medium time horizon\n"
934  " \"long\" : { ... } (json object) estimate for long time horizon\n"
935  "}\n"
936  "\n"
937  "Results are returned for any horizon which tracks blocks up to the confirmation target.\n"
938  "\nExample:\n"
939  + HelpExampleCli("estimaterawfee", "6 0.9")
940  );
941 
942  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
944  unsigned int conf_target = ParseConfirmTarget(request.params[0]);
945  double threshold = 0.95;
946  if (!request.params[1].isNull()) {
947  threshold = request.params[1].get_real();
948  }
949  if (threshold < 0 || threshold > 1) {
950  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
951  }
952 
953  UniValue result(UniValue::VOBJ);
954 
956  CFeeRate feeRate;
957  EstimationResult buckets;
958 
959  // Only output results for horizons which track the target
960  if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
961 
962  feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
963  UniValue horizon_result(UniValue::VOBJ);
964  UniValue errors(UniValue::VARR);
965  UniValue passbucket(UniValue::VOBJ);
966  passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
967  passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
968  passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
969  passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
970  passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
971  passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
972  UniValue failbucket(UniValue::VOBJ);
973  failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
974  failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
975  failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
976  failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
977  failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
978  failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
979 
980  // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
981  if (feeRate != CFeeRate(0)) {
982  horizon_result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
983  horizon_result.push_back(Pair("decay", buckets.decay));
984  horizon_result.push_back(Pair("scale", (int)buckets.scale));
985  horizon_result.push_back(Pair("pass", passbucket));
986  // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
987  if (buckets.fail.start != -1) horizon_result.push_back(Pair("fail", failbucket));
988  } else {
989  // Output only information that is still meaningful in the event of error
990  horizon_result.push_back(Pair("decay", buckets.decay));
991  horizon_result.push_back(Pair("scale", (int)buckets.scale));
992  horizon_result.push_back(Pair("fail", failbucket));
993  errors.push_back("Insufficient data or no feerate found which meets threshold");
994  horizon_result.push_back(Pair("errors",errors));
995  }
996  result.push_back(Pair(StringForFeeEstimateHorizon(horizon), horizon_result));
997  }
998  return result;
999 }
1000 
1001 static const CRPCCommand commands[] =
1002 { // category name actor (function) argNames
1003  // --------------------- ------------------------ ----------------------- ----------
1004  { "mining", "getnetworkhashps", &getnetworkhashps, {"nblocks","height"} },
1005  { "mining", "getmininginfo", &getmininginfo, {} },
1006  { "mining", "prioritisetransaction", &prioritisetransaction, {"txid","fee_delta"} },
1007  { "mining", "getblocktemplate", &getblocktemplate, {"template_request"} },
1008  { "mining", "submitblock", &submitblock, {"hexdata","dummy"} },
1009 
1010 #if ENABLE_MINER
1011  { "generating", "generatetoaddress", &generatetoaddress, {"nblocks","address","maxtries"} },
1012 #endif // ENABLE_MINER
1013 
1014  { "util", "estimatefee", &estimatefee, {"nblocks"} },
1015  { "util", "estimatesmartfee", &estimatesmartfee, {"conf_target", "estimate_mode"} },
1016 
1017  { "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} },
1018 };
1019 
1021 {
1022  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1023  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1024 }
CConditionVariable g_best_block_cv
Definition: validation.cpp:220
uint32_t nNonce
Definition: block.h:29
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:195
UniValue estimaterawfee(const JSONRPCRequest &request)
Definition: mining.cpp:900
CTxMemPool mempool
EstimatorBucket pass
Definition: fees.h:119
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:80
CMasternodeSync masternodeSync
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:109
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
Ran out of memory during operation.
Definition: protocol.h:52
Dash RPC command dispatcher.
Definition: server.h:140
int64_t GetBlockTime() const
Definition: chain.h:297
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:50
int returnedTarget
Definition: fees.h:130
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:59
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:390
uint64_t nLastBlockSize
Definition: miner.cpp:57
Definition: block.h:72
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
Definition: versionbits.h:37
unsigned int MaxBlockSize(bool fDIP0001Active)
Definition: consensus.h:12
#define strprintf
Definition: tinyformat.h:1066
double start
Definition: fees.h:108
UniValue prioritisetransaction(const JSONRPCRequest &request)
Definition: mining.cpp:244
BlockMap & mapBlockIndex
Definition: validation.cpp:215
UniValue GetNetworkHashPS(int lookup, int height)
Return average network hashes per second based on the last &#39;lookup&#39; blocks, or from the last difficul...
Definition: mining.cpp:57
FeeEstimateMode
Definition: fees.h:97
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1020
UniValue estimatesmartfee(const JSONRPCRequest &request)
Definition: mining.cpp:840
double get_real() const
int Height() const
Return the maximal height in the chain.
Definition: chain.h:484
CCriticalSection cs_main
Definition: validation.cpp:213
bool IsValid() const
Definition: validation.h:61
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:281
CTxDestination DecodeDestination(const std::string &str)
Definition: base58.cpp:336
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:25
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:8
UniValue estimatefee(const JSONRPCRequest &request)
Definition: mining.cpp:800
double GetDifficulty(const CChain &chain, const CBlockIndex *blockindex)
Definition: blockchain.cpp:64
void BlockChecked(const CBlock &block, const CValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:729
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:17
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:83
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:583
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
bool isStr() const
Definition: univalue.h:82
UniValue getmininginfo(const JSONRPCRequest &request)
Definition: mining.cpp:200
int64_t get_int64() const
ThresholdState
Definition: versionbits.h:20
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
int nMasternodePaymentsStartBlock
Definition: params.h:134
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
static const CRPCCommand commands[]
Definition: mining.cpp:1001
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:726
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
CValidationState state
Definition: mining.cpp:724
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:353
double withinTarget
Definition: fees.h:110
bool IsCoinBase() const
Definition: transaction.h:272
void RPCTypeCheck(const UniValue &params, const std::list< UniValue::VType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:54
UniValue getblocktemplate(const JSONRPCRequest &request)
Definition: mining.cpp:300
const std::vector< CTxIn > vin
Definition: transaction.h:215
Invalid, missing or duplicate parameter.
Definition: protocol.h:53
uint256 g_best_block
Definition: validation.cpp:221
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:292
General error during transaction or block submission.
Definition: protocol.h:56
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:332
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:249
iterator end()
Definition: prevector.h:320
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: utiltime.cpp:22
false
Definition: bls_dkg.cpp:168
std::string name
Definition: server.h:132
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:148
unsigned long size()
Definition: txmempool.h:660
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:188
bool IsInvalid() const
Definition: validation.h:64
UniValue generateBlocks(std::shared_ptr< CReserveScript > coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
Generate blocks (mine)
int nSuperblockStartBlock
Definition: params.h:142
CMasternodePayments mnpayments
double end
Definition: fees.h:109
EstimatorBucket fail
Definition: fees.h:120
UniValue params
Definition: server.h:42
DeploymentPos
Definition: params.h:15
CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult *result=nullptr) const
Return a specific fee estimate calculation with a given success threshold and time horizon...
Definition: fees.cpp:672
An input of a transaction.
Definition: transaction.h:70
#define LOCK(cs)
Definition: sync.h:178
const uint256 & GetHash() const
Definition: transaction.h:256
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:819
uint64_t nLastBlockTx
Definition: miner.cpp:56
unsigned int MaxBlockSigOps(bool fDIP0001Active)
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: consensus.h:17
void RPCTypeCheckArgument(const UniValue &value, UniValue::VType typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: server.cpp:72
static bool IsValidBlockHeight(int nBlockHeight)
Is Valid Superblock Height.
uint256 hashPrevBlock
Definition: block.h:25
std::string GetRejectReason() const
Definition: validation.h:81
Unexpected type was passed as parameter.
Definition: protocol.h:50
static UniValue BIP22ValidationResult(const CValidationState &state)
Definition: mining.cpp:273
double inMempool
Definition: fees.h:112
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
std::atomic< bool > fDIP0001ActiveAtTip
Definition: validation.cpp:240
bool IsError() const
Definition: validation.h:67
Generate a new block, without valid proof-of-work.
Definition: miner.h:126
int get_int() const
Invalid address or key.
Definition: protocol.h:51
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:256
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:119
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:578
Parameters that influence chain consensus.
Definition: params.h:130
static std::pair< std::string, UniValue > Pair(const char *cKey, const char *cVal)
Definition: univalue.h:185
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:233
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:255
int64_t GetBlockTime() const
Definition: block.h:65
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:447
bool isNull() const
Definition: univalue.h:78
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:309
VersionBitsCache versionbitscache
RPC method is deprecated.
Definition: protocol.h:60
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:180
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
CFeeRate estimateFee(int confTarget) const
DEPRECATED.
Definition: fees.cpp:663
CSporkManager sporkManager
Definition: spork.cpp:29
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:499
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:182
FeeEstimateHorizon
Definition: fees.h:72
uint256 GetHash() const
Definition: block.cpp:14
bool fHelp
Definition: server.h:43
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:710
bool GetBlockTxOuts(int nBlockHeight, CAmount blockReward, std::vector< CTxOut > &voutMasternodePaymentsRet) const
Capture information about block/transaction validation.
Definition: validation.h:22
256-bit opaque blob.
Definition: uint256.h:123
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:130
std::vector< CTransactionRef > vtx
Definition: block.h:76
uint256 ParseHashStr(const std::string &, const std::string &strName)
Definition: core_read.cpp:134
#define ARRAYLEN(array)
std::string EncodeDestination(const CTxDestination &dest)
Definition: base58.cpp:329
const char * name
Deployment name.
Definition: versionbits.h:35
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:389
const UniValue & get_obj() const
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block...
double leftMempool
Definition: fees.h:113
clock::time_point time_point
Definition: bench.h:47
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:453
std::string GetHex() const
Definition: uint256.cpp:21
int64_t atoi64(const char *psz)
unsigned int ParseConfirmTarget(const UniValue &value)
Check bounds on a command line confirm target.
Definition: mining.cpp:42
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:97
const UniValue NullUniValue
Definition: univalue.cpp:15
std::string i64tostr(int64_t n)
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:350
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
iterator begin()
Definition: prevector.h:318
std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:291
double totalConfirmed
Definition: fees.h:111
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
No valid connection manager instance found.
Definition: protocol.h:74
std::string GetHex() const
Use default settings based on other criteria.
size_t size() const
Definition: univalue.h:69
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
bool IsSporkActive(SporkId nSporkID)
IsSporkActive returns a bool for time-based sporks, and should be used to determine whether the spork...
Definition: spork.cpp:211
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
UniValue submitblock(const JSONRPCRequest &request)
Definition: mining.cpp:737
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:54
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:33
UniValue getnetworkhashps(const JSONRPCRequest &request)
Definition: mining.cpp:94
Still downloading initial blocks.
Definition: protocol.h:69
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
std::unique_lock< std::mutex > WaitableLock
Just a typedef for std::unique_lock, can be wrapped later if desired.
Definition: sync.h:109
Definition: script.h:59
void SetHex(const char *psz)
Definition: uint256.cpp:27
COutPoint prevout
Definition: transaction.h:73
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
P2P client errors.
Definition: protocol.h:68
unsigned int scale
Definition: fees.h:122
double getdouble() const
int32_t nVersion
Definition: block.h:24
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:1317
bool isArray() const
Definition: univalue.h:84
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:41
CWaitableCriticalSection g_best_block_mutex
Definition: validation.cpp:219
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:171
Error parsing or validating structure in raw format.
Definition: protocol.h:55
uint32_t nBits
Definition: block.h:28
uint256 hash
Definition: transaction.h:29
double decay
Definition: fees.h:121
Released under the MIT license