Fabcoin Core  0.16.2
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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 <base58.h>
7 #include <amount.h>
8 #include <chain.h>
9 #include <chainparams.h>
10 #include <consensus/consensus.h>
11 #include <consensus/params.h>
12 #include <consensus/validation.h>
13 #include <core_io.h>
14 #include <crypto/equihash.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 <txmempool.h>
25 #include <util.h>
26 #include <utilstrencodings.h>
27 #include <validationinterface.h>
28 #include <warnings.h>
29 
30 #ifdef ENABLE_GPU
31 #include <libgpusolver/libgpusolver.h>
32 #include <libgpusolver/libclwrapper.h>
33 #endif
34 
35 #include <timedata.h>
36 #ifdef ENABLE_WALLET
37 #include <wallet/wallet.h>
38 #include <wallet/walletdb.h>
39 #endif
40 #include <memory>
41 #include <stdint.h>
42 #include <boost/assign/list_of.hpp>
43 #include <boost/shared_ptr.hpp>
44 
45 #include <univalue.h>
46 
47 unsigned int ParseConfirmTarget(const UniValue& value)
48 {
49  int target = value.get_int();
51  if (target < 1 || (unsigned int)target > max_target) {
52  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u - %u", 1, max_target));
53  }
54  return (unsigned int)target;
55 }
56 
62 UniValue GetNetworkHashPS(int lookup, int height) {
63  CBlockIndex *pb = chainActive.Tip();
64 
65  if (height >= 0 && height < chainActive.Height())
66  pb = chainActive[height];
67 
68  if (pb == nullptr || !pb->nHeight)
69  return 0;
70 
71  // If lookup is -1, then use blocks since last difficulty change.
72  if (lookup <= 0)
74 
75  // If lookup is larger than chain, then set it to chain length.
76  if (lookup > pb->nHeight)
77  lookup = pb->nHeight;
78 
79  CBlockIndex *pb0 = pb;
80  int64_t minTime = pb0->GetBlockTime();
81  int64_t maxTime = minTime;
82  for (int i = 0; i < lookup; i++) {
83  pb0 = pb0->pprev;
84  int64_t time = pb0->GetBlockTime();
85  minTime = std::min(time, minTime);
86  maxTime = std::max(time, maxTime);
87  }
88 
89  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
90  if (minTime == maxTime)
91  return 0;
92 
93  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
94  int64_t timeDiff = maxTime - minTime;
95 
96  return workDiff.getdouble() / timeDiff;
97 }
98 
99 // TODO(h4x3rotab): Implement RPC `getlocalsolps`, and maybe `getnetworksolps` as a alias of `getnetworkhashps`.
100 
102 {
103  if (request.fHelp || request.params.size() > 2)
104  throw std::runtime_error(
105  "getnetworkhashps ( nblocks height )\n"
106  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
107  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
108  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
109  "\nArguments:\n"
110  "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
111  "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
112  "\nResult:\n"
113  "x (numeric) Hashes per second estimated\n"
114  "\nExamples:\n"
115  + HelpExampleCli("getnetworkhashps", "")
116  + HelpExampleRpc("getnetworkhashps", "")
117  );
118 
119  LOCK(cs_main);
120  return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1);
121 }
122 
123 
124 #if defined(ENABLE_GPU) && defined(USE_CUDA)
125 #include <../cuda/eqcuda.hpp>
126 
127 static bool cb_cancel()
128 {
129  return false;
130 }
131 
132 static bool cb_validate(std::vector<unsigned char> sols, unsigned char *pblockdata, int thrid)
133 {
134  bool ret = false;
135  CBlock *pblock = (CBlock *)pblockdata;
136 
137  do
138  {
139  pblock->nSolution = sols;
140  CChainParams chainparams = Params();
141  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
142  if (UintToArith256(pblock->GetHash()) > hashTarget)
143  {
144  break;
145  }
146  // Found a solution
148 
149  if (!CheckEquihashSolution(pblock, chainparams ))
150  {
151  LogPrintf("CheckBlockHeader(): Equihash solution invalid at height %d\n", pblock->nHeight);
152  break;
153  }
154 
155  // Check proof of work matches claimed amount
156  if (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, true, chainparams.GetConsensus()))
157  {
158  CBlock dumpBlock(*pblock);
159  LogPrintf("Dump block: Height %d, others == %s \n", pblock->nHeight, dumpBlock.ToString());
160  break;
161  }
162 
164  ret = true;
165  }while(0);
166 
167  return ret;
168 }
169 #endif
170 
171 
172 UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
173 {
174  static const int nInnerLoopCount = 0x10000;
175  int nHeightEnd = 0;
176  int nHeight = 0;
177  int nCounter = 0;
178  int headerlen = 0;
179 
180  { // Don't keep cs_main locked
181  LOCK(cs_main);
182  nHeight = chainActive.Height();
183  nHeightEnd = nHeight+nGenerate;
184  }
185  unsigned int nExtraNonce = 0;
186  UniValue blockHashes(UniValue::VARR);
187  const CChainParams& params = Params();
188  unsigned int n = params.EquihashN();
189  unsigned int k = params.EquihashK();
190 
191  GPUConfig conf;
192  memset(&conf,0,sizeof(GPUConfig));
193 
194  conf.useGPU = gArgs.GetBoolArg("-G", false) || gArgs.GetBoolArg("-GPU", false);
195  conf.selGPU = gArgs.GetArg("-deviceid", 0);
196  conf.allGPU = gArgs.GetBoolArg("-allgpu", 0);
197  conf.forceGenProcLimit = gArgs.GetBoolArg("-forcenolimit", false);
198 
199  uint8_t * header = NULL;
200 #ifdef ENABLE_GPU
201  GPUSolver * g_solver = NULL;
202  if( conf.useGPU )
203  {
204  header = (uint8_t *) calloc(CBlockHeader::HEADER_NEWSIZE, sizeof(uint8_t));
205  LogPrint(BCLog::POW, "Using Equihash solver GPU\n");
206  }
207 #endif
208 
209  while (nHeight < nHeightEnd)
210  {
211 
212  //std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
213  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript, true, nullptr, 0, GetAdjustedTime()+POW_MINER_MAX_TIME));
214 
215  if (!pblocktemplate.get())
216  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
217  nCounter = 0;
218  CBlock *pblock = &pblocktemplate->block;
219  {
220  LOCK(cs_main);
221  IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
222  }
223 
224  n = params.EquihashN(pblock->nHeight);
225  k = params.EquihashK(pblock->nHeight);
226 
227  LogPrintf("Using Equihash solver with n = %u, k = %u\n", n, k);
228 
229  if (pblock->nHeight < (uint32_t)params.GetConsensus().FABHeight)
230  {
231  // Solve sha256d.
232  while (nMaxTries > 0 && (int)pblock->nNonce.GetUint64(0) < nInnerLoopCount &&
233  !CheckProofOfWork(pblock->GetHash(), pblock->nBits, false, Params().GetConsensus()))
234  {
235  pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
236  --nMaxTries;
237  }
238  if ((int)pblock->nNonce.GetUint64(0) == nInnerLoopCount)
239  continue;
240 
241  }
242  else
243  {
244  // Solve Equihash.
245  // I = the block header minus nonce and solution.
246  CEquihashInput I{*pblock};
247  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION );
248  ss << I;
249 
250  crypto_generichash_blake2b_state eh_state;
251  if( conf.useGPU )
252  {
253 #ifdef ENABLE_GPU
254  memcpy(header, &ss[0], ss.size());
255  if( !g_solver )
256  g_solver = new GPUSolver(conf.currentPlatform, conf.currentDevice, n, k);
257 #endif
258  }
259  else
260  {
261  // Solve Equihash.
262  EhInitialiseState(n, k, eh_state);
263  // H(I||...
264  crypto_generichash_blake2b_update(&eh_state, (unsigned char*)&ss[0], ss.size());
265  }
266 
267  while ( nMaxTries > 0 && nCounter < nInnerLoopCount )
268  {
269  crypto_generichash_blake2b_state curr_state;
270  curr_state = eh_state;
271 
272  // Yes, there is a chance every nonce could fail to satisfy the -regtest
273  // target -- 1 in 2^(2^256). That ain't gonna happen
274  pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
275  ++nCounter;
276 
277  if( conf.useGPU )
278  {
279 #ifdef ENABLE_GPU
280  headerlen = ((uint32_t)(nHeight+1) < (uint32_t)params.GetConsensus().ContractHeight) ? CBlockHeader::HEADER_SIZE : CBlockHeader::HEADER_NEWSIZE;
281  for (size_t i = 0; i < FABCOIN_NONCE_LEN; ++i)
282  header[ headerlen-32 + i] = pblock->nNonce.begin()[i];
283 #endif
284  }
285  else
286  {
287  // H(I||V||...
288  curr_state = eh_state;
289  crypto_generichash_blake2b_update(&curr_state, pblock->nNonce.begin(), pblock->nNonce.size());
290  }
291 
292  // (x_1, x_2, ...) = A(I, V, n, k)
293  std::function<bool(std::vector<unsigned char>)> validBlock =
294  [&pblock](std::vector<unsigned char> soln)
295  {
296  pblock->nSolution = soln;
297  // TODO(h4x3rotab): Add metrics counter like Zcash? `solutionTargetChecks.increment();`
298  // TODO(h4x3rotab): Maybe switch to EhBasicSolve and better deal with `nMaxTries`?
299  return CheckProofOfWork(pblock->GetHash(), pblock->nBits, true, Params().GetConsensus());
300  };
301 
302  bool found = false;
303  if( conf.useGPU )
304  {
305 #ifdef ENABLE_GPU
306  found = g_solver->run(n, k, header, headerlen, pblock->nNonce, validBlock, false, curr_state);
307 #endif
308  }
309  else
310  found = EhBasicSolveUncancellable(n, k, curr_state, validBlock);
311  --nMaxTries;
312  // TODO(h4x3rotab): Add metrics counter like Zcash? `ehSolverRuns.increment();`
313  if (found) break;
314  }
315  }
316 
317  if (nMaxTries == 0)
318  break;
319  if (nCounter == nInnerLoopCount)
320  continue;
321 
322  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
323  if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr))
324  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
325  ++nHeight;
326  blockHashes.push_back(pblock->GetHash().GetHex());
327 
328  //mark script as important because it was used at least for one coinbase output if the script came from the wallet
329  if (keepScript)
330  {
331  coinbaseScript->KeepScript();
332  }
333  }
334 
335  if( conf.useGPU )
336  {
337 #ifdef ENABLE_GPU
338  delete g_solver;
339  free(header);
340 #endif
341  }
342 
343  return blockHashes;
344 }
345 
347 {
348  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
349  throw std::runtime_error(
350  "generatetoaddress nblocks address (maxtries)\n"
351  "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
352  "\nArguments:\n"
353  "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
354  "2. address (string, required) The address to send the newly generated fabcoin to.\n"
355  "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
356  "\nResult:\n"
357  "[ blockhashes ] (array) hashes of blocks generated\n"
358  "\nExamples:\n"
359  "\nGenerate 11 blocks to myaddress\n"
360  + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
361  );
362 
363  if (!Params().MineBlocksOnDemand())
364  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
365 
366  int nGenerate = request.params[0].get_int();
367  uint64_t nMaxTries = 1000000;
368  if (!request.params[2].isNull()) {
369  nMaxTries = request.params[2].get_int();
370  }
371 
372  CFabcoinAddress address(request.params[1].get_str());
373  if (!address.IsValid())
374  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
375 
376  std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
377  coinbaseScript->reserveScript = GetScriptForDestination(address.Get());
378 
379  return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
380 }
381 
383 {
384  if (request.fHelp || request.params.size() != 0)
385  throw std::runtime_error(
386  "getmininginfo\n"
387  "\nReturns a json object containing mining-related information."
388  "\nResult:\n"
389  "{\n"
390  " \"blocks\": nnn, (numeric) The current block\n"
391  " \"currentblocksize\": nnn, (numeric) The last block size\n"
392  " \"currentblockweight\": nnn, (numeric) The last block weight\n"
393  " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
394  " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
395  " \"errors\": \"...\" (string) Current errors\n"
396  " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
397  " \"pooledtx\": n (numeric) The size of the mempool\n"
398  " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
399  "}\n"
400  "\nExamples:\n"
401  + HelpExampleCli("getmininginfo", "")
402  + HelpExampleRpc("getmininginfo", "")
403  );
404 
405 
406  LOCK(cs_main);
407 
409  obj.push_back(Pair("blocks", (int)chainActive.Height()));
410  obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight));
411  obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
412  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
413  obj.push_back(Pair("errors", GetWarnings("statusbar")));
414  obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
415  obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
416  obj.push_back(Pair("chain", Params().NetworkIDString()));
417  return obj;
418 }
419 
420 
421 // NOTE: Unlike wallet RPC (which use FAB values), mining RPCs follow GBT (BIP 22) in using liu amounts
423 {
424  if (request.fHelp || request.params.size() != 3)
425  throw std::runtime_error(
426  "prioritisetransaction <txid> <dummy value> <fee delta>\n"
427  "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
428  "\nArguments:\n"
429  "1. \"txid\" (string, required) The transaction id.\n"
430  "2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n"
431  " DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n"
432  "3. fee_delta (numeric, required) The fee value (in liu) to add (or subtract, if negative).\n"
433  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
434  " considers the transaction as it would have paid a higher (or lower) fee.\n"
435  "\nResult:\n"
436  "true (boolean) Returns true\n"
437  "\nExamples:\n"
438  + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
439  + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
440  );
441 
442  LOCK(cs_main);
443 
444  uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
445  CAmount nAmount = request.params[2].get_int64();
446 
447  if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
448  throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
449  }
450 
451  mempool.PrioritiseTransaction(hash, nAmount);
452  return true;
453 }
454 
455 
456 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
457 static UniValue BIP22ValidationResult(const CValidationState& state)
458 {
459  if (state.IsValid())
460  return NullUniValue;
461 
462  std::string strRejectReason = state.GetRejectReason();
463  if (state.IsError())
464  throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
465  if (state.IsInvalid())
466  {
467  if (strRejectReason.empty())
468  return "rejected";
469  return strRejectReason;
470  }
471  // Should be impossible
472  return "valid?";
473 }
474 
475 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
476  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
477  std::string s = vbinfo.name;
478  if (!vbinfo.gbt_force) {
479  s.insert(s.begin(), '!');
480  }
481  return s;
482 }
483 
485 {
486  if (request.fHelp || request.params.size() > 1)
487  throw std::runtime_error(
488  "getblocktemplate ( TemplateRequest )\n"
489  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
490  "It returns data needed to construct a block to work on.\n"
491  "For full specification, see BIPs 22, 23, 9, and 145:\n"
492  " https://github.com/fabcoin/bips/blob/master/bip-0022.mediawiki\n"
493  " https://github.com/fabcoin/bips/blob/master/bip-0023.mediawiki\n"
494  " https://github.com/fabcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
495  " https://github.com/fabcoin/bips/blob/master/bip-0145.mediawiki\n"
496 
497  "\nArguments:\n"
498  "1. template_request (json object, optional) A json object in the following spec\n"
499  " {\n"
500  " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal | proposal_legacy \", or omitted\n"
501  " \"capabilities\":[ (array, optional) A list of strings\n"
502  " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
503  " ,...\n"
504  " ],\n"
505  " \"rules\":[ (array, optional) A list of strings\n"
506  " \"support\" (string) client side supported softfork deployment\n"
507  " ,...\n"
508  " ]\n"
509  " }\n"
510  "\n"
511 
512  "\nResult:\n"
513  "{\n"
514  " \"version\" : n, (numeric) The preferred block version\n"
515  " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
516  " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
517  " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
518  " ,...\n"
519  " },\n"
520  " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
521  " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
522  " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
523  " {\n"
524  " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
525  " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
526  " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
527  " \"depends\" : [ (array) array of numbers \n"
528  " 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"
529  " ,...\n"
530  " ],\n"
531  " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in lius); 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"
532  " \"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"
533  " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
534  " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
535  " }\n"
536  " ,...\n"
537  " ],\n"
538  " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
539  " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
540  " },\n"
541  " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in lius)\n"
542  " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
543  " \"target\" : \"xxxx\", (string) The hash target\n"
544  " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
545  " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
546  " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
547  " ,...\n"
548  " ],\n"
549  " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
550  " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
551  " \"sizelimit\" : n, (numeric) limit of block size\n"
552  " \"weightlimit\" : n, (numeric) limit of block weight\n"
553  " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
554  " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
555  " \"height\" : n (numeric) The height of the next block\n"
556  "}\n"
557 
558  "\nExamples:\n"
559  + HelpExampleCli("getblocktemplate", "")
560  + HelpExampleRpc("getblocktemplate", "")
561  );
562 
563  LOCK(cs_main);
564 
565  std::string strMode = "template";
566  UniValue lpval = NullUniValue;
567  std::set<std::string> setClientRules;
568  int64_t nMaxVersionPreVB = -1;
569  if (!request.params[0].isNull())
570  {
571  const UniValue& oparam = request.params[0].get_obj();
572  const UniValue& modeval = find_value(oparam, "mode");
573  if (modeval.isStr())
574  strMode = modeval.get_str();
575  else if (modeval.isNull())
576  {
577  /* Do nothing */
578  }
579  else
580  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
581  lpval = find_value(oparam, "longpollid");
582 
583  if (strMode == "proposal" || strMode == "proposal_legacy" )
584  {
585  const UniValue& dataval = find_value(oparam, "data");
586  if (!dataval.isStr())
587  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
588 
589  CBlock block;
590 
591  if (!DecodeHexBlk(block, dataval.get_str())){
592  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
593  }
594 
595  uint256 hash = block.GetHash();
596  BlockMap::iterator mi = mapBlockIndex.find(hash);
597  if (mi != mapBlockIndex.end()) {
598  CBlockIndex *pindex = mi->second;
599  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
600  return "duplicate";
601  if (pindex->nStatus & BLOCK_FAILED_MASK)
602  return "duplicate-invalid";
603  return "duplicate-inconclusive";
604  }
605 
606  CBlockIndex* const pindexPrev = chainActive.Tip();
607  // TestBlockValidity only supports blocks built on the current Tip
608  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
609  return "inconclusive-not-best-prevblk";
610  if (block.nHeight != (uint32_t)pindexPrev->nHeight + 1)
611  return "inconclusive-bad-height";
612  CValidationState state;
613  TestBlockValidity(state, Params(), block, pindexPrev, false, true);
614  return BIP22ValidationResult(state);
615  }
616 
617  const UniValue& aClientRules = find_value(oparam, "rules");
618  if (aClientRules.isArray()) {
619  for (unsigned int i = 0; i < aClientRules.size(); ++i) {
620  const UniValue& v = aClientRules[i];
621  setClientRules.insert(v.get_str());
622  }
623  } else {
624  // NOTE: It is important that this NOT be read if versionbits is supported
625  const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
626  if (uvMaxVersion.isNum()) {
627  nMaxVersionPreVB = uvMaxVersion.get_int64();
628  }
629  }
630  }
631 
632  if (strMode != "template")
633  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
634 
635  if(!g_connman)
636  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
637 
638  if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
639  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Fabcoin is not connected!");
640 
642  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Fabcoin is downloading blocks...");
643 
644  static unsigned int nTransactionsUpdatedLast;
645 
646  if (!lpval.isNull())
647  {
648  // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
649  uint256 hashWatchedChain;
650  boost::system_time checktxtime;
651  unsigned int nTransactionsUpdatedLastLP;
652 
653  if (lpval.isStr())
654  {
655  // Format: <hashBestChain><nTransactionsUpdatedLast>
656  std::string lpstr = lpval.get_str();
657 
658  hashWatchedChain.SetHex(lpstr.substr(0, 64));
659  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
660  }
661  else
662  {
663  // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
664  hashWatchedChain = chainActive.Tip()->GetBlockHash();
665  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
666  }
667 
668  // Release the wallet and main lock while waiting
670  {
671  checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
672 
673  boost::unique_lock<boost::mutex> lock(csBestBlock);
674  while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
675  {
676  if (!cvBlockChange.timed_wait(lock, checktxtime))
677  {
678  // Timeout: Check transactions for update
679  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
680  break;
681  checktxtime += boost::posix_time::seconds(10);
682  }
683  }
684  }
686 
687  if (!IsRPCRunning())
688  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
689  // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
690  }
691 
693  // If the caller is indicating segwit support, then allow CreateNewBlock()
694  // to select witness transactions, after segwit activates (otherwise
695  // don't).
696  bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();
697 
698  // Update block
699  static CBlockIndex* pindexPrev;
700  static int64_t nStart;
701  static std::unique_ptr<CBlockTemplate> pblocktemplate;
702  // Cache whether the last invocation was with segwit support, to avoid returning
703  // a segwit-block to a non-segwit caller.
704  static bool fLastTemplateSupportsSegwit = true;
705  if (pindexPrev != chainActive.Tip() ||
706  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
707  fLastTemplateSupportsSegwit != fSupportsSegwit)
708  {
709  // Clear pindexPrev so future calls make a new block, despite any failures from here on
710  pindexPrev = nullptr;
711 
712  // Store the pindexBest used before CreateNewBlock, to avoid races
713  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
714  CBlockIndex* pindexPrevNew = chainActive.Tip();
715  nStart = GetTime();
716  fLastTemplateSupportsSegwit = fSupportsSegwit;
717 
718  // Create new block
719  CScript scriptDummy = CScript() << OP_TRUE;
720  pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
721  if (!pblocktemplate)
722  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
723 
724  // Need to update only after we know CreateNewBlock succeeded
725  pindexPrev = pindexPrevNew;
726  }
727  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
728  const Consensus::Params& consensusParams = Params().GetConsensus();
729 
730  // Update nTime
731  UpdateTime(pblock, consensusParams, pindexPrev);
732  pblock->nNonce = uint256();
733  pblock->nSolution.clear();
734 
735  // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
736  const bool fPreSegWit = !IsWitnessEnabled(pindexPrev, consensusParams);
737 
738  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
739 
740  UniValue transactions(UniValue::VARR);
741  std::map<uint256, int64_t> setTxIndex;
742  int i = 0;
743  for (const auto& it : pblock->vtx) {
744  const CTransaction& tx = *it;
745  uint256 txHash = tx.GetHash();
746  setTxIndex[txHash] = i++;
747 
748  if (tx.IsCoinBase())
749  continue;
750 
751  UniValue entry(UniValue::VOBJ);
752 
753  entry.push_back(Pair("data", EncodeHexTx(tx)));
754  entry.push_back(Pair("txid", txHash.GetHex()));
755  entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
756 
757  UniValue deps(UniValue::VARR);
758  for (const CTxIn &in : tx.vin)
759  {
760  if (setTxIndex.count(in.prevout.hash))
761  deps.push_back(setTxIndex[in.prevout.hash]);
762  }
763  entry.push_back(Pair("depends", deps));
764 
765  int index_in_template = i - 1;
766  entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
767  int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
768  if (fPreSegWit) {
769  assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
770  nTxSigOps /= WITNESS_SCALE_FACTOR;
771  }
772  entry.push_back(Pair("sigops", nTxSigOps));
773  entry.push_back(Pair("weight", GetTransactionWeight(tx)));
774 
775  transactions.push_back(entry);
776  }
777 
780 
781  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
782 
783  UniValue aMutable(UniValue::VARR);
784  aMutable.push_back("time");
785  aMutable.push_back("transactions");
786  aMutable.push_back("prevblock");
787 
788  UniValue result(UniValue::VOBJ);
789  result.push_back(Pair("capabilities", aCaps));
790 
791  UniValue aRules(UniValue::VARR);
792  UniValue vbavailable(UniValue::VOBJ);
793  for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
795  ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
796  switch (state) {
797  case THRESHOLD_DEFINED:
798  case THRESHOLD_FAILED:
799  // Not exposed to GBT at all
800  break;
801  case THRESHOLD_LOCKED_IN:
802  // Ensure bit is set in block version
803  pblock->nVersion |= VersionBitsMask(consensusParams, pos);
804  // FALL THROUGH to get vbavailable set...
805  case THRESHOLD_STARTED:
806  {
807  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
808  vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
809  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
810  if (!vbinfo.gbt_force) {
811  // If the client doesn't support this, don't indicate it in the [default] version
812  pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
813  }
814  }
815  break;
816  }
817  case THRESHOLD_ACTIVE:
818  {
819  // Add to rules only
820  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
821  aRules.push_back(gbt_vb_name(pos));
822  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
823  // Not supported by the client; make sure it's safe to proceed
824  if (!vbinfo.gbt_force) {
825  // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
826  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
827  }
828  }
829  break;
830  }
831  }
832  }
833  result.push_back(Pair("version", pblock->nVersion));
834  result.push_back(Pair("rules", aRules));
835  result.push_back(Pair("vbavailable", vbavailable));
836  result.push_back(Pair("vbrequired", int(0)));
837 
838  if (nMaxVersionPreVB >= 2) {
839  // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
840  // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
841  // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
842  // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
843  aMutable.push_back("version/force");
844  }
845  // TODO(h4x3rotab): Return nHeight?
846  result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
847  result.push_back(Pair("transactions", transactions));
848  result.push_back(Pair("coinbaseaux", aux));
849  result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue));
850  result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
851  result.push_back(Pair("target", hashTarget.GetHex()));
852  result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
853  result.push_back(Pair("mutable", aMutable));
854  result.push_back(Pair("noncerange", "00000000ffffffff"));
855  int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
856  int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
857  if (fPreSegWit) {
858  assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
859  nSigOpLimit /= WITNESS_SCALE_FACTOR;
860  assert(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
861  nSizeLimit /= WITNESS_SCALE_FACTOR;
862  }
863  result.push_back(Pair("sigoplimit", nSigOpLimit));
864  result.push_back(Pair("sizelimit", nSizeLimit));
865  if (!fPreSegWit) {
866  result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
867  }
868  result.push_back(Pair("curtime", pblock->GetBlockTime()));
869  result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
870  result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
871 
872  if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
873  result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
874  }
875 
876  return result;
877 }
878 
880 {
881 public:
883  bool found;
885 
886  submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
887 
888 protected:
889  void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
890  if (block.GetHash() != hash)
891  return;
892  found = true;
893  state = stateIn;
894  }
895 };
896 
898 {
899  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
900  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) {
901  throw std::runtime_error(
902  "submitblock \"hexdata\" ( \"dummy\" )\n"
903  "\nAttempts to submit new block to network.\n"
904  "See https://en.fabcoin.it/wiki/BIP_0022 for full specification.\n"
905 
906  "\nArguments\n"
907  "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
908  "2. \"dummy\" (optional) dummy value, for compatibility with BIP22. This value is ignored.\n"
909  "\nResult:\n"
910  "\nExamples:\n"
911  + HelpExampleCli("submitblock", "\"mydata\"")
912  + HelpExampleRpc("submitblock", "\"mydata\"")
913  );
914  }
915 
916  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
917  CBlock& block = *blockptr;
918 
919  if (!DecodeHexBlk(block, request.params[0].get_str())) {
920  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
921  }
922 
923  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
924  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
925  }
926 
927  uint256 hash = block.GetHash();
928  bool fBlockPresent = false;
929  {
930  LOCK(cs_main);
931  BlockMap::iterator mi = mapBlockIndex.find(hash);
932  if (mi != mapBlockIndex.end()) {
933  CBlockIndex *pindex = mi->second;
934  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
935  return "duplicate";
936  }
937  if (pindex->nStatus & BLOCK_FAILED_MASK) {
938  return "duplicate-invalid";
939  }
940  // Otherwise, we might only have the header - process the block before returning
941  fBlockPresent = true;
942  }
943  }
944 
945  {
946  LOCK(cs_main);
947  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
948  if (mi != mapBlockIndex.end()) {
949  UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
950  }
951  }
952 
953  submitblock_StateCatcher sc(block.GetHash());
955  bool fAccepted = ProcessNewBlock(Params(), blockptr, true, nullptr);
957  if (fBlockPresent) {
958  if (fAccepted && !sc.found) {
959  return "duplicate-inconclusive";
960  }
961  return "duplicate";
962  }
963  if (!sc.found) {
964  return "inconclusive";
965  }
966  return BIP22ValidationResult(sc.state);
967 }
968 
970 {
971  if (request.fHelp || request.params.size() > 1)
972  throw std::runtime_error(
973  "getblocksubsidy height\n"
974  "\nReturns block subsidy reward of block at index provided.\n"
975  "\nArguments:\n"
976  "1. height (numeric, optional) The block height. If not provided, defaults to the current height of the chain.\n"
977  "\nResult:\n"
978  "{\n"
979  "\"miner\": n, (numeric) The mining reward amount in lius.\n"
980  "\"founders\": f, (numeric) Always 0, for Zcash mining compatibility.\n"
981  "}\n"
982  "\nExamples:\n"
983  + HelpExampleCli("getblocksubsidy", "1000")
984  + HelpExampleRpc("getblocksubsidy", "1000")
985  );
986 
987  RPCTypeCheck(request.params, {UniValue::VNUM});
988 
989  LOCK(cs_main);
990  int nHeight = (request.params.size() == 1) ? request.params[0].get_int() : chainActive.Height();
991  if (nHeight < 0)
992  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range.");
993 
994  UniValue result(UniValue::VOBJ);
995 
996  CAmount nReward = GetBlockSubsidy(nHeight, Params().GetConsensus());
997  result.push_back(Pair("miner", nReward));
998  result.push_back(Pair("founders", 0));
999 
1000  return result;
1001 }
1002 
1004 {
1005  if (request.fHelp || request.params.size() != 1)
1006  throw std::runtime_error(
1007  "estimatefee nblocks\n"
1008  "\nDEPRECATED. Please use estimatesmartfee for more intelligent estimates."
1009  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1010  "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
1011  "as defined in BIP 141 (witness data is discounted).\n"
1012  "\nArguments:\n"
1013  "1. nblocks (numeric, required)\n"
1014  "\nResult:\n"
1015  "n (numeric) estimated fee-per-kilobyte\n"
1016  "\n"
1017  "A negative value is returned if not enough transactions and blocks\n"
1018  "have been observed to make an estimate.\n"
1019  "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
1020  "a fee that is high enough to get reliably included in the next block.\n"
1021  "\nExample:\n"
1022  + HelpExampleCli("estimatefee", "6")
1023  );
1024 
1025  RPCTypeCheck(request.params, {UniValue::VNUM});
1026 
1027  int nBlocks = request.params[0].get_int();
1028  if (nBlocks < 1)
1029  nBlocks = 1;
1030 
1031  CFeeRate feeRate = ::feeEstimator.estimateFee(nBlocks);
1032  if (feeRate == CFeeRate(0))
1033  return -1.0;
1034 
1035  return ValueFromAmount(feeRate.GetFeePerK());
1036 }
1037 
1039 {
1040  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1041  throw std::runtime_error(
1042  "estimatesmartfee conf_target (\"estimate_mode\")\n"
1043  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1044  "confirmation within conf_target blocks if possible and return the number of blocks\n"
1045  "for which the estimate is valid. Uses virtual transaction size as defined\n"
1046  "in BIP 141 (witness data is discounted).\n"
1047  "\nArguments:\n"
1048  "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
1049  "2. \"estimate_mode\" (string, optional, default=CONSERVATIVE) The fee estimate mode.\n"
1050  " Whether to return a more conservative estimate which also satisfies\n"
1051  " a longer history. A conservative estimate potentially returns a\n"
1052  " higher feerate and is more likely to be sufficient for the desired\n"
1053  " target, but is not as responsive to short term drops in the\n"
1054  " prevailing fee market. Must be one of:\n"
1055  " \"UNSET\" (defaults to CONSERVATIVE)\n"
1056  " \"ECONOMICAL\"\n"
1057  " \"CONSERVATIVE\"\n"
1058  "\nResult:\n"
1059  "{\n"
1060  " \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in FAB)\n"
1061  " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
1062  " \"blocks\" : n (numeric) block number where estimate was found\n"
1063  "}\n"
1064  "\n"
1065  "The request target will be clamped between 2 and the highest target\n"
1066  "fee estimation is able to return based on how long it has been running.\n"
1067  "An error is returned if not enough transactions and blocks\n"
1068  "have been observed to make an estimate for any number of blocks.\n"
1069  "\nExample:\n"
1070  + HelpExampleCli("estimatesmartfee", "6")
1071  );
1072 
1073  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
1075  unsigned int conf_target = ParseConfirmTarget(request.params[0]);
1076  bool conservative = true;
1077  if (request.params.size() > 1 && !request.params[1].isNull()) {
1078  FeeEstimateMode fee_mode;
1079  if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
1080  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
1081  }
1082  if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
1083  }
1084 
1085  UniValue result(UniValue::VOBJ);
1086  UniValue errors(UniValue::VARR);
1087  FeeCalculation feeCalc;
1088  CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative);
1089  if (feeRate != CFeeRate(0)) {
1090  result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
1091  } else {
1092  errors.push_back("Insufficient data or no feerate found");
1093  result.push_back(Pair("errors", errors));
1094  }
1095  result.push_back(Pair("blocks", feeCalc.returnedTarget));
1096  return result;
1097 }
1098 
1100 {
1101  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1102  throw std::runtime_error(
1103  "estimaterawfee conf_target (threshold)\n"
1104  "\nWARNING: This interface is unstable and may disappear or change!\n"
1105  "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
1106  " implementation of fee estimation. The parameters it can be called with\n"
1107  " and the results it returns will change if the internal implementation changes.\n"
1108  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1109  "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
1110  "defined in BIP 141 (witness data is discounted).\n"
1111  "\nArguments:\n"
1112  "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
1113  "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
1114  " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
1115  " lower buckets. Default: 0.95\n"
1116  "\nResult:\n"
1117  "{\n"
1118  " \"short\" : { (json object, optional) estimate for short time horizon\n"
1119  " \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in FAB)\n"
1120  " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
1121  " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
1122  " \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
1123  " \"startrange\" : x.x, (numeric) start of feerate range\n"
1124  " \"endrange\" : x.x, (numeric) end of feerate range\n"
1125  " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
1126  " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
1127  " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
1128  " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
1129  " },\n"
1130  " \"fail\" : { ... }, (json object, optional) information about the highest range of feerates to fail to meet the threshold\n"
1131  " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
1132  " },\n"
1133  " \"medium\" : { ... }, (json object, optional) estimate for medium time horizon\n"
1134  " \"long\" : { ... } (json object) estimate for long time horizon\n"
1135  "}\n"
1136  "\n"
1137  "Results are returned for any horizon which tracks blocks up to the confirmation target.\n"
1138  "\nExample:\n"
1139  + HelpExampleCli("estimaterawfee", "6 0.9")
1140  );
1141 
1142  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
1144  unsigned int conf_target = ParseConfirmTarget(request.params[0]);
1145  double threshold = 0.95;
1146  if (!request.params[1].isNull()) {
1147  threshold = request.params[1].get_real();
1148  }
1149  if (threshold < 0 || threshold > 1) {
1150  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
1151  }
1152 
1153  UniValue result(UniValue::VOBJ);
1154 
1156  CFeeRate feeRate;
1157  EstimationResult buckets;
1158 
1159  // Only output results for horizons which track the target
1160  if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
1161 
1162  feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
1163  UniValue horizon_result(UniValue::VOBJ);
1164  UniValue errors(UniValue::VARR);
1165  UniValue passbucket(UniValue::VOBJ);
1166  passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
1167  passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
1168  passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
1169  passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
1170  passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
1171  passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
1172  UniValue failbucket(UniValue::VOBJ);
1173  failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
1174  failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
1175  failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
1176  failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
1177  failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
1178  failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
1179 
1180  // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
1181  if (feeRate != CFeeRate(0)) {
1182  horizon_result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
1183  horizon_result.push_back(Pair("decay", buckets.decay));
1184  horizon_result.push_back(Pair("scale", (int)buckets.scale));
1185  horizon_result.push_back(Pair("pass", passbucket));
1186  // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
1187  if (buckets.fail.start != -1) horizon_result.push_back(Pair("fail", failbucket));
1188  } else {
1189  // Output only information that is still meaningful in the event of error
1190  horizon_result.push_back(Pair("decay", buckets.decay));
1191  horizon_result.push_back(Pair("scale", (int)buckets.scale));
1192  horizon_result.push_back(Pair("fail", failbucket));
1193  errors.push_back("Insufficient data or no feerate found which meets threshold");
1194  horizon_result.push_back(Pair("errors",errors));
1195  }
1196  result.push_back(Pair(StringForFeeEstimateHorizon(horizon), horizon_result));
1197  }
1198  return result;
1199 }
1200 
1202 {
1203  if (request.fHelp || request.params.size() != 0)
1204  throw std::runtime_error(
1205  "getgenerate\n"
1206  "\nReturn if the server is set to generate coins or not. The default is false.\n"
1207  "It is set with the command line argument -gen (or " + std::string(FABCOIN_CONF_FILENAME) + " setting gen)\n"
1208  "It can also be set with the setgenerate call.\n"
1209  "\nResult\n"
1210  "true|false (boolean) If the server is set to generate coins or not\n"
1211  "\nExamples:\n"
1212  + HelpExampleCli("getgenerate", "")
1213  + HelpExampleRpc("getgenerate", "")
1214  );
1215 
1216  LOCK(cs_main);
1217  return gArgs.GetBoolArg("-gen", DEFAULT_GENERATE);
1218 }
1219 
1221 {
1222  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1223  throw std::runtime_error(
1224  "setgenerate generate ( genproclimit )\n"
1225  "\nSet 'generate' true or false to turn generation on or off.\n"
1226  "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
1227  "See the getgenerate call for the current setting.\n"
1228  "\nArguments:\n"
1229  "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
1230  "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
1231  "\nExamples:\n"
1232  "\nSet the generation on with a limit of one processor\n"
1233  + HelpExampleCli("setgenerate", "true 1") +
1234  "\nCheck the setting\n"
1235  + HelpExampleCli("getgenerate", "") +
1236  "\nTurn off generation\n"
1237  + HelpExampleCli("setgenerate", "false") +
1238  "\nUsing json rpc\n"
1239  + HelpExampleRpc("setgenerate", "true, 1")
1240  );
1241 
1242  if (Params().MineBlocksOnDemand())
1243  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network");
1244 
1245  bool fGenerate = true;
1246  if (request.params.size() > 0)
1247  fGenerate = request.params[0].get_bool();
1248 
1249  int nGenProcLimit = 1;
1250  if (request.params.size() > 1)
1251  {
1252  nGenProcLimit = request.params[1].get_int();
1253  if (nGenProcLimit == 0)
1254  fGenerate = false;
1255  }
1256 
1257  gArgs.ForceSetArg("-gen",fGenerate ? "1" : "0");
1258  gArgs.ForceSetArg("-genproclimit",itostr(nGenProcLimit));
1259  GenerateFabcoins(fGenerate, nGenProcLimit, Params());
1260 
1261  GPUConfig conf;
1262  conf.useGPU = gArgs.GetBoolArg("-G", false) || gArgs.GetBoolArg("-GPU", false);
1263  conf.selGPU = gArgs.GetArg("-deviceid", 0);
1264  conf.allGPU = gArgs.GetBoolArg("-allgpu", 0);
1265  conf.forceGenProcLimit = gArgs.GetBoolArg("-forcenolimit", false);
1266  GenerateFabcoins(fGenerate, nGenProcLimit, Params(), conf);
1267 
1268  return 0;
1269 }
1270 
1271 
1272 static const CRPCCommand commands[] =
1273 { // category name actor (function) okSafeMode
1274  // --------------------- ------------------------ ----------------------- ----------
1275  { "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} },
1276  { "mining", "getmininginfo", &getmininginfo, true, {} },
1277  { "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","dummy","fee_delta"} },
1278  { "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} },
1279  { "mining", "submitblock", &submitblock, true, {"hexdata","dummy"} },
1280  { "mining", "getblocksubsidy", &getblocksubsidy, true, {"height"} },
1281 
1282  { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} },
1283  { "generating", "getgenerate", &getgenerate, true, {"generate","genproclimit"} },
1284  { "generating", "setgenerate", &setgenerate, true, {"generate"} },
1285 
1286  { "util", "estimatefee", &estimatefee, true, {"nblocks"} },
1287  { "util", "estimatesmartfee", &estimatesmartfee, true, {"conf_target", "estimate_mode"} },
1288 
1289  { "hidden", "estimaterawfee", &estimaterawfee, true, {"conf_target", "threshold"} },
1290 };
1291 
1293 {
1294  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1295  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1296 }
int get_int() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:205
bool forceGenProcLimit
Definition: gpuconfig.h:38
UniValue estimaterawfee(const JSONRPCRequest &request)
Definition: mining.cpp:1099
CAmount GetFeePerK() const
Return the fee in liu for a size of 1000 bytes.
Definition: feerate.h:38
CTxMemPool mempool
EstimatorBucket pass
Definition: fees.h:118
const std::string & get_str() const
size_t size() const
Definition: univalue.h:70
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:76
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:146
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
Ran out of memory during operation.
Definition: protocol.h:52
double get_real() const
uint256 nNonce
Definition: block.h:53
Fabcoin RPC command dispatcher.
Definition: server.h:200
void SetThreadPriority(int nPriority)
Definition: util.cpp:945
int returnedTarget
Definition: fees.h:129
int64_t GetTransactionWeight(const CTransaction &tx)
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:184
UniValue setgenerate(const JSONRPCRequest &request)
Definition: mining.cpp:1220
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:65
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:335
bool IsError() const
Definition: validation.h:72
Definition: block.h:155
CFeeRate estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool &pool)
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:736
unsigned int EquihashN(uint32_t nHeight=0) const
Definition: chainparams.h:72
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
Definition: versionbits.h:37
#define strprintf
Definition: tinyformat.h:1054
#define EhInitialiseState(n, k, base_state)
Definition: equihash.h:204
uint256 GetWitnessHash() const
Definition: transaction.cpp:71
double start
Definition: fees.h:107
UniValue prioritisetransaction(const JSONRPCRequest &request)
Definition: mining.cpp:422
CWaitableCriticalSection csBestBlock
Definition: validation.cpp:82
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:62
std::string GetHex() const
Definition: uint256.cpp:21
unsigned selGPU
Definition: gpuconfig.h:35
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1292
UniValue estimatesmartfee(const JSONRPCRequest &request)
Definition: mining.cpp:1038
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
uint32_t nHeight
Definition: block.h:46
FeeEstimateMode
Definition: fees.h:96
CCriticalSection cs_main
Definition: validation.cpp:77
base58-encoded Fabcoin addresses.
Definition: base58.h:104
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:19
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
bool run(unsigned int n, unsigned int k, uint8_t *header, size_t header_len, uint256 nonce, const std::function< bool(std::vector< unsigned char >)> validBlock, const std::function< bool(GPUSolverCancelCheck)> cancelled, crypto_generichash_blake2b_state base_state)
void GenerateFabcoins(bool fGenerate, int nThreads, const CChainParams &chainparams)
Run the miner threads.
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
UniValue estimatefee(const JSONRPCRequest &request)
Definition: mining.cpp:1003
bool isArray() const
Definition: univalue.h:85
void BlockChecked(const CBlock &block, const CValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:889
CFeeRate estimateFee(int confTarget) const
DEPRECATED.
Definition: fees.cpp:690
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:559
assert(len-trim+(2 *lenIndices)<=WIDTH)
CChainParams defines various tweakable parameters of a given instance of the Fabcoin system...
Definition: chainparams.h:47
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, bool fMineWitnessTx=true, int64_t *pTotalFees=0, int32_t nTime=0, int32_t nTimeLimit=0)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:153
FeeEstimateHorizon
Definition: fees.h:71
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index, or the chain tip if not provided...
Definition: blockchain.cpp:105
UniValue getmininginfo(const JSONRPCRequest &request)
Definition: mining.cpp:382
ThresholdState
Definition: versionbits.h:20
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
uint64_t GetUint64(int pos) const
Definition: uint256.h:90
UniValue getblocksubsidy(const JSONRPCRequest &request)
Definition: mining.cpp:969
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: util.cpp:545
ExecStats::duration min
Definition: ExecStats.cpp:35
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:886
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:884
#define FABCOIN_NONCE_LEN
Definition: libclwrapper.h:8
unsigned char * begin()
Definition: uint256.h:65
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:298
double withinTarget
Definition: fees.h:109
uint32_t FABHeight
Block height at which Fabcoin Equihash hard fork becomes active.
Definition: params.h:52
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:59
UniValue getblocktemplate(const JSONRPCRequest &request)
Definition: mining.cpp:484
const std::vector< CTxIn > vin
Definition: transaction.h:292
Invalid, missing or duplicate parameter.
Definition: protocol.h:53
arith_uint256 UintToArith256(const uint256 &a)
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:53
uint64_t nLastBlockWeight
Definition: miner.cpp:63
UniValue generateBlocks(std::shared_ptr< CReserveScript > coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
Generate blocks (mine)
Definition: mining.cpp:172
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:354
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams &params)
Check whether the Equihash solution in a block header is valid.
Definition: pow.cpp:258
General error during transaction or block submission.
Definition: protocol.h:56
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:106
#define THREAD_PRIORITY_NORMAL
Definition: compat.h:82
iterator end()
Definition: prevector.h:292
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:512
std::string name
Definition: server.h:191
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:20
int Height() const
Return the maximal height in the chain.
Definition: chain.h:543
int64_t get_int64() const
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:771
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
#define LogPrintf(...)
Definition: util.h:153
bool CheckProofOfWork(uint256 hash, unsigned int nBits, bool postfork, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:290
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:217
double getdouble() const
#define THREAD_PRIORITY_LOWEST
Definition: compat.h:80
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:155
unsigned long size()
Definition: txmempool.h:659
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:185
double end
Definition: fees.h:108
const char *const FABCOIN_CONF_FILENAME
Definition: util.cpp:91
EstimatorBucket fail
Definition: fees.h:119
UniValue params
Definition: server.h:59
int64_t GetBlockTime() const
Definition: block.h:127
DeploymentPos
Definition: params.h:15
An input of a transaction.
Definition: transaction.h:61
#define LOCK(cs)
Definition: sync.h:175
size_type size() const
Definition: streams.h:237
const Object_type::value_type::Value_type & find_value(const Object_type &obj, const String_type &name)
bool isNum() const
Definition: univalue.h:84
uint64_t nLastBlockTx
Definition: miner.cpp:62
void RPCTypeCheckArgument(const UniValue &value, UniValue::VType typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: server.cpp:77
uint32_t ContractHeight
Block height at which Fabcoin Smart Contract hard fork becomes active.
Definition: params.h:56
uint256 hashPrevBlock
Definition: block.h:44
Unexpected type was passed as parameter.
Definition: protocol.h:50
double inMempool
Definition: fees.h:111
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Generate a new block, without valid proof-of-work.
Definition: miner.h:187
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:40
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
bool IsValid() const
Definition: validation.h:66
Invalid address or key.
Definition: protocol.h:51
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:370
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:554
UniValue getgenerate(const JSONRPCRequest &request)
Definition: mining.cpp:1201
bool EhBasicSolveUncancellable(unsigned int n, unsigned int k, const eh_HashState &base_state, const std::function< bool(std::vector< unsigned char >)> validBlock)
Definition: equihash.h:238
Parameters that influence chain consensus.
Definition: params.h:39
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:113
std::vector< unsigned char > nSolution
Definition: block.h:54
std::string GetHex() const
256-bit unsigned big integer.
int64_t DifficultyAdjustmentInterval(uint32_t nheight=0) const
Definition: params.h:84
VersionBitsCache versionbitscache
Custom serializer for CBlockHeader that omits the nonce and solution, for use as input to Equihash...
Definition: block.h:215
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
bool IsInvalid() const
Definition: validation.h:69
std::string GetRejectReason() const
Definition: validation.h:89
#define LogPrint(category,...)
Definition: util.h:164
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:715
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:179
std::string ToString() const
Definition: block.cpp:66
bool fHelp
Definition: server.h:60
bool allGPU
Definition: gpuconfig.h:36
Capture information about block/transaction validation.
Definition: validation.h:27
256-bit opaque blob.
Definition: uint256.h:132
ArgsManager gArgs
Definition: util.cpp:94
uint256 ArithToUint256(const arith_uint256 &a)
std::vector< CTransactionRef > vtx
Definition: block.h:159
uint256 GetHash() const
Definition: block.cpp:38
uint256 ParseHashStr(const std::string &, const std::string &strName)
Definition: core_read.cpp:171
#define ARRAYLEN(array)
unsigned currentDevice
Definition: gpuconfig.h:40
const char * name
Deployment name.
Definition: versionbits.h:35
static const size_t HEADER_SIZE
Definition: block.h:39
bool useGPU
Definition: gpuconfig.h:33
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:177
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
void * memcpy(void *a, const void *b, size_t c)
#define I(x, y, z)
Definition: Hash.cpp:82
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
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...
#define round(a, b, c, x, mul)
double leftMempool
Definition: fees.h:112
int64_t atoi64(const char *psz)
unsigned int ParseConfirmTarget(const UniValue &value)
Check bounds on a command line confirm target.
Definition: mining.cpp:47
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:124
Fee rate in liu per kilobyte: CAmount / kB.
Definition: feerate.h:20
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:75
const UniValue NullUniValue
Definition: univalue.cpp:15
std::string i64tostr(int64_t n)
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:290
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:379
std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:475
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
bool IsCoinBase() const
Definition: transaction.h:349
double totalConfirmed
Definition: fees.h:110
const uint256 & GetHash() const
Definition: transaction.h:325
UniValue generatetoaddress(const JSONRPCRequest &request)
Definition: mining.cpp:346
bool get_bool() const
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
unsigned currentPlatform
Definition: gpuconfig.h:39
No valid connection manager instance found.
Definition: protocol.h:73
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:19
struct evm_uint160be address(struct evm_env *env)
Definition: capi.c:13
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
Use default settings based on other criteria.
UniValue submitblock(const JSONRPCRequest &request)
Definition: mining.cpp:897
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:29
UniValue getnetworkhashps(const JSONRPCRequest &request)
Definition: mining.cpp:101
Still downloading initial blocks.
Definition: protocol.h:68
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:699
int64_t GetBlockTime() const
Definition: chain.h:329
const UniValue & get_obj() const
bool isNull() const
Definition: univalue.h:79
Definition: script.h:59
void SetHex(const char *psz)
Definition: uint256.cpp:39
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
static const size_t HEADER_NEWSIZE
Definition: block.h:40
unsigned int scale
Definition: fees.h:121
Config::Pair_type Pair
int64_t GetMedianTimePast() const
Definition: chain.h:341
int32_t nVersion
Definition: block.h:43
unsigned int EquihashK(uint32_t nHeight=0) const
Definition: chainparams.h:73
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:844
BlockMap mapBlockIndex
Definition: validation.cpp:79
bool isStr() const
Definition: univalue.h:83
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:72
std::string itostr(int n)
Error parsing or validating structure in raw format.
Definition: protocol.h:55
uint256 GetBlockHash() const
Definition: chain.h:324
uint32_t nBits
Definition: block.h:49
CConditionVariable cvBlockChange
Definition: validation.cpp:83
unsigned int size() const
Definition: uint256.h:85
uint256 hash
Definition: transaction.h:21
double decay
Definition: fees.h:120