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