Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

blockchain.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2020 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <rpc/blockchain.h>
8 
9 #include <amount.h>
10 #include <chain.h>
11 #include <chainparams.h>
12 #include <checkpoints.h>
13 #include <coins.h>
14 #include <core_io.h>
15 #include <consensus/validation.h>
16 #include <validation.h>
17 #include <core_io.h>
18 // #include <rpc/index/txindex.h>
19 #include <policy/feerate.h>
20 #include <policy/policy.h>
21 #include <primitives/transaction.h>
22 #include <rpc/server.h>
23 #include <streams.h>
24 #include <sync.h>
25 #include <txdb.h>
26 #include <txmempool.h>
27 #include <util.h>
28 #include <utilstrencodings.h>
29 #include <hash.h>
30 #include <warnings.h>
31 
32 #include <evo/specialtx.h>
33 #include <evo/cbtx.h>
34 
37 
38 #include <stdint.h>
39 
40 #include <univalue.h>
41 
42 #include <boost/algorithm/string.hpp>
43 #include <boost/thread/thread.hpp> // boost::thread::interrupt
44 
45 #include <memory>
46 #include <mutex>
47 #include <condition_variable>
48 
50 {
52  int height;
53 };
54 
55 static std::mutex cs_blockchange;
56 static std::condition_variable cond_blockchange;
58 
59 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
60 
61 /* Calculate the difficulty for a given block index,
62  * or the block index of the given chain.
63  */
64 double GetDifficulty(const CChain& chain, const CBlockIndex* blockindex)
65 {
66  if (blockindex == nullptr)
67  {
68  if (chain.Tip() == nullptr)
69  return 1.0;
70  else
71  blockindex = chain.Tip();
72  }
73 
74  int nShift = (blockindex->nBits >> 24) & 0xff;
75  double dDiff =
76  (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
77 
78  while (nShift < 29)
79  {
80  dDiff *= 256.0;
81  nShift++;
82  }
83  while (nShift > 29)
84  {
85  dDiff /= 256.0;
86  nShift--;
87  }
88 
89  return dDiff;
90 }
91 
92 double GetDifficulty(const CBlockIndex* blockindex)
93 {
94  return GetDifficulty(chainActive, blockindex);
95 }
96 
98 {
100  UniValue result(UniValue::VOBJ);
101  result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
102  int confirmations = -1;
103  // Only report confirmations if the block is on the main chain
104  if (chainActive.Contains(blockindex))
105  confirmations = chainActive.Height() - blockindex->nHeight + 1;
106  result.push_back(Pair("confirmations", confirmations));
107  result.push_back(Pair("height", blockindex->nHeight));
108  result.push_back(Pair("version", blockindex->nVersion));
109  result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
110  result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
111  result.push_back(Pair("time", (int64_t)blockindex->nTime));
112  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
113  result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
114  result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
115  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
116  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
117  result.push_back(Pair("nTx", (uint64_t)blockindex->nTx));
118 
119  if (blockindex->pprev)
120  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
121  CBlockIndex *pnext = chainActive.Next(blockindex);
122  if (pnext)
123  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
124 
125  result.push_back(Pair("chainlock", llmq::chainLocksHandler->HasChainLock(blockindex->nHeight, blockindex->GetBlockHash())));
126 
127  return result;
128 }
129 
130 UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails)
131 {
133  UniValue result(UniValue::VOBJ);
134  result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
135  int confirmations = -1;
136  // Only report confirmations if the block is on the main chain
137  if (chainActive.Contains(blockindex))
138  confirmations = chainActive.Height() - blockindex->nHeight + 1;
139  result.push_back(Pair("confirmations", confirmations));
140  result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
141  result.push_back(Pair("height", blockindex->nHeight));
142  result.push_back(Pair("version", block.nVersion));
143  result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
144  result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
145  bool chainLock = llmq::chainLocksHandler->HasChainLock(blockindex->nHeight, blockindex->GetBlockHash());
147  for(const auto& tx : block.vtx)
148  {
149  if(txDetails)
150  {
151  UniValue objTx(UniValue::VOBJ);
152  TxToUniv(*tx, uint256(), objTx, true);
153  bool fLocked = llmq::quorumInstantSendManager->IsLocked(tx->GetHash());
154  objTx.push_back(Pair("instantlock", fLocked || chainLock));
155  objTx.push_back(Pair("instantlock_internal", fLocked));
156  txs.push_back(objTx);
157  }
158  else
159  txs.push_back(tx->GetHash().GetHex());
160  }
161  result.push_back(Pair("tx", txs));
162  if (!block.vtx[0]->vExtraPayload.empty()) {
163  CCbTx cbTx;
164  if (GetTxPayload(block.vtx[0]->vExtraPayload, cbTx)) {
165  UniValue cbTxObj;
166  cbTx.ToJson(cbTxObj);
167  result.push_back(Pair("cbTx", cbTxObj));
168  }
169  }
170  result.push_back(Pair("time", block.GetBlockTime()));
171  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
172  result.push_back(Pair("nonce", (uint64_t)block.nNonce));
173  result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
174  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
175  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
176  result.push_back(Pair("nTx", (uint64_t)blockindex->nTx));
177 
178  if (blockindex->pprev)
179  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
180  CBlockIndex *pnext = chainActive.Next(blockindex);
181  if (pnext)
182  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
183 
184  result.push_back(Pair("chainlock", chainLock));
185 
186  return result;
187 }
188 
190 {
191  if (request.fHelp || request.params.size() != 0)
192  throw std::runtime_error(
193  "getblockcount\n"
194  "\nReturns the number of blocks in the longest blockchain.\n"
195  "\nResult:\n"
196  "n (numeric) The current block count\n"
197  "\nExamples:\n"
198  + HelpExampleCli("getblockcount", "")
199  + HelpExampleRpc("getblockcount", "")
200  );
201 
202  LOCK(cs_main);
203  return chainActive.Height();
204 }
205 
207 {
208  if (request.fHelp || request.params.size() != 0)
209  throw std::runtime_error(
210  "getbestblockhash\n"
211  "\nReturns the hash of the best (tip) block in the longest blockchain.\n"
212  "\nResult:\n"
213  "\"hex\" (string) the block hash hex encoded\n"
214  "\nExamples:\n"
215  + HelpExampleCli("getbestblockhash", "")
216  + HelpExampleRpc("getbestblockhash", "")
217  );
218 
219  LOCK(cs_main);
220  return chainActive.Tip()->GetBlockHash().GetHex();
221 }
222 
224 {
225  if (request.fHelp || request.params.size() != 0)
226  throw std::runtime_error(
227  "getbestchainlock\n"
228  "\nReturns the block hash of the best chainlock. Throws an error if there is no known chainlock yet. "
229  "\nResult:\n"
230  "{\n"
231  " \"blockhash\" : \"hash\", (string) The block hash hex encoded\n"
232  " \"height\" : n, (numeric) The block height or index\n"
233  " \"known_block\" : true|false (boolean) True if the block is known by our node\n"
234  "}\n"
235  "\nExamples:\n"
236  + HelpExampleCli("getbestchainlock", "")
237  + HelpExampleRpc("getbestchainlock", "")
238  );
239  UniValue result(UniValue::VOBJ);
240 
242  if (clsig.IsNull()) {
243  throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to find any chainlock");
244  }
245  result.push_back(Pair("blockhash", clsig.blockHash.GetHex()));
246  result.push_back(Pair("height", clsig.nHeight));
247  LOCK(cs_main);
248  result.push_back(Pair("known_block", mapBlockIndex.count(clsig.blockHash) > 0));
249  return result;
250 }
251 
252 void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
253 {
254  if(pindex) {
255  std::lock_guard<std::mutex> lock(cs_blockchange);
256  latestblock.hash = pindex->GetBlockHash();
257  latestblock.height = pindex->nHeight;
258  }
259  cond_blockchange.notify_all();
260 }
261 
263 {
264  if (request.fHelp || request.params.size() > 1)
265  throw std::runtime_error(
266  "waitfornewblock (timeout)\n"
267  "\nWaits for a specific new block and returns useful info about it.\n"
268  "\nReturns the current block on timeout or exit.\n"
269  "\nArguments:\n"
270  "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
271  "\nResult:\n"
272  "{ (json object)\n"
273  " \"hash\" : { (string) The blockhash\n"
274  " \"height\" : { (int) Block height\n"
275  "}\n"
276  "\nExamples:\n"
277  + HelpExampleCli("waitfornewblock", "1000")
278  + HelpExampleRpc("waitfornewblock", "1000")
279  );
280  int timeout = 0;
281  if (!request.params[0].isNull())
282  timeout = request.params[0].get_int();
283 
284  CUpdatedBlock block;
285  {
286  std::unique_lock<std::mutex> lock(cs_blockchange);
287  block = latestblock;
288  if(timeout)
289  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
290  else
291  cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
292  block = latestblock;
293  }
295  ret.push_back(Pair("hash", block.hash.GetHex()));
296  ret.push_back(Pair("height", block.height));
297  return ret;
298 }
299 
301 {
302  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
303  throw std::runtime_error(
304  "waitforblock <blockhash> (timeout)\n"
305  "\nWaits for a specific new block and returns useful info about it.\n"
306  "\nReturns the current block on timeout or exit.\n"
307  "\nArguments:\n"
308  "1. \"blockhash\" (required, string) Block hash to wait for.\n"
309  "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
310  "\nResult:\n"
311  "{ (json object)\n"
312  " \"hash\" : { (string) The blockhash\n"
313  " \"height\" : { (int) Block height\n"
314  "}\n"
315  "\nExamples:\n"
316  + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
317  + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
318  );
319  int timeout = 0;
320 
321  uint256 hash = uint256S(request.params[0].get_str());
322 
323  if (!request.params[1].isNull())
324  timeout = request.params[1].get_int();
325 
326  CUpdatedBlock block;
327  {
328  std::unique_lock<std::mutex> lock(cs_blockchange);
329  if(timeout)
330  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
331  else
332  cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
333  block = latestblock;
334  }
335 
337  ret.push_back(Pair("hash", block.hash.GetHex()));
338  ret.push_back(Pair("height", block.height));
339  return ret;
340 }
341 
343 {
344  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
345  throw std::runtime_error(
346  "waitforblockheight <height> (timeout)\n"
347  "\nWaits for (at least) block height and returns the height and hash\n"
348  "of the current tip.\n"
349  "\nReturns the current block on timeout or exit.\n"
350  "\nArguments:\n"
351  "1. height (required, int) Block height to wait for (int)\n"
352  "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
353  "\nResult:\n"
354  "{ (json object)\n"
355  " \"hash\" : { (string) The blockhash\n"
356  " \"height\" : { (int) Block height\n"
357  "}\n"
358  "\nExamples:\n"
359  + HelpExampleCli("waitforblockheight", "\"100\", 1000")
360  + HelpExampleRpc("waitforblockheight", "\"100\", 1000")
361  );
362  int timeout = 0;
363 
364  int height = request.params[0].get_int();
365 
366  if (!request.params[1].isNull())
367  timeout = request.params[1].get_int();
368 
369  CUpdatedBlock block;
370  {
371  std::unique_lock<std::mutex> lock(cs_blockchange);
372  if(timeout)
373  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
374  else
375  cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
376  block = latestblock;
377  }
379  ret.push_back(Pair("hash", block.hash.GetHex()));
380  ret.push_back(Pair("height", block.height));
381  return ret;
382 }
383 
385 {
386  if (request.fHelp || request.params.size() != 0)
387  throw std::runtime_error(
388  "getdifficulty\n"
389  "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
390  "\nResult:\n"
391  "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
392  "\nExamples:\n"
393  + HelpExampleCli("getdifficulty", "")
394  + HelpExampleRpc("getdifficulty", "")
395  );
396 
397  LOCK(cs_main);
398  return GetDifficulty();
399 }
400 
402 {
403  return " \"size\" : n, (numeric) transaction size in bytes\n"
404  " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
405  " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
406  " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
407  " \"height\" : n, (numeric) block height when transaction entered pool\n"
408  " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
409  " \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
410  " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
411  " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
412  " \"ancestorsize\" : n, (numeric) size of in-mempool ancestors (including this one)\n"
413  " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
414  " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
415  " \"transactionid\", (string) parent transaction id\n"
416  " ... ],\n"
417  " \"instantlock\" : true|false (boolean) True if this transaction was locked via InstantSend\n";
418 }
419 
420 void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
421 {
423 
424  info.push_back(Pair("size", (int)e.GetTxSize()));
425  info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
426  info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
427  info.push_back(Pair("time", e.GetTime()));
428  info.push_back(Pair("height", (int)e.GetHeight()));
429  info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
430  info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
431  info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
432  info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
433  info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
434  info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
435  const CTransaction& tx = e.GetTx();
436  std::set<std::string> setDepends;
437  for (const CTxIn& txin : tx.vin)
438  {
439  if (mempool.exists(txin.prevout.hash))
440  setDepends.insert(txin.prevout.hash.ToString());
441  }
442 
443  UniValue depends(UniValue::VARR);
444  for (const std::string& dep : setDepends)
445  {
446  depends.push_back(dep);
447  }
448 
449  info.push_back(Pair("depends", depends));
450  info.push_back(Pair("instantlock", llmq::quorumInstantSendManager->IsLocked(tx.GetHash())));
451 }
452 
453 UniValue mempoolToJSON(bool fVerbose)
454 {
455  if (fVerbose)
456  {
457  LOCK(mempool.cs);
459  for (const CTxMemPoolEntry& e : mempool.mapTx)
460  {
461  const uint256& hash = e.GetTx().GetHash();
462  UniValue info(UniValue::VOBJ);
463  entryToJSON(info, e);
464  o.push_back(Pair(hash.ToString(), info));
465  }
466  return o;
467  }
468  else
469  {
470  std::vector<uint256> vtxid;
471  mempool.queryHashes(vtxid);
472 
474  for (const uint256& hash : vtxid)
475  a.push_back(hash.ToString());
476 
477  return a;
478  }
479 }
480 
482 {
483  if (request.fHelp || request.params.size() > 1)
484  throw std::runtime_error(
485  "getrawmempool ( verbose )\n"
486  "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
487  "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n"
488  "\nArguments:\n"
489  "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
490  "\nResult: (for verbose = false):\n"
491  "[ (json array of string)\n"
492  " \"transactionid\" (string) The transaction id\n"
493  " ,...\n"
494  "]\n"
495  "\nResult: (for verbose = true):\n"
496  "{ (json object)\n"
497  " \"transactionid\" : { (json object)\n"
499  + " }, ...\n"
500  "}\n"
501  "\nExamples:\n"
502  + HelpExampleCli("getrawmempool", "true")
503  + HelpExampleRpc("getrawmempool", "true")
504  );
505 
506  bool fVerbose = false;
507  if (!request.params[0].isNull())
508  fVerbose = request.params[0].get_bool();
509 
510  return mempoolToJSON(fVerbose);
511 }
512 
514 {
515  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
516  throw std::runtime_error(
517  "getmempoolancestors txid (verbose)\n"
518  "\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
519  "\nArguments:\n"
520  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
521  "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
522  "\nResult (for verbose=false):\n"
523  "[ (json array of strings)\n"
524  " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
525  " ,...\n"
526  "]\n"
527  "\nResult (for verbose=true):\n"
528  "{ (json object)\n"
529  " \"transactionid\" : { (json object)\n"
531  + " }, ...\n"
532  "}\n"
533  "\nExamples:\n"
534  + HelpExampleCli("getmempoolancestors", "\"mytxid\"")
535  + HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
536  );
537  }
538 
539  bool fVerbose = false;
540  if (!request.params[1].isNull())
541  fVerbose = request.params[1].get_bool();
542 
543  uint256 hash = ParseHashV(request.params[0], "parameter 1");
544 
545  LOCK(mempool.cs);
546 
547  CTxMemPool::txiter it = mempool.mapTx.find(hash);
548  if (it == mempool.mapTx.end()) {
549  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
550  }
551 
552  CTxMemPool::setEntries setAncestors;
553  uint64_t noLimit = std::numeric_limits<uint64_t>::max();
554  std::string dummy;
555  mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
556 
557  if (!fVerbose) {
559  for (CTxMemPool::txiter ancestorIt : setAncestors) {
560  o.push_back(ancestorIt->GetTx().GetHash().ToString());
561  }
562 
563  return o;
564  } else {
566  for (CTxMemPool::txiter ancestorIt : setAncestors) {
567  const CTxMemPoolEntry &e = *ancestorIt;
568  const uint256& _hash = e.GetTx().GetHash();
569  UniValue info(UniValue::VOBJ);
570  entryToJSON(info, e);
571  o.push_back(Pair(_hash.ToString(), info));
572  }
573  return o;
574  }
575 }
576 
578 {
579  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
580  throw std::runtime_error(
581  "getmempooldescendants txid (verbose)\n"
582  "\nIf txid is in the mempool, returns all in-mempool descendants.\n"
583  "\nArguments:\n"
584  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
585  "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
586  "\nResult (for verbose=false):\n"
587  "[ (json array of strings)\n"
588  " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
589  " ,...\n"
590  "]\n"
591  "\nResult (for verbose=true):\n"
592  "{ (json object)\n"
593  " \"transactionid\" : { (json object)\n"
595  + " }, ...\n"
596  "}\n"
597  "\nExamples:\n"
598  + HelpExampleCli("getmempooldescendants", "\"mytxid\"")
599  + HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
600  );
601  }
602 
603  bool fVerbose = false;
604  if (!request.params[1].isNull())
605  fVerbose = request.params[1].get_bool();
606 
607  uint256 hash = ParseHashV(request.params[0], "parameter 1");
608 
609  LOCK(mempool.cs);
610 
611  CTxMemPool::txiter it = mempool.mapTx.find(hash);
612  if (it == mempool.mapTx.end()) {
613  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
614  }
615 
616  CTxMemPool::setEntries setDescendants;
617  mempool.CalculateDescendants(it, setDescendants);
618  // CTxMemPool::CalculateDescendants will include the given tx
619  setDescendants.erase(it);
620 
621  if (!fVerbose) {
623  for (CTxMemPool::txiter descendantIt : setDescendants) {
624  o.push_back(descendantIt->GetTx().GetHash().ToString());
625  }
626 
627  return o;
628  } else {
630  for (CTxMemPool::txiter descendantIt : setDescendants) {
631  const CTxMemPoolEntry &e = *descendantIt;
632  const uint256& _hash = e.GetTx().GetHash();
633  UniValue info(UniValue::VOBJ);
634  entryToJSON(info, e);
635  o.push_back(Pair(_hash.ToString(), info));
636  }
637  return o;
638  }
639 }
640 
642 {
643  if (request.fHelp || request.params.size() != 1) {
644  throw std::runtime_error(
645  "getmempoolentry txid\n"
646  "\nReturns mempool data for given transaction\n"
647  "\nArguments:\n"
648  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
649  "\nResult:\n"
650  "{ (json object)\n"
652  + "}\n"
653  "\nExamples:\n"
654  + HelpExampleCli("getmempoolentry", "\"mytxid\"")
655  + HelpExampleRpc("getmempoolentry", "\"mytxid\"")
656  );
657  }
658 
659  uint256 hash = ParseHashV(request.params[0], "parameter 1");
660 
661  LOCK(mempool.cs);
662 
663  CTxMemPool::txiter it = mempool.mapTx.find(hash);
664  if (it == mempool.mapTx.end()) {
665  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
666  }
667 
668  const CTxMemPoolEntry &e = *it;
669  UniValue info(UniValue::VOBJ);
670  entryToJSON(info, e);
671  return info;
672 }
673 
675 {
676  if (request.fHelp || request.params.size() != 2)
677  throw std::runtime_error(
678  "getblockhashes timestamp\n"
679  "\nReturns array of hashes of blocks within the timestamp range provided.\n"
680  "\nArguments:\n"
681  "1. high (numeric, required) The newer block timestamp\n"
682  "2. low (numeric, required) The older block timestamp\n"
683  "\nResult:\n"
684  "[\n"
685  " \"hash\" (string) The block hash\n"
686  "]\n"
687  "\nExamples:\n"
688  + HelpExampleCli("getblockhashes", "1231614698 1231024505")
689  + HelpExampleRpc("getblockhashes", "1231614698, 1231024505")
690  );
691 
692  unsigned int high = request.params[0].get_int();
693  unsigned int low = request.params[1].get_int();
694  std::vector<uint256> blockHashes;
695 
696  if (!GetTimestampIndex(high, low, blockHashes)) {
697  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
698  }
699 
700  UniValue result(UniValue::VARR);
701  for (std::vector<uint256>::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) {
702  result.push_back(it->GetHex());
703  }
704 
705  return result;
706 }
707 
709 {
710  if (request.fHelp || request.params.size() != 1)
711  throw std::runtime_error(
712  "getblockhash height\n"
713  "\nReturns hash of block in best-block-chain at height provided.\n"
714  "\nArguments:\n"
715  "1. height (numeric, required) The height index\n"
716  "\nResult:\n"
717  "\"hash\" (string) The block hash\n"
718  "\nExamples:\n"
719  + HelpExampleCli("getblockhash", "1000")
720  + HelpExampleRpc("getblockhash", "1000")
721  );
722 
723  LOCK(cs_main);
724 
725  int nHeight = request.params[0].get_int();
726  if (nHeight < 0 || nHeight > chainActive.Height())
727  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
728 
729  CBlockIndex* pblockindex = chainActive[nHeight];
730  return pblockindex->GetBlockHash().GetHex();
731 }
732 
734 {
735  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
736  throw std::runtime_error(
737  "getblockheader \"hash\" ( verbose )\n"
738  "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
739  "If verbose is true, returns an Object with information about blockheader <hash>.\n"
740  "\nArguments:\n"
741  "1. \"hash\" (string, required) The block hash\n"
742  "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
743  "\nResult (for verbose = true):\n"
744  "{\n"
745  " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
746  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
747  " \"height\" : n, (numeric) The block height or index\n"
748  " \"version\" : n, (numeric) The block version\n"
749  " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
750  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
751  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
752  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
753  " \"nonce\" : n, (numeric) The nonce\n"
754  " \"bits\" : \"1d00ffff\", (string) The bits\n"
755  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
756  " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
757  " \"nTx\" : n, (numeric) The number of transactions in the block.\n"
758  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
759  " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
760  "}\n"
761  "\nResult (for verbose=false):\n"
762  "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
763  "\nExamples:\n"
764  + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
765  + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
766  );
767 
768  LOCK(cs_main);
769 
770  std::string strHash = request.params[0].get_str();
771  uint256 hash(uint256S(strHash));
772 
773  bool fVerbose = true;
774  if (!request.params[1].isNull())
775  fVerbose = request.params[1].get_bool();
776 
777  if (mapBlockIndex.count(hash) == 0)
778  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
779 
780  CBlockIndex* pblockindex = mapBlockIndex[hash];
781 
782  if (!fVerbose)
783  {
785  ssBlock << pblockindex->GetBlockHeader();
786  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
787  return strHex;
788  }
789 
790  return blockheaderToJSON(pblockindex);
791 }
792 
794 {
795  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
796  throw std::runtime_error(
797  "getblockheaders \"hash\" ( count verbose )\n"
798  "\nReturns an array of items with information about <count> blockheaders starting from <hash>.\n"
799  "\nIf verbose is false, each item is a string that is serialized, hex-encoded data for a single blockheader.\n"
800  "If verbose is true, each item is an Object with information about a single blockheader.\n"
801  "\nArguments:\n"
802  "1. \"hash\" (string, required) The block hash\n"
803  "2. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n"
804  "3. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
805  "\nResult (for verbose = true):\n"
806  "[ {\n"
807  " \"hash\" : \"hash\", (string) The block hash\n"
808  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
809  " \"height\" : n, (numeric) The block height or index\n"
810  " \"version\" : n, (numeric) The block version\n"
811  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
812  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
813  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
814  " \"nonce\" : n, (numeric) The nonce\n"
815  " \"bits\" : \"1d00ffff\", (string) The bits\n"
816  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
817  " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
818  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
819  " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
820  "}, {\n"
821  " ...\n"
822  " },\n"
823  "...\n"
824  "]\n"
825  "\nResult (for verbose=false):\n"
826  "[\n"
827  " \"data\", (string) A string that is serialized, hex-encoded data for block header.\n"
828  " ...\n"
829  "]\n"
830  "\nExamples:\n"
831  + HelpExampleCli("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
832  + HelpExampleRpc("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
833  );
834 
835  LOCK(cs_main);
836 
837  std::string strHash = request.params[0].get_str();
838  uint256 hash(uint256S(strHash));
839 
840  if (mapBlockIndex.count(hash) == 0)
841  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
842 
843  int nCount = MAX_HEADERS_RESULTS;
844  if (!request.params[1].isNull())
845  nCount = request.params[1].get_int();
846 
847  if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS)
848  throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range");
849 
850  bool fVerbose = true;
851  if (!request.params[2].isNull())
852  fVerbose = request.params[2].get_bool();
853 
854  CBlockIndex* pblockindex = mapBlockIndex[hash];
855 
856  UniValue arrHeaders(UniValue::VARR);
857 
858  if (!fVerbose)
859  {
860  for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
861  {
863  ssBlock << pblockindex->GetBlockHeader();
864  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
865  arrHeaders.push_back(strHex);
866  if (--nCount <= 0)
867  break;
868  }
869  return arrHeaders;
870  }
871 
872  for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
873  {
874  arrHeaders.push_back(blockheaderToJSON(pblockindex));
875  if (--nCount <= 0)
876  break;
877  }
878 
879  return arrHeaders;
880 }
881 
882 static CBlock GetBlockChecked(const CBlockIndex* pblockindex)
883 {
884  CBlock block;
885  if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) {
886  throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
887  }
888 
889  if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
890  // Block not found on disk. This could be because we have the block
891  // header in our index but don't have the block (for example if a
892  // non-whitelisted node sends us an unrequested long chain of valid
893  // blocks, we add the headers to our index, but don't accept the
894  // block).
895  throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
896  }
897 
898  return block;
899 }
900 
901 
903 {
904  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
905  throw std::runtime_error(
906  "getmerkleblocks \"filter\" \"hash\" ( count )\n"
907  "\nReturns an array of hex-encoded merkleblocks for <count> blocks starting from <hash> which match <filter>.\n"
908  "\nArguments:\n"
909  "1. \"filter\" (string, required) The hex encoded bloom filter\n"
910  "2. \"hash\" (string, required) The block hash\n"
911  "3. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n"
912  "\nResult:\n"
913  "[\n"
914  " \"data\", (string) A string that is serialized, hex-encoded data for a merkleblock.\n"
915  " ...\n"
916  "]\n"
917  "\nExamples:\n"
918  + HelpExampleCli("getmerkleblocks", "\"2303028005802040100040000008008400048141010000f8400420800080025004000004130000000000000001\" \"00000000007e1432d2af52e8463278bf556b55cf5049262f25634557e2e91202\" 2000")
919  + HelpExampleRpc("getmerkleblocks", "\"2303028005802040100040000008008400048141010000f8400420800080025004000004130000000000000001\" \"00000000007e1432d2af52e8463278bf556b55cf5049262f25634557e2e91202\" 2000")
920  );
921 
922  LOCK(cs_main);
923 
924  CBloomFilter filter;
925  std::string strFilter = request.params[0].get_str();
926  CDataStream ssBloomFilter(ParseHex(strFilter), SER_NETWORK, PROTOCOL_VERSION);
927  ssBloomFilter >> filter;
928  if (!filter.IsWithinSizeConstraints()) {
929  throw JSONRPCError(RPC_INVALID_PARAMETER, "Filter is not within size constraints");
930  }
931  filter.UpdateEmptyFull();
932 
933  std::string strHash = request.params[1].get_str();
934  uint256 hash(uint256S(strHash));
935 
936  if (mapBlockIndex.count(hash) == 0) {
937  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
938  }
939 
940  int nCount = MAX_HEADERS_RESULTS;
941  if (!request.params[2].isNull())
942  nCount = request.params[2].get_int();
943 
944  if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS) {
945  throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range");
946  }
947 
948  CBlockIndex* pblockindex = mapBlockIndex[hash];
949  CBlock block = GetBlockChecked(pblockindex);
950 
951  UniValue arrMerkleBlocks(UniValue::VARR);
952 
953  for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
954  {
955  if (--nCount < 0) {
956  break;
957  }
958 
959  if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
960  // this shouldn't happen, we already checked pruning case earlier
961  throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
962  }
963 
964  CMerkleBlock merkleblock(block, filter);
965  if (merkleblock.vMatchedTxn.empty()) {
966  // ignore blocks that do not match the filter
967  continue;
968  }
969 
970  CDataStream ssMerkleBlock(SER_NETWORK, PROTOCOL_VERSION);
971  ssMerkleBlock << merkleblock;
972  std::string strHex = HexStr(ssMerkleBlock);
973  arrMerkleBlocks.push_back(strHex);
974  }
975  return arrMerkleBlocks;
976 }
977 
979 {
980  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
981  throw std::runtime_error(
982  "getblock \"blockhash\" ( verbosity ) \n"
983  "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
984  "If verbosity is 1, returns an Object with information about block <hash>.\n"
985  "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
986  "\nArguments:\n"
987  "1. \"blockhash\" (string, required) The block hash\n"
988  "2. verbosity (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n"
989  "\nResult (for verbosity = 0):\n"
990  "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
991  "\nResult (for verbose = 1):\n"
992  "{\n"
993  " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
994  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
995  " \"size\" : n, (numeric) The block size\n"
996  " \"height\" : n, (numeric) The block height or index\n"
997  " \"version\" : n, (numeric) The block version\n"
998  " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
999  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
1000  " \"tx\" : [ (array of string) The transaction ids\n"
1001  " \"transactionid\" (string) The transaction id\n"
1002  " ,...\n"
1003  " ],\n"
1004  " \"cbTx\" : { (json object) The coinbase special transaction \n"
1005  " \"version\" (numeric) The coinbase special transaction version\n"
1006  " \"height\" (numeric) The block height\n"
1007  " \"merkleRootMNList\" : \"xxxx\", (string) The merkle root of the masternode list\n"
1008  " \"merkleRootQuorums\" : \"xxxx\", (string) The merkle root of the quorum list\n"
1009  " },\n"
1010  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
1011  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
1012  " \"nonce\" : n, (numeric) The nonce\n"
1013  " \"bits\" : \"1d00ffff\", (string) The bits\n"
1014  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
1015  " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
1016  " \"nTx\" : n, (numeric) The number of transactions in the block.\n"
1017  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
1018  " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
1019  "}\n"
1020  "\nResult (for verbosity = 2):\n"
1021  "{\n"
1022  " ..., Same output as verbosity = 1.\n"
1023  " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
1024  " ,...\n"
1025  " ],\n"
1026  " ,... Same output as verbosity = 1.\n"
1027  "}\n"
1028  "\nExamples:\n"
1029  + HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
1030  + HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
1031  );
1032 
1033  LOCK(cs_main);
1034 
1035  std::string strHash = request.params[0].get_str();
1036  uint256 hash(uint256S(strHash));
1037 
1038  int verbosity = 1;
1039  if (!request.params[1].isNull()) {
1040  if(request.params[1].isNum())
1041  verbosity = request.params[1].get_int();
1042  else
1043  verbosity = request.params[1].get_bool() ? 1 : 0;
1044  }
1045 
1046  if (mapBlockIndex.count(hash) == 0)
1047  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1048 
1049  CBlockIndex* pblockindex = mapBlockIndex[hash];
1050  const CBlock block = GetBlockChecked(pblockindex);
1051 
1052  if (verbosity <= 0)
1053  {
1055  ssBlock << block;
1056  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
1057  return strHex;
1058  }
1059 
1060  return blockToJSON(block, pblockindex, verbosity >= 2);
1061 }
1062 
1064 {
1065  int nHeight;
1067  uint64_t nTransactions;
1069  uint64_t nBogoSize;
1071  uint64_t nDiskSize;
1073 
1075 };
1076 
1077 static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
1078 {
1079  assert(!outputs.empty());
1080  ss << hash;
1081  ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
1082  stats.nTransactions++;
1083  for (const auto output : outputs) {
1084  ss << VARINT(output.first + 1);
1085  ss << output.second.out.scriptPubKey;
1086  ss << VARINT(output.second.out.nValue);
1087  stats.nTransactionOutputs++;
1088  stats.nTotalAmount += output.second.out.nValue;
1089  stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ +
1090  2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */;
1091  }
1092  ss << VARINT(0);
1093 }
1094 
1096 static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
1097 {
1098  std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
1099  assert(pcursor);
1100 
1102  stats.hashBlock = pcursor->GetBestBlock();
1103  {
1104  LOCK(cs_main);
1105  stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
1106  }
1107  ss << stats.hashBlock;
1108  uint256 prevkey;
1109  std::map<uint32_t, Coin> outputs;
1110  while (pcursor->Valid()) {
1111  boost::this_thread::interruption_point();
1112  COutPoint key;
1113  Coin coin;
1114  if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
1115  if (!outputs.empty() && key.hash != prevkey) {
1116  ApplyStats(stats, ss, prevkey, outputs);
1117  outputs.clear();
1118  }
1119  prevkey = key.hash;
1120  outputs[key.n] = std::move(coin);
1121  } else {
1122  return error("%s: unable to read value", __func__);
1123  }
1124  pcursor->Next();
1125  }
1126  if (!outputs.empty()) {
1127  ApplyStats(stats, ss, prevkey, outputs);
1128  }
1129  stats.hashSerialized = ss.GetHash();
1130  stats.nDiskSize = view->EstimateSize();
1131  return true;
1132 }
1133 
1135 {
1136  if (request.fHelp || request.params.size() != 1)
1137  throw std::runtime_error(
1138  "pruneblockchain\n"
1139  "\nArguments:\n"
1140  "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n"
1141  " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n"
1142  "\nResult:\n"
1143  "n (numeric) Height of the last block pruned.\n"
1144  "\nExamples:\n"
1145  + HelpExampleCli("pruneblockchain", "1000")
1146  + HelpExampleRpc("pruneblockchain", "1000"));
1147 
1148  if (!fPruneMode)
1149  throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
1150 
1151  LOCK(cs_main);
1152 
1153  int heightParam = request.params[0].get_int();
1154  if (heightParam < 0)
1155  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
1156 
1157  // Height value more than a billion is too high to be a block height, and
1158  // too low to be a block time (corresponds to timestamp from Sep 2001).
1159  if (heightParam > 1000000000) {
1160  // Add a 2 hour buffer to include blocks which might have had old timestamps
1162  if (!pindex) {
1163  throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
1164  }
1165  heightParam = pindex->nHeight;
1166  }
1167 
1168  unsigned int height = (unsigned int) heightParam;
1169  unsigned int chainHeight = (unsigned int) chainActive.Height();
1170  if (chainHeight < Params().PruneAfterHeight())
1171  throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
1172  else if (height > chainHeight)
1173  throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
1174  else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
1175  LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.");
1176  height = chainHeight - MIN_BLOCKS_TO_KEEP;
1177  }
1178 
1179  PruneBlockFilesManual(height);
1180  return uint64_t(height);
1181 }
1182 
1184 {
1185  if (request.fHelp || request.params.size() != 0)
1186  throw std::runtime_error(
1187  "gettxoutsetinfo\n"
1188  "\nReturns statistics about the unspent transaction output set.\n"
1189  "Note this call may take some time.\n"
1190  "\nResult:\n"
1191  "{\n"
1192  " \"height\":n, (numeric) The current block height (index)\n"
1193  " \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n"
1194  " \"transactions\": n, (numeric) The number of transactions with unspent outputs\n"
1195  " \"txouts\": n, (numeric) The number of unspent transaction outputs\n"
1196  " \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n"
1197  " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n"
1198  " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
1199  " \"total_amount\": x.xxx (numeric) The total amount\n"
1200  "}\n"
1201  "\nExamples:\n"
1202  + HelpExampleCli("gettxoutsetinfo", "")
1203  + HelpExampleRpc("gettxoutsetinfo", "")
1204  );
1205 
1206  UniValue ret(UniValue::VOBJ);
1207 
1208  CCoinsStats stats;
1209  FlushStateToDisk();
1210  if (GetUTXOStats(pcoinsdbview.get(), stats)) {
1211  ret.push_back(Pair("height", (int64_t)stats.nHeight));
1212  ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
1213  ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
1214  ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
1215  ret.push_back(Pair("bogosize", (int64_t)stats.nBogoSize));
1216  ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex()));
1217  ret.push_back(Pair("disk_size", stats.nDiskSize));
1218  ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
1219  } else {
1220  throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1221  }
1222  return ret;
1223 }
1224 
1226 {
1227  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
1228  throw std::runtime_error(
1229  "gettxout \"txid\" n ( include_mempool )\n"
1230  "\nReturns details about an unspent transaction output.\n"
1231  "\nArguments:\n"
1232  "1. \"txid\" (string, required) The transaction id\n"
1233  "2. \"n\" (numeric, required) vout number\n"
1234  "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true."
1235  " Note that an unspent output that is spent in the mempool won't appear.\n"
1236  "\nResult:\n"
1237  "{\n"
1238  " \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n"
1239  " \"confirmations\" : n, (numeric) The number of confirmations\n"
1240  " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
1241  " \"scriptPubKey\" : { (json object)\n"
1242  " \"asm\" : \"code\", (string) \n"
1243  " \"hex\" : \"hex\", (string) \n"
1244  " \"reqSigs\" : n, (numeric) Number of required signatures\n"
1245  " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
1246  " \"addresses\" : [ (array of string) array of dash addresses\n"
1247  " \"address\" (string) dash address\n"
1248  " ,...\n"
1249  " ]\n"
1250  " },\n"
1251  " \"coinbase\" : true|false (boolean) Coinbase or not\n"
1252  "}\n"
1253 
1254  "\nExamples:\n"
1255  "\nGet unspent transactions\n"
1256  + HelpExampleCli("listunspent", "") +
1257  "\nView the details\n"
1258  + HelpExampleCli("gettxout", "\"txid\" 1") +
1259  "\nAs a json rpc call\n"
1260  + HelpExampleRpc("gettxout", "\"txid\", 1")
1261  );
1262 
1263  LOCK(cs_main);
1264 
1265  UniValue ret(UniValue::VOBJ);
1266 
1267  std::string strHash = request.params[0].get_str();
1268  uint256 hash(uint256S(strHash));
1269  int n = request.params[1].get_int();
1270  COutPoint out(hash, n);
1271  bool fMempool = true;
1272  if (!request.params[2].isNull())
1273  fMempool = request.params[2].get_bool();
1274 
1275  Coin coin;
1276  if (fMempool) {
1277  LOCK(mempool.cs);
1278  CCoinsViewMemPool view(pcoinsTip.get(), mempool);
1279  if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
1280  return NullUniValue;
1281  }
1282  } else {
1283  if (!pcoinsTip->GetCoin(out, coin)) {
1284  return NullUniValue;
1285  }
1286  }
1287 
1288  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
1289  CBlockIndex *pindex = it->second;
1290  ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
1291  if (coin.nHeight == MEMPOOL_HEIGHT) {
1292  ret.push_back(Pair("confirmations", 0));
1293  } else {
1294  ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)));
1295  }
1296  ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
1298  ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
1299  ret.push_back(Pair("scriptPubKey", o));
1300  ret.push_back(Pair("coinbase", (bool)coin.fCoinBase));
1301 
1302  return ret;
1303 }
1304 
1306 {
1307  int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
1308  int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
1309  if (request.fHelp || request.params.size() > 2)
1310  throw std::runtime_error(
1311  "verifychain ( checklevel nblocks )\n"
1312  "\nVerifies blockchain database.\n"
1313  "\nArguments:\n"
1314  "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
1315  "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
1316  "\nResult:\n"
1317  "true|false (boolean) Verified or not\n"
1318  "\nExamples:\n"
1319  + HelpExampleCli("verifychain", "")
1320  + HelpExampleRpc("verifychain", "")
1321  );
1322 
1323  LOCK(cs_main);
1324 
1325  if (!request.params[0].isNull())
1326  nCheckLevel = request.params[0].get_int();
1327  if (!request.params[1].isNull())
1328  nCheckDepth = request.params[1].get_int();
1329 
1330  return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth);
1331 }
1332 
1334 static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
1335 {
1337  bool activated = false;
1338  switch(version)
1339  {
1340  case 2:
1341  activated = pindex->nHeight >= consensusParams.BIP34Height;
1342  break;
1343  case 3:
1344  activated = pindex->nHeight >= consensusParams.BIP66Height;
1345  break;
1346  case 4:
1347  activated = pindex->nHeight >= consensusParams.BIP65Height;
1348  break;
1349  }
1350  rv.push_back(Pair("status", activated));
1351  return rv;
1352 }
1353 
1354 static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
1355 {
1357  rv.push_back(Pair("id", name));
1358  rv.push_back(Pair("version", version));
1359  rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams)));
1360  return rv;
1361 }
1362 
1364 {
1366  const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
1367  switch (thresholdState) {
1368  case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
1369  case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
1370  case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
1371  case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
1372  case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
1373  }
1374  if (THRESHOLD_STARTED == thresholdState)
1375  {
1376  rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
1377  }
1378  rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
1379  rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
1380  rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id)));
1381  if (THRESHOLD_STARTED == thresholdState)
1382  {
1383  UniValue statsUV(UniValue::VOBJ);
1384  BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
1385  statsUV.push_back(Pair("period", statsStruct.period));
1386  statsUV.push_back(Pair("threshold", statsStruct.threshold));
1387  statsUV.push_back(Pair("elapsed", statsStruct.elapsed));
1388  statsUV.push_back(Pair("count", statsStruct.count));
1389  statsUV.push_back(Pair("possible", statsStruct.possible));
1390  rv.push_back(Pair("statistics", statsUV));
1391  }
1392  return rv;
1393 }
1394 
1395 void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
1396 {
1397  // Deployments with timeout value of 0 are hidden.
1398  // A timeout value of 0 guarantees a softfork will never be activated.
1399  // This is used when softfork codes are merged without specifying the deployment schedule.
1400  if (consensusParams.vDeployments[id].nTimeout > 0)
1401  bip9_softforks.push_back(Pair(VersionBitsDeploymentInfo[id].name, BIP9SoftForkDesc(consensusParams, id)));
1402 }
1403 
1405 {
1406  if (request.fHelp || request.params.size() != 0)
1407  throw std::runtime_error(
1408  "getblockchaininfo\n"
1409  "Returns an object containing various state info regarding blockchain processing.\n"
1410  "\nResult:\n"
1411  "{\n"
1412  " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
1413  " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
1414  " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
1415  " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
1416  " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
1417  " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
1418  " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
1419  " \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n"
1420  " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
1421  " \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n"
1422  " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
1423  " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n"
1424  " \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n"
1425  " \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n"
1426  " \"softforks\": [ (array) status of softforks in progress\n"
1427  " {\n"
1428  " \"id\": \"xxxx\", (string) name of softfork\n"
1429  " \"version\": xx, (numeric) block version\n"
1430  " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
1431  " \"status\": xx, (boolean) true if threshold reached\n"
1432  " },\n"
1433  " }, ...\n"
1434  " ],\n"
1435  " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
1436  " \"xxxx\" : { (string) name of the softfork\n"
1437  " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
1438  " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
1439  " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
1440  " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
1441  " \"since\": xx, (numeric) height of the first block to which the status applies\n"
1442  " \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n"
1443  " \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n"
1444  " \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n"
1445  " \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n"
1446  " \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n"
1447  " \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n"
1448  " }\n"
1449  " }\n"
1450  " }\n"
1451  " \"warnings\" : \"...\", (string) any network and blockchain warnings.\n"
1452  "}\n"
1453  "\nExamples:\n"
1454  + HelpExampleCli("getblockchaininfo", "")
1455  + HelpExampleRpc("getblockchaininfo", "")
1456  );
1457 
1458  LOCK(cs_main);
1459 
1460  UniValue obj(UniValue::VOBJ);
1461  obj.push_back(Pair("chain", Params().NetworkIDString()));
1462  obj.push_back(Pair("blocks", (int)chainActive.Height()));
1463  obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
1464  obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
1465  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
1466  obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
1467  obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip())));
1468  obj.push_back(Pair("initialblockdownload", IsInitialBlockDownload()));
1469  obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
1470  obj.push_back(Pair("size_on_disk", CalculateCurrentUsage()));
1471  obj.push_back(Pair("pruned", fPruneMode));
1472  if (fPruneMode) {
1473  CBlockIndex* block = chainActive.Tip();
1474  assert(block);
1475  while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
1476  block = block->pprev;
1477  }
1478 
1479  obj.push_back(Pair("pruneheight", block->nHeight));
1480 
1481  // if 0, execution bypasses the whole if block.
1482  bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1);
1483  obj.push_back(Pair("automatic_pruning", automatic_pruning));
1484  if (automatic_pruning) {
1485  obj.push_back(Pair("prune_target_size", nPruneTarget));
1486  }
1487  }
1488 
1489  const Consensus::Params& consensusParams = Params().GetConsensus();
1490  CBlockIndex* tip = chainActive.Tip();
1491  UniValue softforks(UniValue::VARR);
1492  UniValue bip9_softforks(UniValue::VOBJ);
1493  // sorted by activation block
1494  softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
1495  softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
1496  softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
1498  BIP9SoftForkDescPushBack(bip9_softforks, consensusParams, static_cast<Consensus::DeploymentPos>(pos));
1499  }
1500  obj.push_back(Pair("softforks", softforks));
1501  obj.push_back(Pair("bip9_softforks", bip9_softforks));
1502 
1503  obj.push_back(Pair("warnings", GetWarnings("statusbar")));
1504  return obj;
1505 }
1506 
1509 {
1510  bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
1511  {
1512  /* Make sure that unequal blocks with the same height do not compare
1513  equal. Use the pointers themselves to make a distinction. */
1514 
1515  if (a->nHeight != b->nHeight)
1516  return (a->nHeight > b->nHeight);
1517 
1518  return a < b;
1519  }
1520 };
1521 
1523 {
1524  if (request.fHelp || request.params.size() > 2)
1525  throw std::runtime_error(
1526  "getchaintips ( count branchlen )\n"
1527  "Return information about all known tips in the block tree,"
1528  " including the main chain as well as orphaned branches.\n"
1529  "\nArguments:\n"
1530  "1. count (numeric, optional) only show this much of latest tips\n"
1531  "2. branchlen (numeric, optional) only show tips that have equal or greater length of branch\n"
1532  "\nResult:\n"
1533  "[\n"
1534  " {\n"
1535  " \"height\": xxxx, (numeric) height of the chain tip\n"
1536  " \"hash\": \"xxxx\", (string) block hash of the tip\n"
1537  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
1538  " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
1539  " \"branchlen\": 0 (numeric) zero for main chain\n"
1540  " \"forkpoint\": \"xxxx\", (string) same as \"hash\" for the main chain\n"
1541  " \"status\": \"active\" (string) \"active\" for the main chain\n"
1542  " },\n"
1543  " {\n"
1544  " \"height\": xxxx,\n"
1545  " \"hash\": \"xxxx\",\n"
1546  " \"difficulty\" : x.xxx,\n"
1547  " \"chainwork\" : \"0000...1f3\"\n"
1548  " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
1549  " \"forkpoint\": \"xxxx\", (string) block hash of the last common block between this tip and the main chain\n"
1550  " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
1551  " }\n"
1552  "]\n"
1553  "Possible values for status:\n"
1554  "1. \"invalid\" This branch contains at least one invalid block\n"
1555  "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1556  "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1557  "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1558  "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
1559  "\nExamples:\n"
1560  + HelpExampleCli("getchaintips", "")
1561  + HelpExampleRpc("getchaintips", "")
1562  );
1563 
1564  LOCK(cs_main);
1565 
1566  /*
1567  * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
1568  * Algorithm:
1569  * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
1570  * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
1571  * - add chainActive.Tip()
1572  */
1573  std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1574  std::set<const CBlockIndex*> setOrphans;
1575  std::set<const CBlockIndex*> setPrevs;
1576 
1577  for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
1578  {
1579  if (!chainActive.Contains(item.second)) {
1580  setOrphans.insert(item.second);
1581  setPrevs.insert(item.second->pprev);
1582  }
1583  }
1584 
1585  for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
1586  {
1587  if (setPrevs.erase(*it) == 0) {
1588  setTips.insert(*it);
1589  }
1590  }
1591 
1592  // Always report the currently active tip.
1593  setTips.insert(chainActive.Tip());
1594 
1595  int nBranchMin = -1;
1596  int nCountMax = INT_MAX;
1597 
1598  if(!request.params[0].isNull())
1599  nCountMax = request.params[0].get_int();
1600 
1601  if(!request.params[1].isNull())
1602  nBranchMin = request.params[1].get_int();
1603 
1604  /* Construct the output array. */
1605  UniValue res(UniValue::VARR);
1606  for (const CBlockIndex* block : setTips)
1607  {
1608  const CBlockIndex* pindexFork = chainActive.FindFork(block);
1609  const int branchLen = block->nHeight - pindexFork->nHeight;
1610  if(branchLen < nBranchMin) continue;
1611 
1612  if(nCountMax-- < 1) break;
1613 
1614  UniValue obj(UniValue::VOBJ);
1615  obj.push_back(Pair("height", block->nHeight));
1616  obj.push_back(Pair("hash", block->phashBlock->GetHex()));
1617  obj.push_back(Pair("difficulty", GetDifficulty(block)));
1618  obj.push_back(Pair("chainwork", block->nChainWork.GetHex()));
1619  obj.push_back(Pair("branchlen", branchLen));
1620  obj.push_back(Pair("forkpoint", pindexFork->phashBlock->GetHex()));
1621 
1622  std::string status;
1623  if (chainActive.Contains(block)) {
1624  // This block is part of the currently active chain.
1625  status = "active";
1626  } else if (block->nStatus & BLOCK_FAILED_MASK) {
1627  // This block or one of its ancestors is invalid.
1628  status = "invalid";
1629  } else if (block->nChainTx == 0) {
1630  // This block cannot be connected because full block data for it or one of its parents is missing.
1631  status = "headers-only";
1632  } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
1633  // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
1634  status = "valid-fork";
1635  } else if (block->IsValid(BLOCK_VALID_TREE)) {
1636  // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
1637  status = "valid-headers";
1638  } else {
1639  // No clue.
1640  status = "unknown";
1641  }
1642  obj.push_back(Pair("status", status));
1643 
1644  res.push_back(obj);
1645  }
1646 
1647  return res;
1648 }
1649 
1651 {
1652  UniValue ret(UniValue::VOBJ);
1653  ret.push_back(Pair("size", (int64_t) mempool.size()));
1654  ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
1655  ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
1656  size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1657  ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
1658  ret.push_back(Pair("mempoolminfee", ValueFromAmount(std::max(mempool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK())));
1659  ret.push_back(Pair("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
1660  ret.push_back(Pair("instantsendlocks", (int64_t)llmq::quorumInstantSendManager->GetInstantSendLockCount()));
1661 
1662  return ret;
1663 }
1664 
1666 {
1667  if (request.fHelp || request.params.size() != 0)
1668  throw std::runtime_error(
1669  "getmempoolinfo\n"
1670  "\nReturns details on the active state of the TX memory pool.\n"
1671  "\nResult:\n"
1672  "{\n"
1673  " \"size\": xxxxx, (numeric) Current tx count\n"
1674  " \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
1675  " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
1676  " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
1677  " \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n"
1678  " \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n"
1679  " \"instantsendlocks\": xxxxx, (numeric) Number of unconfirmed instant send locks\n"
1680  "}\n"
1681  "\nExamples:\n"
1682  + HelpExampleCli("getmempoolinfo", "")
1683  + HelpExampleRpc("getmempoolinfo", "")
1684  );
1685 
1686  return mempoolInfoToJSON();
1687 }
1688 
1690 {
1691  if (request.fHelp || request.params.size() != 1)
1692  throw std::runtime_error(
1693  "preciousblock \"blockhash\"\n"
1694  "\nTreats a block as if it were received before others with the same work.\n"
1695  "\nA later preciousblock call can override the effect of an earlier one.\n"
1696  "\nThe effects of preciousblock are not retained across restarts.\n"
1697  "\nArguments:\n"
1698  "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n"
1699  "\nResult:\n"
1700  "\nExamples:\n"
1701  + HelpExampleCli("preciousblock", "\"blockhash\"")
1702  + HelpExampleRpc("preciousblock", "\"blockhash\"")
1703  );
1704 
1705  std::string strHash = request.params[0].get_str();
1706  uint256 hash(uint256S(strHash));
1707  CBlockIndex* pblockindex;
1708 
1709  {
1710  LOCK(cs_main);
1711  if (mapBlockIndex.count(hash) == 0)
1712  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1713 
1714  pblockindex = mapBlockIndex[hash];
1715  }
1716 
1717  CValidationState state;
1718  PreciousBlock(state, Params(), pblockindex);
1719 
1720  if (!state.IsValid()) {
1722  }
1723 
1724  return NullUniValue;
1725 }
1726 
1728 {
1729  if (request.fHelp || request.params.size() != 1)
1730  throw std::runtime_error(
1731  "invalidateblock \"blockhash\"\n"
1732  "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
1733  "\nArguments:\n"
1734  "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n"
1735  "\nResult:\n"
1736  "\nExamples:\n"
1737  + HelpExampleCli("invalidateblock", "\"blockhash\"")
1738  + HelpExampleRpc("invalidateblock", "\"blockhash\"")
1739  );
1740 
1741  std::string strHash = request.params[0].get_str();
1742  uint256 hash(uint256S(strHash));
1743  CValidationState state;
1744 
1745  {
1746  LOCK(cs_main);
1747  if (mapBlockIndex.count(hash) == 0)
1748  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1749 
1750  CBlockIndex* pblockindex = mapBlockIndex[hash];
1751  InvalidateBlock(state, Params(), pblockindex);
1752  }
1753 
1754  if (state.IsValid()) {
1755  ActivateBestChain(state, Params());
1756  }
1757 
1758  if (!state.IsValid()) {
1760  }
1761 
1762  return NullUniValue;
1763 }
1764 
1766 {
1767  if (request.fHelp || request.params.size() != 1)
1768  throw std::runtime_error(
1769  "reconsiderblock \"blockhash\"\n"
1770  "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
1771  "This can be used to undo the effects of invalidateblock.\n"
1772  "\nArguments:\n"
1773  "1. \"blockhash\" (string, required) the hash of the block to reconsider\n"
1774  "\nResult:\n"
1775  "\nExamples:\n"
1776  + HelpExampleCli("reconsiderblock", "\"blockhash\"")
1777  + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
1778  );
1779 
1780  std::string strHash = request.params[0].get_str();
1781  uint256 hash(uint256S(strHash));
1782 
1783  {
1784  LOCK(cs_main);
1785  if (mapBlockIndex.count(hash) == 0)
1786  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1787 
1788  CBlockIndex* pblockindex = mapBlockIndex[hash];
1789  ResetBlockFailureFlags(pblockindex);
1790  }
1791 
1792  CValidationState state;
1793  ActivateBestChain(state, Params());
1794 
1795  if (!state.IsValid()) {
1797  }
1798 
1799  return NullUniValue;
1800 }
1801 
1803 {
1804  if (request.fHelp || request.params.size() > 2)
1805  throw std::runtime_error(
1806  "getchaintxstats ( nblocks blockhash )\n"
1807  "\nCompute statistics about the total number and rate of transactions in the chain.\n"
1808  "\nArguments:\n"
1809  "1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n"
1810  "2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n"
1811  "\nResult:\n"
1812  "{\n"
1813  " \"time\": xxxxx, (numeric) The timestamp for the final block in the window in UNIX format.\n"
1814  " \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n"
1815  " \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n"
1816  " \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n"
1817  " \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n"
1818  " \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n"
1819  "}\n"
1820  "\nExamples:\n"
1821  + HelpExampleCli("getchaintxstats", "")
1822  + HelpExampleRpc("getchaintxstats", "2016")
1823  );
1824 
1825  const CBlockIndex* pindex;
1826  int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month
1827 
1828  bool havehash = !request.params[1].isNull();
1829  uint256 hash;
1830  if (havehash) {
1831  hash = uint256S(request.params[1].get_str());
1832  }
1833 
1834  {
1835  LOCK(cs_main);
1836  if (havehash) {
1837  auto it = mapBlockIndex.find(hash);
1838  if (it == mapBlockIndex.end()) {
1839  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1840  }
1841  pindex = it->second;
1842  if (!chainActive.Contains(pindex)) {
1843  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
1844  }
1845  } else {
1846  pindex = chainActive.Tip();
1847  }
1848  }
1849 
1850  assert(pindex != nullptr);
1851 
1852  if (request.params[0].isNull()) {
1853  blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
1854  } else {
1855  blockcount = request.params[0].get_int();
1856 
1857  if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
1858  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
1859  }
1860  }
1861 
1862  const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount);
1863  int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast();
1864  int nTxDiff = pindex->nChainTx - pindexPast->nChainTx;
1865 
1866  UniValue ret(UniValue::VOBJ);
1867  ret.push_back(Pair("time", (int64_t)pindex->nTime));
1868  ret.push_back(Pair("txcount", (int64_t)pindex->nChainTx));
1869  ret.push_back(Pair("window_block_count", blockcount));
1870  if (blockcount > 0) {
1871  ret.push_back(Pair("window_tx_count", nTxDiff));
1872  ret.push_back(Pair("window_interval", nTimeDiff));
1873  if (nTimeDiff > 0) {
1874  ret.push_back(Pair("txrate", ((double)nTxDiff) / nTimeDiff));
1875  }
1876  }
1877 
1878  return ret;
1879 }
1880 
1881 template<typename T>
1882 static T CalculateTruncatedMedian(std::vector<T>& scores)
1883 {
1884  size_t size = scores.size();
1885  if (size == 0) {
1886  return 0;
1887  }
1888 
1889  std::sort(scores.begin(), scores.end());
1890  if (size % 2 == 0) {
1891  return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1892  } else {
1893  return scores[size / 2];
1894  }
1895 }
1896 
1897 template<typename T>
1898 static inline bool SetHasKeys(const std::set<T>& set) {return false;}
1899 template<typename T, typename Tk, typename... Args>
1900 static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args)
1901 {
1902  return (set.count(key) != 0) || SetHasKeys(set, args...);
1903 }
1904 
1905 // outpoint (needed for the utxo index) + nHeight + fCoinBase
1906 static constexpr size_t PER_UTXO_OVERHEAD = sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
1907 
1908 static UniValue getblockstats(const JSONRPCRequest& request)
1909 {
1910  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) {
1911  throw std::runtime_error(
1912  "getblockstats hash_or_height ( stats )\n"
1913  "\nCompute per block statistics for a given window. All amounts are in duffs.\n"
1914  "It won't work for some heights with pruning.\n"
1915  "It won't work without -txindex for utxo_size_inc, *fee or *feerate stats.\n"
1916  "\nArguments:\n"
1917  "1. \"hash_or_height\" (string or numeric, required) The block hash or height of the target block\n"
1918  "2. \"stats\" (array, optional) Values to plot, by default all values (see result below)\n"
1919  " [\n"
1920  " \"height\", (string, optional) Selected statistic\n"
1921  " \"time\", (string, optional) Selected statistic\n"
1922  " ,...\n"
1923  " ]\n"
1924  "\nResult:\n"
1925  "{ (json object)\n"
1926  " \"avgfee\": xxxxx, (numeric) Average fee in the block\n"
1927  " \"avgfeerate\": xxxxx, (numeric) Average feerate (in duffs per byte)\n"
1928  " \"avgtxsize\": xxxxx, (numeric) Average transaction size\n"
1929  " \"blockhash\": xxxxx, (string) The block hash (to check for potential reorgs)\n"
1930  " \"height\": xxxxx, (numeric) The height of the block\n"
1931  " \"ins\": xxxxx, (numeric) The number of inputs (excluding coinbase)\n"
1932  " \"maxfee\": xxxxx, (numeric) Maximum fee in the block\n"
1933  " \"maxfeerate\": xxxxx, (numeric) Maximum feerate (in duffs per byte)\n"
1934  " \"maxtxsize\": xxxxx, (numeric) Maximum transaction size\n"
1935  " \"medianfee\": xxxxx, (numeric) Truncated median fee in the block\n"
1936  " \"medianfeerate\": xxxxx, (numeric) Truncated median feerate (in duffs per byte)\n"
1937  " \"mediantime\": xxxxx, (numeric) The block median time past\n"
1938  " \"mediantxsize\": xxxxx, (numeric) Truncated median transaction size\n"
1939  " \"minfee\": xxxxx, (numeric) Minimum fee in the block\n"
1940  " \"minfeerate\": xxxxx, (numeric) Minimum feerate (in duffs per byte)\n"
1941  " \"mintxsize\": xxxxx, (numeric) Minimum transaction size\n"
1942  " \"outs\": xxxxx, (numeric) The number of outputs\n"
1943  " \"subsidy\": xxxxx, (numeric) The block subsidy\n"
1944  " \"time\": xxxxx, (numeric) The block time\n"
1945  " \"total_out\": xxxxx, (numeric) Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])\n"
1946  " \"total_size\": xxxxx, (numeric) Total size of all non-coinbase transactions\n"
1947  " \"totalfee\": xxxxx, (numeric) The fee total\n"
1948  " \"txs\": xxxxx, (numeric) The number of transactions (excluding coinbase)\n"
1949  " \"utxo_increase\": xxxxx, (numeric) The increase/decrease in the number of unspent outputs\n"
1950  " \"utxo_size_inc\": xxxxx, (numeric) The increase/decrease in size for the utxo index (not discounting op_return and similar)\n"
1951  "}\n"
1952  "\nExamples:\n"
1953  + HelpExampleCli("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'")
1954  + HelpExampleRpc("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'")
1955  );
1956  }
1957 
1958  LOCK(cs_main);
1959 
1960  CBlockIndex* pindex;
1961  if (request.params[0].isNum()) {
1962  const int height = request.params[0].get_int();
1963  const int current_tip = chainActive.Height();
1964  if (height < 0) {
1965  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
1966  }
1967  if (height > current_tip) {
1968  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip));
1969  }
1970 
1971  pindex = chainActive[height];
1972  } else {
1973  const uint256 hash = ParseHashV(request.params[0], "parameter 1");
1974  if (mapBlockIndex.count(hash) == 0)
1975  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1976  pindex = mapBlockIndex[hash];
1977  // pindex = LookupBlockIndex(hash);
1978  // if (!pindex) {
1979  // throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1980  // }
1981  if (!chainActive.Contains(pindex)) {
1982  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString()));
1983  }
1984  }
1985 
1986  assert(pindex != nullptr);
1987 
1988  std::set<std::string> stats;
1989  if (!request.params[1].isNull()) {
1990  const UniValue stats_univalue = request.params[1].get_array();
1991  for (unsigned int i = 0; i < stats_univalue.size(); i++) {
1992  const std::string stat = stats_univalue[i].get_str();
1993  stats.insert(stat);
1994  }
1995  }
1996 
1997  const CBlock block = GetBlockChecked(pindex);
1998 
1999  const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
2000  const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0;
2001  const bool do_medianfee = do_all || stats.count("medianfee") != 0;
2002  const bool do_medianfeerate = do_all || stats.count("medianfeerate") != 0;
2003  const bool loop_inputs = do_all || do_medianfee || do_medianfeerate ||
2004  SetHasKeys(stats, "utxo_size_inc", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate");
2005  const bool loop_outputs = do_all || loop_inputs || stats.count("total_out");
2006  const bool do_calculate_size = do_all || do_mediantxsize ||
2007  SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "avgfeerate", "medianfeerate", "minfeerate", "maxfeerate");
2008 
2009  CAmount maxfee = 0;
2010  CAmount maxfeerate = 0;
2011  CAmount minfee = MAX_MONEY;
2012  CAmount minfeerate = MAX_MONEY;
2013  CAmount total_out = 0;
2014  CAmount totalfee = 0;
2015  int64_t inputs = 0;
2016  int64_t maxtxsize = 0;
2017  int64_t mintxsize = MaxBlockSize(true);
2018  int64_t outputs = 0;
2019  int64_t total_size = 0;
2020  int64_t utxo_size_inc = 0;
2021  std::vector<CAmount> fee_array;
2022  std::vector<CAmount> feerate_array;
2023  std::vector<int64_t> txsize_array;
2024 
2025  for (const auto& tx : block.vtx) {
2026  outputs += tx->vout.size();
2027 
2028  CAmount tx_total_out = 0;
2029  if (loop_outputs) {
2030  for (const CTxOut& out : tx->vout) {
2031  tx_total_out += out.nValue;
2033  }
2034  }
2035 
2036  if (tx->IsCoinBase()) {
2037  continue;
2038  }
2039 
2040  inputs += tx->vin.size(); // Don't count coinbase's fake input
2041  total_out += tx_total_out; // Don't count coinbase reward
2042 
2043  int64_t tx_size = 0;
2044  if (do_calculate_size) {
2045 
2046  tx_size = tx->GetTotalSize();
2047  if (do_mediantxsize) {
2048  txsize_array.push_back(tx_size);
2049  }
2050  maxtxsize = std::max(maxtxsize, tx_size);
2051  mintxsize = std::min(mintxsize, tx_size);
2052  total_size += tx_size;
2053  }
2054 
2055  if (loop_inputs) {
2056 
2057  if (!fTxIndex) {
2058  throw JSONRPCError(RPC_INVALID_PARAMETER, "One or more of the selected stats requires -txindex enabled");
2059  }
2060  CAmount tx_total_in = 0;
2061  for (const CTxIn& in : tx->vin) {
2062  CTransactionRef tx_in;
2063  uint256 hashBlock;
2064  if (!GetTransaction(in.prevout.hash, tx_in, Params().GetConsensus(), hashBlock, false)) {
2065  throw JSONRPCError(RPC_INTERNAL_ERROR, std::string("Unexpected internal error (tx index seems corrupt)"));
2066  }
2067 
2068  CTxOut prevoutput = tx_in->vout[in.prevout.n];
2069 
2070  tx_total_in += prevoutput.nValue;
2071  utxo_size_inc -= GetSerializeSize(prevoutput, SER_NETWORK, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
2072  }
2073 
2074  CAmount txfee = tx_total_in - tx_total_out;
2075  assert(MoneyRange(txfee));
2076  if (do_medianfee) {
2077  fee_array.push_back(txfee);
2078  }
2079  maxfee = std::max(maxfee, txfee);
2080  minfee = std::min(minfee, txfee);
2081  totalfee += txfee;
2082 
2083  CAmount feerate = tx_size ? txfee / tx_size : 0;
2084  if (do_medianfeerate) {
2085  feerate_array.push_back(feerate);
2086  }
2087  maxfeerate = std::max(maxfeerate, feerate);
2088  minfeerate = std::min(minfeerate, feerate);
2089  }
2090  }
2091 
2092  UniValue ret_all(UniValue::VOBJ);
2093  ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
2094  ret_all.pushKV("avgfeerate", total_size ? totalfee / total_size : 0); // Unit: sat/byte
2095  ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
2096  ret_all.pushKV("blockhash", pindex->GetBlockHash().GetHex());
2097  ret_all.pushKV("height", (int64_t)pindex->nHeight);
2098  ret_all.pushKV("ins", inputs);
2099  ret_all.pushKV("maxfee", maxfee);
2100  ret_all.pushKV("maxfeerate", maxfeerate);
2101  ret_all.pushKV("maxtxsize", maxtxsize);
2102  ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
2103  ret_all.pushKV("medianfeerate", CalculateTruncatedMedian(feerate_array));
2104  ret_all.pushKV("mediantime", pindex->GetMedianTimePast());
2105  ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
2106  ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
2107  ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
2108  ret_all.pushKV("mintxsize", mintxsize == MaxBlockSize(true) ? 0 : mintxsize);
2109  ret_all.pushKV("outs", outputs);
2110  ret_all.pushKV("subsidy", pindex->pprev ? GetBlockSubsidy(pindex->pprev->nBits, pindex->pprev->nHeight, Params().GetConsensus()) : 50 * COIN);
2111  ret_all.pushKV("time", pindex->GetBlockTime());
2112  ret_all.pushKV("total_out", total_out);
2113  ret_all.pushKV("total_size", total_size);
2114  ret_all.pushKV("totalfee", totalfee);
2115  ret_all.pushKV("txs", (int64_t)block.vtx.size());
2116  ret_all.pushKV("utxo_increase", outputs - inputs);
2117  ret_all.pushKV("utxo_size_inc", utxo_size_inc);
2118 
2119  if (do_all) {
2120  return ret_all;
2121  }
2122 
2123  UniValue ret(UniValue::VOBJ);
2124  for (const std::string& stat : stats) {
2125  const UniValue& value = ret_all[stat];
2126  if (value.isNull()) {
2127  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic %s", stat));
2128  }
2129  ret.pushKV(stat, value);
2130  }
2131  return ret;
2132 }
2133 
2135 {
2136  if (request.fHelp || request.params.size() < 1 || request.params.size() > 5)
2137  throw std::runtime_error(
2138  "getspecialtxes \"blockhash\" ( type count skip verbosity ) \n"
2139  "Returns an array of special transactions found in the specified block\n"
2140  "\nIf verbosity is 0, returns tx hash for each transaction.\n"
2141  "If verbosity is 1, returns hex-encoded data for each transaction.\n"
2142  "If verbosity is 2, returns an Object with information for each transaction.\n"
2143  "\nArguments:\n"
2144  "1. \"blockhash\" (string, required) The block hash\n"
2145  "2. type (numeric, optional, default=-1) Filter special txes by type, -1 means all types\n"
2146  "3. count (numeric, optional, default=10) The number of transactions to return\n"
2147  "4. skip (numeric, optional, default=0) The number of transactions to skip\n"
2148  "5. verbosity (numeric, optional, default=0) 0 for hashes, 1 for hex-encoded data, and 2 for json object\n"
2149  "\nResult (for verbosity = 0):\n"
2150  "[\n"
2151  " \"txid\" : \"xxxx\", (string) The transaction id\n"
2152  "]\n"
2153  "\nResult (for verbosity = 1):\n"
2154  "[\n"
2155  " \"data\", (string) A string that is serialized, hex-encoded data for the transaction\n"
2156  "]\n"
2157  "\nResult (for verbosity = 2):\n"
2158  "[ (array of Objects) The transactions in the format of the getrawtransaction RPC.\n"
2159  " ...,\n"
2160  "]\n"
2161  "\nExamples:\n"
2162  + HelpExampleCli("getspecialtxes", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
2163  + HelpExampleRpc("getspecialtxes", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
2164  );
2165 
2166  LOCK(cs_main);
2167 
2168  std::string strHash = request.params[0].get_str();
2169  uint256 hash(uint256S(strHash));
2170 
2171  int nTxType = -1;
2172  if (!request.params[1].isNull()) {
2173  nTxType = request.params[1].get_int();
2174  }
2175 
2176  int nCount = 10;
2177  if (!request.params[2].isNull()) {
2178  nCount = request.params[2].get_int();
2179  if (nCount < 0)
2180  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
2181  }
2182 
2183  int nSkip = 0;
2184  if (!request.params[3].isNull()) {
2185  nSkip = request.params[3].get_int();
2186  if (nSkip < 0)
2187  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative skip");
2188  }
2189 
2190  int nVerbosity = 0;
2191  if (!request.params[4].isNull()) {
2192  nVerbosity = request.params[4].get_int();
2193  if (nVerbosity < 0 || nVerbosity > 2) {
2194  throw JSONRPCError(RPC_INVALID_PARAMETER, "Verbosity must be in range 0..2");
2195  }
2196  }
2197 
2198  if (mapBlockIndex.count(hash) == 0)
2199  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2200 
2201  CBlockIndex* pblockindex = mapBlockIndex[hash];
2202  const CBlock block = GetBlockChecked(pblockindex);
2203 
2204  int nTxNum = 0;
2205  UniValue result(UniValue::VARR);
2206  for(const auto& tx : block.vtx)
2207  {
2208  if (tx->nVersion != 3 || tx->nType == TRANSACTION_NORMAL // ensure it's in fact a special tx
2209  || (nTxType != -1 && tx->nType != nTxType)) { // ensure special tx type matches filter, if given
2210  continue;
2211  }
2212 
2213  nTxNum++;
2214  if (nTxNum <= nSkip) continue;
2215  if (nTxNum > nSkip + nCount) break;
2216 
2217  switch (nVerbosity)
2218  {
2219  case 0 : result.push_back(tx->GetHash().GetHex()); break;
2220  case 1 : result.push_back(EncodeHexTx(*tx)); break;
2221  case 2 :
2222  {
2223  UniValue objTx(UniValue::VOBJ);
2224  TxToJSON(*tx, uint256(), objTx);
2225  result.push_back(objTx);
2226  break;
2227  }
2228  default : throw JSONRPCError(RPC_INTERNAL_ERROR, "Unsupported verbosity");
2229  }
2230  }
2231 
2232  return result;
2233 }
2234 
2236 {
2237  if (request.fHelp || request.params.size() != 0) {
2238  throw std::runtime_error(
2239  "savemempool\n"
2240  "\nDumps the mempool to disk.\n"
2241  "\nExamples:\n"
2242  + HelpExampleCli("savemempool", "")
2243  + HelpExampleRpc("savemempool", "")
2244  );
2245  }
2246 
2247  if (!DumpMempool()) {
2248  throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
2249  }
2250 
2251  return NullUniValue;
2252 }
2253 
2254 static const CRPCCommand commands[] =
2255 { // category name actor (function) argNames
2256  // --------------------- ------------------------ ----------------------- ----------
2257  { "blockchain", "getblockchaininfo", &getblockchaininfo, {} },
2258  { "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} },
2259  { "blockchain", "getblockstats", &getblockstats, {"hash_or_height", "stats"} },
2260  { "blockchain", "getbestblockhash", &getbestblockhash, {} },
2261  { "blockchain", "getbestchainlock", &getbestchainlock, {} },
2262  { "blockchain", "getblockcount", &getblockcount, {} },
2263  { "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} },
2264  { "blockchain", "getblockhashes", &getblockhashes, {"high","low"} },
2265  { "blockchain", "getblockhash", &getblockhash, {"height"} },
2266  { "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} },
2267  { "blockchain", "getblockheaders", &getblockheaders, {"blockhash","count","verbose"} },
2268  { "blockchain", "getmerkleblocks", &getmerkleblocks, {"filter","blockhash","count"} },
2269  { "blockchain", "getchaintips", &getchaintips, {"count","branchlen"} },
2270  { "blockchain", "getdifficulty", &getdifficulty, {} },
2271  { "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} },
2272  { "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} },
2273  { "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} },
2274  { "blockchain", "getmempoolinfo", &getmempoolinfo, {} },
2275  { "blockchain", "getrawmempool", &getrawmempool, {"verbose"} },
2276  { "blockchain", "getspecialtxes", &getspecialtxes, {"blockhash", "type", "count", "skip", "verbosity"} },
2277  { "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} },
2278  { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} },
2279  { "blockchain", "pruneblockchain", &pruneblockchain, {"height"} },
2280  { "blockchain", "savemempool", &savemempool, {} },
2281  { "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} },
2282 
2283  { "blockchain", "preciousblock", &preciousblock, {"blockhash"} },
2284 
2285  /* Not shown in help */
2286  { "hidden", "invalidateblock", &invalidateblock, {"blockhash"} },
2287  { "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} },
2288  { "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} },
2289  { "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} },
2290  { "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} },
2291 };
2292 
2294 {
2295  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
2296  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
2297 }
UniValue getmerkleblocks(const JSONRPCRequest &request)
Definition: blockchain.cpp:902
uint32_t nNonce
Definition: block.h:29
CAmount GetModFeesWithAncestors() const
Definition: txmempool.h:131
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
bool GetTxPayload(const std::vector< unsigned char > &payload, T &obj)
Definition: specialtx.h:21
CAmount nValue
Definition: transaction.h:147
#define VARINT(obj)
Definition: serialize.h:375
CTxMemPool mempool
uint64_t nTransactionOutputs
uint64_t GetSizeWithAncestors() const
Definition: txmempool.h:130
static bool FlushStateToDisk(const CChainParams &chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
void ToJson(UniValue &obj) const
Definition: cbtx.h:44
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:230
bool DumpMempool(void)
Dump the mempool to disk.
UniValue getmempoolancestors(const JSONRPCRequest &request)
Definition: blockchain.cpp:513
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
Definition: validation.cpp:950
Dash RPC command dispatcher.
Definition: server.h:140
int64_t GetBlockTime() const
Definition: chain.h:297
UniValue getblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:978
uint256 hashBlock
CScript scriptPubKey
Definition: transaction.h:148
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
bool get_bool() const
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:390
A UTXO entry.
Definition: coins.h:29
Definition: block.h:72
UniValue getbestblockhash(const JSONRPCRequest &request)
Definition: blockchain.cpp:206
Definition: cbtx.h:16
size_t GetTxSize() const
Definition: txmempool.h:105
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:30
unsigned int MaxBlockSize(bool fDIP0001Active)
Definition: consensus.h:12
static CUpdatedBlock latestblock
Definition: blockchain.cpp:57
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
UniValue reconsiderblock(const JSONRPCRequest &request)
#define strprintf
Definition: tinyformat.h:1066
An in-memory indexed chain of blocks.
Definition: chain.h:442
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1389
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:229
bool isSpent(const COutPoint &outpoint)
Definition: txmempool.cpp:344
bool HasChainLock(int nHeight, const uint256 &blockHash)
UniValue preciousblock(const JSONRPCRequest &request)
BlockMap & mapBlockIndex
Definition: validation.cpp:215
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:1295
static const CAmount COIN
Definition: amount.h:14
UniValue mempoolInfoToJSON()
Mempool information to JSON.
Comparison function for sorting the getchaintips heads.
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be prun...
Definition: validation.h:207
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:134
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
CBlockHeader GetBlockHeader() const
Definition: chain.h:279
int Height() const
Return the maximal height in the chain.
Definition: chain.h:484
CCriticalSection cs_main
Definition: validation.cpp:213
bool IsValid() const
Definition: validation.h:61
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:46
CTxOut out
unspent transaction output
Definition: coins.h:33
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:25
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
CAmount GetModFeesWithDescendants() const
Definition: txmempool.h:125
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:8
static void ApplyStats(CCoinsStats &stats, CHashWriter &ss, const uint256 &hash, const std::map< uint32_t, Coin > &outputs)
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:36
sph_u32 high
Definition: keccak.c:370
uint64_t GetTotalTxSize() const
Definition: txmempool.h:666
UniValue blockheaderToJSON(const CBlockIndex *blockindex)
Block header to JSON.
Definition: blockchain.cpp:97
int BIP66Height
Block height at which BIP66 becomes active.
Definition: params.h:154
BIP9Stats VersionBitsTipStatistics(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the numerical statistics for the BIP9 state for a given deployment at the current tip...
uint64_t GetSizeWithDescendants() const
Definition: txmempool.h:124
double GetDifficulty(const CChain &chain, const CBlockIndex *blockindex)
Definition: blockchain.cpp:64
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:14
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:499
uint64_t nTransactions
const std::string & get_str() const
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:1180
uint64_t nDiskSize
bool isNum() const
Definition: univalue.h:83
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:583
const UniValue & get_array() const
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:103
uint32_t nTime
Definition: chain.h:212
ThresholdState
Definition: versionbits.h:20
UniValue verifychain(const JSONRPCRequest &request)
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
UniValue getblockcount(const JSONRPCRequest &request)
Definition: blockchain.cpp:189
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:237
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:345
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:353
UniValue waitfornewblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:262
uint64_t nBogoSize
int threshold
Definition: versionbits.h:44
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:204
UniValue getchaintips(const JSONRPCRequest &request)
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
UniValue getmempooldescendants(const JSONRPCRequest &request)
Definition: blockchain.cpp:577
uint256 hash
Definition: blockchain.cpp:51
const std::vector< CTxIn > vin
Definition: transaction.h:215
Invalid, missing or duplicate parameter.
Definition: protocol.h:53
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: server.cpp:121
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
Calculate statistics about the unspent transaction output set.
UniValue waitforblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:300
static UniValue getblockstats(const JSONRPCRequest &request)
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:69
void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
Definition: blockchain.cpp:420
indexed_transaction_set mapTx
Definition: txmempool.h:489
CInstantSendManager * quorumInstantSendManager
CAmount nTotalAmount
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:300
uint256 hashSerialized
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static T CalculateTruncatedMedian(std::vector< T > &scores)
uint256 GetBlockHash() const
Definition: chain.h:292
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0...
Definition: txmempool.h:38
std::string name
Definition: server.h:132
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:127
CChainLocksHandler * chainLocksHandler
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
UniValue pruneblockchain(const JSONRPCRequest &request)
UniValue waitforblockheight(const JSONRPCRequest &request)
Definition: blockchain.cpp:342
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry)
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:148
unsigned long size()
Definition: txmempool.h:660
uint256 hashMerkleRoot
Definition: block.h:26
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
uint32_t nNonce
Definition: chain.h:214
Abstract view on the open txout dataset.
Definition: coins.h:145
unsigned int GetHeight() const
Definition: txmempool.h:107
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:246
UniValue params
Definition: server.h:42
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:218
DeploymentPos
Definition: params.h:15
An input of a transaction.
Definition: transaction.h:70
int period
Definition: versionbits.h:43
#define LOCK(cs)
Definition: sync.h:178
const char * name
Definition: rest.cpp:36
const uint256 & GetHash() const
Definition: transaction.h:256
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:299
const CAmount & GetFee() const
Definition: txmempool.h:104
UniValue getmempoolinfo(const JSONRPCRequest &request)
static std::condition_variable cond_blockchange
Definition: blockchain.cpp:56
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:149
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:471
UniValue getspecialtxes(const JSONRPCRequest &request)
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
Definition: validation.h:92
uint256 uint256S(const char *str)
Definition: uint256.h:143
int64_t nStartTime
Start MedianTime for version bits miner confirmation.
Definition: params.h:35
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
Definition: chain.cpp:62
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:702
int64_t nPowTargetSpacing
Definition: params.h:176
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:476
UniValue getdifficulty(const JSONRPCRequest &request)
Definition: blockchain.cpp:384
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:426
std::string GetRejectReason() const
Definition: validation.h:81
uint32_t n
Definition: transaction.h:30
bool IsLocked(const uint256 &txHash)
UniValue getchaintxstats(const JSONRPCRequest &request)
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
UniValue gettxoutsetinfo(const JSONRPCRequest &request)
void BIP9SoftForkDescPushBack(UniValue &bip9_softforks, const Consensus::Params &consensusParams, Consensus::DeploymentPos id)
uint256 hashMerkleRoot
Definition: chain.h:211
UniValue getblockhash(const JSONRPCRequest &request)
Definition: blockchain.cpp:708
General application defined errors.
Definition: protocol.h:48
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:135
int VersionBitsTipStateSinceHeight(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
bool exists(uint256 hash) const
Definition: txmempool.h:672
An output of a transaction.
Definition: transaction.h:144
int get_int() const
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:154
std::string ToString() const
Definition: uint256.cpp:62
Invalid address or key.
Definition: protocol.h:51
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:578
UniValue getmempoolentry(const JSONRPCRequest &request)
Definition: blockchain.cpp:641
Parameters that influence chain consensus.
Definition: params.h:130
static std::pair< std::string, UniValue > Pair(const char *cKey, const char *cVal)
Definition: univalue.h:185
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
UniValue getblockhashes(const JSONRPCRequest &request)
Definition: blockchain.cpp:674
int64_t GetBlockTime() const
Definition: block.h:65
bool fTxIndex
Definition: validation.cpp:225
uint64_t GetCountWithDescendants() const
Definition: txmempool.h:123
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1470
UniValue gettxout(const JSONRPCRequest &request)
static UniValue SoftForkMajorityDesc(int version, CBlockIndex *pindex, const Consensus::Params &consensusParams)
Implementation of IsSuperMajority with better feedback.
bool isNull() const
Definition: univalue.h:78
int64_t GetMedianTimePast() const
Definition: chain.h:309
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:491
CCriticalSection cs
Definition: txmempool.h:488
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex *pindex, const Consensus::Params &consensusParams)
UniValue mempoolToJSON(bool fVerbose)
Mempool to JSON.
Definition: blockchain.cpp:453
int BIP65Height
Block height at which BIP65 becomes active.
Definition: params.h:152
Database error.
Definition: protocol.h:54
#define LogPrint(category,...)
Definition: util.h:214
uint256 GetHash()
Definition: hash.h:203
uint64_t GetCountWithAncestors() const
Definition: txmempool.h:129
bool fHelp
Definition: server.h:43
int32_t nVersion
block header
Definition: chain.h:210
Capture information about block/transaction validation.
Definition: validation.h:22
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Definition: params.h:37
256-bit opaque blob.
Definition: uint256.h:123
ArgsManager gArgs
Definition: util.cpp:108
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:130
std::vector< CTransactionRef > vtx
Definition: block.h:76
UniValue invalidateblock(const JSONRPCRequest &request)
const_iterator end() const
Definition: streams.h:192
#define ARRAYLEN(array)
const_iterator begin() const
Definition: streams.h:190
static bool SetHasKeys(const std::set< T > &set)
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
UniValue getrawmempool(const JSONRPCRequest &request)
Definition: blockchain.cpp:481
UniValue savemempool(const JSONRPCRequest &request)
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:140
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:177
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.
int64_t GetTime() const
Definition: txmempool.h:106
static std::mutex cs_blockchange
Definition: blockchain.cpp:55
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:211
const CTransaction & GetTx() const
Definition: txmempool.h:102
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:14
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
UniValue getblockchaininfo(const JSONRPCRequest &request)
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
int64_t GetModifiedFee() const
Definition: txmempool.h:109
UniValue getblockheader(const JSONRPCRequest &request)
Definition: blockchain.cpp:733
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:453
std::string GetHex() const
Definition: uint256.cpp:21
sph_u32 low
Definition: keccak.c:370
static constexpr size_t PER_UTXO_OVERHEAD
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, const CSpentIndexTxInfo *ptxSpentInfo=nullptr)
Definition: core_write.cpp:163
const UniValue NullUniValue
Definition: univalue.cpp:15
static int count
Definition: tests.c:45
int elapsed
Definition: versionbits.h:45
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:137
bool possible
Definition: versionbits.h:47
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:184
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:252
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
std::string GetHex() const
size_t size() const
Definition: univalue.h:69
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
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:54
std::string EntryDescriptionString()
Definition: blockchain.cpp:401
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:33
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:110
full block available in blk*.dat
Definition: chain.h:154
CAmount GetBlockSubsidy(int nPrevBits, int nPrevHeight, const Consensus::Params &consensusParams, bool fSuperblockPartOnly)
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
AssertLockHeld(g_cs_orphans)
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
UniValue blockToJSON(const CBlock &block, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
Definition: blockchain.cpp:130
COutPoint prevout
Definition: transaction.h:73
UniValue getblockheaders(const JSONRPCRequest &request)
Definition: blockchain.cpp:793
static UniValue BIP9SoftForkDesc(const Consensus::Params &consensusParams, Consensus::DeploymentPos id)
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:739
int32_t nVersion
Definition: block.h:24
bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector< uint256 > &hashes)
Definition: validation.cpp:897
static const int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:29
static CBlock GetBlockChecked(const CBlockIndex *pblockindex)
Definition: blockchain.cpp:882
uint32_t nBits
Definition: chain.h:213
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:41
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
static const CRPCCommand commands[]
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:212
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:171
uint32_t nBits
Definition: block.h:28
UniValue getbestchainlock(const JSONRPCRequest &request)
Definition: blockchain.cpp:223
std::vector< unsigned char > ParseHex(const char *psz)
uint256 hash
Definition: transaction.h:29
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:174
Released under the MIT license