Raven Core  3.0.0
P2P Digital Currency
blockchain.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven 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 "base58.h"
11 #include "chain.h"
12 #include "chainparams.h"
13 #include "checkpoints.h"
14 #include "coins.h"
15 #include "consensus/validation.h"
16 #include "validation.h"
17 #include "core_io.h"
18 #include "policy/feerate.h"
19 #include "policy/policy.h"
20 #include "primitives/transaction.h"
21 #include "rpc/server.h"
22 #include "script/script.h"
23 #include "script/script_error.h"
24 #include "script/sign.h"
25 #include "script/standard.h"
26 #include "streams.h"
27 #include "sync.h"
28 #include "txdb.h"
29 #include "txmempool.h"
30 #include "util.h"
31 #include "utilstrencodings.h"
32 #include "hash.h"
33 #include "warnings.h"
34 
35 #include <stdint.h>
36 
37 #include <univalue.h>
38 
39 #include <boost/thread/thread.hpp> // boost::thread::interrupt
40 
41 #include <mutex>
42 #include <condition_variable>
43 
45 {
47  int height;
48 };
49 
50 static std::mutex cs_blockchange;
51 static std::condition_variable cond_blockchange;
52 static CUpdatedBlock latestblock;
53 
54 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
55 
56 double GetDifficulty(const CBlockIndex* blockindex)
57 {
58  if (blockindex == nullptr)
59  {
60  if (chainActive.Tip() == nullptr)
61  return 1.0;
62  else
63  blockindex = chainActive.Tip();
64  }
65 
66  int nShift = (blockindex->nBits >> 24) & 0xff;
67 
68  double dDiff =
69  (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
70 
71  while (nShift < 29)
72  {
73  dDiff *= 256.0;
74  nShift++;
75  }
76  while (nShift > 29)
77  {
78  dDiff /= 256.0;
79  nShift--;
80  }
81 
82  return dDiff;
83 }
84 
86 {
87  UniValue result(UniValue::VOBJ);
88  result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
89  int confirmations = -1;
90  // Only report confirmations if the block is on the main chain
91  if (chainActive.Contains(blockindex))
92  confirmations = chainActive.Height() - blockindex->nHeight + 1;
93  result.push_back(Pair("confirmations", confirmations));
94  result.push_back(Pair("height", blockindex->nHeight));
95  result.push_back(Pair("version", blockindex->nVersion));
96  result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
97  result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
98  result.push_back(Pair("time", (int64_t)blockindex->nTime));
99  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
100  result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
101  result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
102  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
103  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
104 
105  if (blockindex->pprev)
106  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
107  CBlockIndex *pnext = chainActive.Next(blockindex);
108  if (pnext)
109  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
110  return result;
111 }
112 
113 UniValue blockToDeltasJSON(const CBlock& block, const CBlockIndex* blockindex)
114 {
115  UniValue result(UniValue::VOBJ);
116  result.push_back(Pair("hash", block.GetHash().GetHex()));
117  int confirmations = -1;
118  // Only report confirmations if the block is on the main chain
119  if (chainActive.Contains(blockindex)) {
120  confirmations = chainActive.Height() - blockindex->nHeight + 1;
121  } else {
122  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block is an orphan");
123  }
124  result.push_back(Pair("confirmations", confirmations));
125  result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
126  result.push_back(Pair("height", blockindex->nHeight));
127  result.push_back(Pair("version", block.nVersion));
128  result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
129 
130  UniValue deltas(UniValue::VARR);
131 
132  for (unsigned int i = 0; i < block.vtx.size(); i++) {
133  const CTransaction &tx = *(block.vtx[i]);
134  const uint256 txhash = tx.GetHash();
135 
136  UniValue entry(UniValue::VOBJ);
137  entry.push_back(Pair("txid", txhash.GetHex()));
138  entry.push_back(Pair("index", (int)i));
139 
140  UniValue inputs(UniValue::VARR);
141 
142  if (!tx.IsCoinBase()) {
143 
144  for (size_t j = 0; j < tx.vin.size(); j++) {
145  const CTxIn input = tx.vin[j];
146 
147  UniValue delta(UniValue::VOBJ);
148 
149  CSpentIndexValue spentInfo;
150  CSpentIndexKey spentKey(input.prevout.hash, input.prevout.n);
151 
152  if (GetSpentIndex(spentKey, spentInfo)) {
153  if (spentInfo.addressType == 1) {
154  delta.push_back(Pair("address", CRavenAddress(CKeyID(spentInfo.addressHash)).ToString()));
155  } else if (spentInfo.addressType == 2) {
156  delta.push_back(Pair("address", CRavenAddress(CScriptID(spentInfo.addressHash)).ToString()));
157  } else {
158  continue;
159  }
160  delta.push_back(Pair("satoshis", -1 * spentInfo.satoshis));
161  delta.push_back(Pair("index", (int)j));
162  delta.push_back(Pair("prevtxid", input.prevout.hash.GetHex()));
163  delta.push_back(Pair("prevout", (int)input.prevout.n));
164 
165  inputs.push_back(delta);
166  } else {
167  throw JSONRPCError(RPC_INTERNAL_ERROR, "Spent information not available");
168  }
169 
170  }
171  }
172 
173  entry.push_back(Pair("inputs", inputs));
174 
175  UniValue outputs(UniValue::VARR);
176 
177  for (unsigned int k = 0; k < tx.vout.size(); k++) {
178  const CTxOut &out = tx.vout[k];
179 
180  UniValue delta(UniValue::VOBJ);
181 
182  if (out.scriptPubKey.IsPayToScriptHash()) {
183  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
184  delta.push_back(Pair("address", CRavenAddress(CScriptID(uint160(hashBytes))).ToString()));
185 
186  } else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
187  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
188  delta.push_back(Pair("address", CRavenAddress(CKeyID(uint160(hashBytes))).ToString()));
189  } else {
190  continue;
191  }
192 
193  delta.push_back(Pair("satoshis", out.nValue));
194  delta.push_back(Pair("index", (int)k));
195 
196  outputs.push_back(delta);
197  }
198 
199  entry.push_back(Pair("outputs", outputs));
200  deltas.push_back(entry);
201 
202  }
203  result.push_back(Pair("deltas", deltas));
204  result.push_back(Pair("time", block.GetBlockTime()));
205  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
206  result.push_back(Pair("nonce", (uint64_t)block.nNonce));
207  result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
208  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
209  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
210 
211  if (blockindex->pprev)
212  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
213  CBlockIndex *pnext = chainActive.Next(blockindex);
214  if (pnext)
215  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
216  return result;
217 }
218 
219 UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails)
220 {
221  UniValue result(UniValue::VOBJ);
222  result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
223  int confirmations = -1;
224  // Only report confirmations if the block is on the main chain
225  if (chainActive.Contains(blockindex))
226  confirmations = chainActive.Height() - blockindex->nHeight + 1;
227  result.push_back(Pair("confirmations", confirmations));
228  result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS)));
229  result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
230  result.push_back(Pair("weight", (int)::GetBlockWeight(block)));
231  result.push_back(Pair("height", blockindex->nHeight));
232  result.push_back(Pair("version", block.nVersion));
233  result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
234  result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
236  for(const auto& tx : block.vtx)
237  {
238  if(txDetails)
239  {
240  UniValue objTx(UniValue::VOBJ);
241  TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());
242  txs.push_back(objTx);
243  }
244  else
245  txs.push_back(tx->GetHash().GetHex());
246  }
247  result.push_back(Pair("tx", txs));
248  result.push_back(Pair("time", block.GetBlockTime()));
249  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
250  result.push_back(Pair("nonce", (uint64_t)block.nNonce));
251  result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
252  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
253  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
254 
255  if (blockindex->pprev)
256  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
257  CBlockIndex *pnext = chainActive.Next(blockindex);
258  if (pnext)
259  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
260  return result;
261 }
262 
264 {
265  if (request.fHelp || request.params.size() != 0)
266  throw std::runtime_error(
267  "getblockcount\n"
268  "\nReturns the number of blocks in the longest blockchain.\n"
269  "\nResult:\n"
270  "n (numeric) The current block count\n"
271  "\nExamples:\n"
272  + HelpExampleCli("getblockcount", "")
273  + HelpExampleRpc("getblockcount", "")
274  );
275 
276  LOCK(cs_main);
277  return chainActive.Height();
278 }
279 
281 {
282  if (request.fHelp || request.params.size() != 0)
283  throw std::runtime_error(
284  "getbestblockhash\n"
285  "\nReturns the hash of the best (tip) block in the longest blockchain.\n"
286  "\nResult:\n"
287  "\"hex\" (string) the block hash hex encoded\n"
288  "\nExamples:\n"
289  + HelpExampleCli("getbestblockhash", "")
290  + HelpExampleRpc("getbestblockhash", "")
291  );
292 
293  LOCK(cs_main);
294  return chainActive.Tip()->GetBlockHash().GetHex();
295 }
296 
297 void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
298 {
299  if(pindex) {
300  std::lock_guard<std::mutex> lock(cs_blockchange);
301  latestblock.hash = pindex->GetBlockHash();
302  latestblock.height = pindex->nHeight;
303  }
304  cond_blockchange.notify_all();
305 }
306 
308 {
309  if (request.fHelp || request.params.size() > 1)
310  throw std::runtime_error(
311  "waitfornewblock (timeout)\n"
312  "\nWaits for a specific new block and returns useful info about it.\n"
313  "\nReturns the current block on timeout or exit.\n"
314  "\nArguments:\n"
315  "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
316  "\nResult:\n"
317  "{ (json object)\n"
318  " \"hash\" : { (string) The blockhash\n"
319  " \"height\" : { (int) Block height\n"
320  "}\n"
321  "\nExamples:\n"
322  + HelpExampleCli("waitfornewblock", "1000")
323  + HelpExampleRpc("waitfornewblock", "1000")
324  );
325  int timeout = 0;
326  if (!request.params[0].isNull())
327  timeout = request.params[0].get_int();
328 
329  CUpdatedBlock block;
330  {
331  std::unique_lock<std::mutex> lock(cs_blockchange);
332  block = latestblock;
333  if(timeout)
334  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
335  else
336  cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
337  block = latestblock;
338  }
340  ret.push_back(Pair("hash", block.hash.GetHex()));
341  ret.push_back(Pair("height", block.height));
342  return ret;
343 }
344 
346 {
347  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
348  throw std::runtime_error(
349  "waitforblock <blockhash> (timeout)\n"
350  "\nWaits for a specific new block and returns useful info about it.\n"
351  "\nReturns the current block on timeout or exit.\n"
352  "\nArguments:\n"
353  "1. \"blockhash\" (required, string) Block hash to wait for.\n"
354  "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
355  "\nResult:\n"
356  "{ (json object)\n"
357  " \"hash\" : { (string) The blockhash\n"
358  " \"height\" : { (int) Block height\n"
359  "}\n"
360  "\nExamples:\n"
361  + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
362  + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
363  );
364  int timeout = 0;
365 
366  uint256 hash = uint256S(request.params[0].get_str());
367 
368  if (!request.params[1].isNull())
369  timeout = request.params[1].get_int();
370 
371  CUpdatedBlock block;
372  {
373  std::unique_lock<std::mutex> lock(cs_blockchange);
374  if(timeout)
375  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
376  else
377  cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
378  block = latestblock;
379  }
380 
382  ret.push_back(Pair("hash", block.hash.GetHex()));
383  ret.push_back(Pair("height", block.height));
384  return ret;
385 }
386 
388 {
389  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
390  throw std::runtime_error(
391  "waitforblockheight <height> (timeout)\n"
392  "\nWaits for (at least) block height and returns the height and hash\n"
393  "of the current tip.\n"
394  "\nReturns the current block on timeout or exit.\n"
395  "\nArguments:\n"
396  "1. height (required, int) Block height to wait for (int)\n"
397  "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
398  "\nResult:\n"
399  "{ (json object)\n"
400  " \"hash\" : { (string) The blockhash\n"
401  " \"height\" : { (int) Block height\n"
402  "}\n"
403  "\nExamples:\n"
404  + HelpExampleCli("waitforblockheight", "\"100\", 1000")
405  + HelpExampleRpc("waitforblockheight", "\"100\", 1000")
406  );
407  int timeout = 0;
408 
409  int height = request.params[0].get_int();
410 
411  if (!request.params[1].isNull())
412  timeout = request.params[1].get_int();
413 
414  CUpdatedBlock block;
415  {
416  std::unique_lock<std::mutex> lock(cs_blockchange);
417  if(timeout)
418  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
419  else
420  cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
421  block = latestblock;
422  }
424  ret.push_back(Pair("hash", block.hash.GetHex()));
425  ret.push_back(Pair("height", block.height));
426  return ret;
427 }
428 
430 {
431  if (request.fHelp || request.params.size() != 0)
432  throw std::runtime_error(
433  "getdifficulty\n"
434  "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
435  "\nResult:\n"
436  "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
437  "\nExamples:\n"
438  + HelpExampleCli("getdifficulty", "")
439  + HelpExampleRpc("getdifficulty", "")
440  );
441 
442  LOCK(cs_main);
443  return GetDifficulty();
444 }
445 
447 {
448  return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n"
449  " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
450  " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
451  " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
452  " \"height\" : n, (numeric) block height when transaction entered pool\n"
453  " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
454  " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n"
455  " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
456  " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
457  " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n"
458  " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
459  " \"wtxid\" : hash, (string) hash of serialized transaction, including witness data\n"
460  " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
461  " \"transactionid\", (string) parent transaction id\n"
462  " ... ]\n";
463 }
464 
465 void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
466 {
468 
469  info.push_back(Pair("size", (int)e.GetTxSize()));
470  info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
471  info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
472  info.push_back(Pair("time", e.GetTime()));
473  info.push_back(Pair("height", (int)e.GetHeight()));
474  info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
475  info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
476  info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
477  info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
478  info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
479  info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
480  info.push_back(Pair("wtxid", mempool.vTxHashes[e.vTxHashesIdx].first.ToString()));
481  const CTransaction& tx = e.GetTx();
482  std::set<std::string> setDepends;
483  for (const CTxIn& txin : tx.vin)
484  {
485  if (mempool.exists(txin.prevout.hash))
486  setDepends.insert(txin.prevout.hash.ToString());
487  }
488 
489  UniValue depends(UniValue::VARR);
490  for (const std::string& dep : setDepends)
491  {
492  depends.push_back(dep);
493  }
494 
495  info.push_back(Pair("depends", depends));
496 }
497 
498 UniValue mempoolToJSON(bool fVerbose)
499 {
500  if (fVerbose)
501  {
502  LOCK(mempool.cs);
504  for (const CTxMemPoolEntry& e : mempool.mapTx)
505  {
506  const uint256& hash = e.GetTx().GetHash();
507  UniValue info(UniValue::VOBJ);
508  entryToJSON(info, e);
509  o.push_back(Pair(hash.ToString(), info));
510  }
511  return o;
512  }
513  else
514  {
515  std::vector<uint256> vtxid;
516  mempool.queryHashes(vtxid);
517 
519  for (const uint256& hash : vtxid)
520  a.push_back(hash.ToString());
521 
522  return a;
523  }
524 }
525 
527 {
528  if (request.fHelp || request.params.size() > 1)
529  throw std::runtime_error(
530  "getrawmempool ( verbose )\n"
531  "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
532  "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n"
533  "\nArguments:\n"
534  "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
535  "\nResult: (for verbose = false):\n"
536  "[ (json array of string)\n"
537  " \"transactionid\" (string) The transaction id\n"
538  " ,...\n"
539  "]\n"
540  "\nResult: (for verbose = true):\n"
541  "{ (json object)\n"
542  " \"transactionid\" : { (json object)\n"
544  + " }, ...\n"
545  "}\n"
546  "\nExamples:\n"
547  + HelpExampleCli("getrawmempool", "true")
548  + HelpExampleRpc("getrawmempool", "true")
549  );
550 
551  bool fVerbose = false;
552  if (!request.params[0].isNull())
553  fVerbose = request.params[0].get_bool();
554 
555  return mempoolToJSON(fVerbose);
556 }
557 
559 {
560  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
561  throw std::runtime_error(
562  "getmempoolancestors txid (verbose)\n"
563  "\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
564  "\nArguments:\n"
565  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
566  "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
567  "\nResult (for verbose=false):\n"
568  "[ (json array of strings)\n"
569  " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
570  " ,...\n"
571  "]\n"
572  "\nResult (for verbose=true):\n"
573  "{ (json object)\n"
574  " \"transactionid\" : { (json object)\n"
576  + " }, ...\n"
577  "}\n"
578  "\nExamples:\n"
579  + HelpExampleCli("getmempoolancestors", "\"mytxid\"")
580  + HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
581  );
582  }
583 
584  bool fVerbose = false;
585  if (!request.params[1].isNull())
586  fVerbose = request.params[1].get_bool();
587 
588  uint256 hash = ParseHashV(request.params[0], "parameter 1");
589 
590  LOCK(mempool.cs);
591 
592  CTxMemPool::txiter it = mempool.mapTx.find(hash);
593  if (it == mempool.mapTx.end()) {
594  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
595  }
596 
597  CTxMemPool::setEntries setAncestors;
598  uint64_t noLimit = std::numeric_limits<uint64_t>::max();
599  std::string dummy;
600  mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
601 
602  if (!fVerbose) {
604  for (CTxMemPool::txiter ancestorIt : setAncestors) {
605  o.push_back(ancestorIt->GetTx().GetHash().ToString());
606  }
607 
608  return o;
609  } else {
611  for (CTxMemPool::txiter ancestorIt : setAncestors) {
612  const CTxMemPoolEntry &e = *ancestorIt;
613  const uint256& _hash = e.GetTx().GetHash();
614  UniValue info(UniValue::VOBJ);
615  entryToJSON(info, e);
616  o.push_back(Pair(_hash.ToString(), info));
617  }
618  return o;
619  }
620 }
621 
623 {
624  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
625  throw std::runtime_error(
626  "getmempooldescendants txid (verbose)\n"
627  "\nIf txid is in the mempool, returns all in-mempool descendants.\n"
628  "\nArguments:\n"
629  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
630  "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
631  "\nResult (for verbose=false):\n"
632  "[ (json array of strings)\n"
633  " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
634  " ,...\n"
635  "]\n"
636  "\nResult (for verbose=true):\n"
637  "{ (json object)\n"
638  " \"transactionid\" : { (json object)\n"
640  + " }, ...\n"
641  "}\n"
642  "\nExamples:\n"
643  + HelpExampleCli("getmempooldescendants", "\"mytxid\"")
644  + HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
645  );
646  }
647 
648  bool fVerbose = false;
649  if (!request.params[1].isNull())
650  fVerbose = request.params[1].get_bool();
651 
652  uint256 hash = ParseHashV(request.params[0], "parameter 1");
653 
654  LOCK(mempool.cs);
655 
656  CTxMemPool::txiter it = mempool.mapTx.find(hash);
657  if (it == mempool.mapTx.end()) {
658  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
659  }
660 
661  CTxMemPool::setEntries setDescendants;
662  mempool.CalculateDescendants(it, setDescendants);
663  // CTxMemPool::CalculateDescendants will include the given tx
664  setDescendants.erase(it);
665 
666  if (!fVerbose) {
668  for (CTxMemPool::txiter descendantIt : setDescendants) {
669  o.push_back(descendantIt->GetTx().GetHash().ToString());
670  }
671 
672  return o;
673  } else {
675  for (CTxMemPool::txiter descendantIt : setDescendants) {
676  const CTxMemPoolEntry &e = *descendantIt;
677  const uint256& _hash = e.GetTx().GetHash();
678  UniValue info(UniValue::VOBJ);
679  entryToJSON(info, e);
680  o.push_back(Pair(_hash.ToString(), info));
681  }
682  return o;
683  }
684 }
685 
687 {
688  if (request.fHelp || request.params.size() != 1) {
689  throw std::runtime_error(
690  "getmempoolentry txid\n"
691  "\nReturns mempool data for given transaction\n"
692  "\nArguments:\n"
693  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
694  "\nResult:\n"
695  "{ (json object)\n"
697  + "}\n"
698  "\nExamples:\n"
699  + HelpExampleCli("getmempoolentry", "\"mytxid\"")
700  + HelpExampleRpc("getmempoolentry", "\"mytxid\"")
701  );
702  }
703 
704  uint256 hash = ParseHashV(request.params[0], "parameter 1");
705 
706  LOCK(mempool.cs);
707 
708  CTxMemPool::txiter it = mempool.mapTx.find(hash);
709  if (it == mempool.mapTx.end()) {
710  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
711  }
712 
713  const CTxMemPoolEntry &e = *it;
714  UniValue info(UniValue::VOBJ);
715  entryToJSON(info, e);
716  return info;
717 }
718 
720 {
721  if (request.fHelp || request.params.size() != 1)
722  throw std::runtime_error("");
723 
724  std::string strHash = request.params[0].get_str();
725  uint256 hash(uint256S(strHash));
726 
727  if (mapBlockIndex.count(hash) == 0)
728  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
729 
730  CBlock block;
731  CBlockIndex* pblockindex = mapBlockIndex[hash];
732 
733  if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
734  throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
735 
736  if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
737  throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
738 
739  return blockToDeltasJSON(block, pblockindex);
740 }
741 
743 {
744  if (request.fHelp || request.params.size() < 2)
745  throw std::runtime_error(
746  "getblockhashes timestamp\n"
747  "\nReturns array of hashes of blocks within the timestamp range provided.\n"
748  "\nArguments:\n"
749  "1. high (numeric, required) The newer block timestamp\n"
750  "2. low (numeric, required) The older block timestamp\n"
751  "3. options (string, required) A json object\n"
752  " {\n"
753  " \"noOrphans\":true (boolean) will only include blocks on the main chain\n"
754  " \"logicalTimes\":true (boolean) will include logical timestamps with hashes\n"
755  " }\n"
756  "\nResult:\n"
757  "[\n"
758  " \"hash\" (string) The block hash\n"
759  "]\n"
760  "[\n"
761  " {\n"
762  " \"blockhash\": (string) The block hash\n"
763  " \"logicalts\": (numeric) The logical timestamp\n"
764  " }\n"
765  "]\n"
766  "\nExamples:\n"
767  + HelpExampleCli("getblockhashes", "1231614698 1231024505")
768  + HelpExampleRpc("getblockhashes", "1231614698, 1231024505")
769  + HelpExampleCli("getblockhashes", "1231614698 1231024505 '{\"noOrphans\":false, \"logicalTimes\":true}'")
770  );
771 
772  unsigned int high = request.params[0].get_int();
773  unsigned int low = request.params[1].get_int();
774  bool fActiveOnly = false;
775  bool fLogicalTS = false;
776 
777  if (request.params.size() > 2) {
778  if (request.params[2].isObject()) {
779  UniValue noOrphans = find_value(request.params[2].get_obj(), "noOrphans");
780  UniValue returnLogical = find_value(request.params[2].get_obj(), "logicalTimes");
781 
782  if (noOrphans.isBool())
783  fActiveOnly = noOrphans.get_bool();
784 
785  if (returnLogical.isBool())
786  fLogicalTS = returnLogical.get_bool();
787  }
788  }
789 
790  std::vector<std::pair<uint256, unsigned int> > blockHashes;
791 
792  if (fActiveOnly)
793  LOCK(cs_main);
794 
795  if (!GetTimestampIndex(high, low, fActiveOnly, blockHashes)) {
796  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
797  }
798 
799  UniValue result(UniValue::VARR);
800 
801  for (std::vector<std::pair<uint256, unsigned int> >::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) {
802  if (fLogicalTS) {
803  UniValue item(UniValue::VOBJ);
804  item.push_back(Pair("blockhash", it->first.GetHex()));
805  item.push_back(Pair("logicalts", (int)it->second));
806  result.push_back(item);
807  } else {
808  result.push_back(it->first.GetHex());
809  }
810  }
811 
812  return result;
813 }
814 
816 {
817  if (request.fHelp || request.params.size() != 1)
818  throw std::runtime_error(
819  "getblockhash height\n"
820  "\nReturns hash of block in best-block-chain at height provided.\n"
821  "\nArguments:\n"
822  "1. height (numeric, required) The height index\n"
823  "\nResult:\n"
824  "\"hash\" (string) The block hash\n"
825  "\nExamples:\n"
826  + HelpExampleCli("getblockhash", "1000")
827  + HelpExampleRpc("getblockhash", "1000")
828  );
829 
830  LOCK(cs_main);
831 
832  int nHeight = request.params[0].get_int();
833  if (nHeight < 0 || nHeight > chainActive.Height())
834  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
835 
836  CBlockIndex* pblockindex = chainActive[nHeight];
837  return pblockindex->GetBlockHash().GetHex();
838 }
839 
841 {
842  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
843  throw std::runtime_error(
844  "getblockheader \"hash\" ( verbose )\n"
845  "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
846  "If verbose is true, returns an Object with information about blockheader <hash>.\n"
847  "\nArguments:\n"
848  "1. \"hash\" (string, required) The block hash\n"
849  "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
850  "\nResult (for verbose = true):\n"
851  "{\n"
852  " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
853  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
854  " \"height\" : n, (numeric) The block height or index\n"
855  " \"version\" : n, (numeric) The block version\n"
856  " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
857  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
858  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
859  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
860  " \"nonce\" : n, (numeric) The nonce\n"
861  " \"bits\" : \"1d00ffff\", (string) The bits\n"
862  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
863  " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
864  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
865  " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
866  "}\n"
867  "\nResult (for verbose=false):\n"
868  "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
869  "\nExamples:\n"
870  + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
871  + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
872  );
873 
874  LOCK(cs_main);
875 
876  std::string strHash = request.params[0].get_str();
877  uint256 hash(uint256S(strHash));
878 
879  bool fVerbose = true;
880  if (!request.params[1].isNull())
881  fVerbose = request.params[1].get_bool();
882 
883  if (mapBlockIndex.count(hash) == 0)
884  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
885 
886  CBlockIndex* pblockindex = mapBlockIndex[hash];
887 
888  if (!fVerbose)
889  {
890  CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
891  ssBlock << pblockindex->GetBlockHeader();
892  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
893  return strHex;
894  }
895 
896  return blockheaderToJSON(pblockindex);
897 }
898 
900 {
901  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
902  throw std::runtime_error(
903  "getblock \"blockhash\" ( verbosity ) \n"
904  "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
905  "If verbosity is 1, returns an Object with information about block <hash>.\n"
906  "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
907  "\nArguments:\n"
908  "1. \"blockhash\" (string, required) The block hash\n"
909  "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"
910  "\nResult (for verbosity = 0):\n"
911  "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
912  "\nResult (for verbosity = 1):\n"
913  "{\n"
914  " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
915  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
916  " \"size\" : n, (numeric) The block size\n"
917  " \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
918  " \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
919  " \"height\" : n, (numeric) The block height or index\n"
920  " \"version\" : n, (numeric) The block version\n"
921  " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
922  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
923  " \"tx\" : [ (array of string) The transaction ids\n"
924  " \"transactionid\" (string) The transaction id\n"
925  " ,...\n"
926  " ],\n"
927  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
928  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
929  " \"nonce\" : n, (numeric) The nonce\n"
930  " \"bits\" : \"1d00ffff\", (string) The bits\n"
931  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
932  " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
933  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
934  " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
935  "}\n"
936  "\nResult (for verbosity = 2):\n"
937  "{\n"
938  " ..., Same output as verbosity = 1.\n"
939  " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
940  " ,...\n"
941  " ],\n"
942  " ,... Same output as verbosity = 1.\n"
943  "}\n"
944  "\nExamples:\n"
945  + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
946  + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
947  );
948 
949  LOCK(cs_main);
950 
951  std::string strHash = request.params[0].get_str();
952  uint256 hash(uint256S(strHash));
953 
954  int verbosity = 1;
955  if (!request.params[1].isNull()) {
956  if(request.params[1].isNum())
957  verbosity = request.params[1].get_int();
958  else
959  verbosity = request.params[1].get_bool() ? 1 : 0;
960  }
961 
962  if (mapBlockIndex.count(hash) == 0)
963  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
964 
965  CBlock block;
966  CBlockIndex* pblockindex = mapBlockIndex[hash];
967 
968  if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
969  throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
970 
971  if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
972  // Block not found on disk. This could be because we have the block
973  // header in our index but don't have the block (for example if a
974  // non-whitelisted node sends us an unrequested long chain of valid
975  // blocks, we add the headers to our index, but don't accept the
976  // block).
977  throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
978 
979  if (verbosity <= 0)
980  {
981  CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
982  ssBlock << block;
983  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
984  return strHex;
985  }
986 
987  return blockToJSON(block, pblockindex, verbosity >= 2);
988 }
989 
991 {
992  int nHeight;
994  uint64_t nTransactions;
996  uint64_t nBogoSize;
998  uint64_t nDiskSize;
1000 
1001  CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {}
1002 };
1003 
1004 static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
1005 {
1006  assert(!outputs.empty());
1007  ss << hash;
1008  ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
1009  stats.nTransactions++;
1010  for (const auto output : outputs) {
1011  ss << VARINT(output.first + 1);
1012  ss << output.second.out.scriptPubKey;
1013  ss << VARINT(output.second.out.nValue);
1014  stats.nTransactionOutputs++;
1015  stats.nTotalAmount += output.second.out.nValue;
1016  stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ +
1017  2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */;
1018  }
1019  ss << VARINT(0);
1020 }
1021 
1023 static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
1024 {
1025  std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
1026  assert(pcursor);
1027 
1028  CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
1029  stats.hashBlock = pcursor->GetBestBlock();
1030  {
1031  LOCK(cs_main);
1032  stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
1033  }
1034  ss << stats.hashBlock;
1035  uint256 prevkey;
1036  std::map<uint32_t, Coin> outputs;
1037  while (pcursor->Valid()) {
1038  boost::this_thread::interruption_point();
1039  COutPoint key;
1040  Coin coin;
1041  if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
1042  if (!outputs.empty() && key.hash != prevkey) {
1043  ApplyStats(stats, ss, prevkey, outputs);
1044  outputs.clear();
1045  }
1046  prevkey = key.hash;
1047  outputs[key.n] = std::move(coin);
1048  } else {
1049  return error("%s: unable to read value", __func__);
1050  }
1051  pcursor->Next();
1052  }
1053  if (!outputs.empty()) {
1054  ApplyStats(stats, ss, prevkey, outputs);
1055  }
1056  stats.hashSerialized = ss.GetHash();
1057  stats.nDiskSize = view->EstimateSize();
1058  return true;
1059 }
1060 
1062 {
1063  if (request.fHelp || request.params.size() != 1)
1064  throw std::runtime_error(
1065  "pruneblockchain\n"
1066  "\nArguments:\n"
1067  "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n"
1068  " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n"
1069  "\nResult:\n"
1070  "n (numeric) Height of the last block pruned.\n"
1071  "\nExamples:\n"
1072  + HelpExampleCli("pruneblockchain", "1000")
1073  + HelpExampleRpc("pruneblockchain", "1000"));
1074 
1075  if (!fPruneMode)
1076  throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
1077 
1078  LOCK(cs_main);
1079 
1080  int heightParam = request.params[0].get_int();
1081  if (heightParam < 0)
1082  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
1083 
1084  // Height value more than a billion is too high to be a block height, and
1085  // too low to be a block time (corresponds to timestamp from Sep 2001).
1086  if (heightParam > 1000000000) {
1087  // Add a 2 hour buffer to include blocks which might have had old timestamps
1088  CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW);
1089  if (!pindex) {
1090  throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
1091  }
1092  heightParam = pindex->nHeight;
1093  }
1094 
1095  unsigned int height = (unsigned int) heightParam;
1096  unsigned int chainHeight = (unsigned int) chainActive.Height();
1097  if (chainHeight < Params().PruneAfterHeight())
1098  throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
1099  else if (height > chainHeight)
1100  throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
1101  else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
1102  LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.");
1103  height = chainHeight - MIN_BLOCKS_TO_KEEP;
1104  }
1105 
1106  PruneBlockFilesManual(height);
1107  return uint64_t(height);
1108 }
1109 
1111 {
1112  if (request.fHelp || request.params.size() != 0)
1113  throw std::runtime_error(
1114  "gettxoutsetinfo\n"
1115  "\nReturns statistics about the unspent transaction output set.\n"
1116  "Note this call may take some time.\n"
1117  "\nResult:\n"
1118  "{\n"
1119  " \"height\":n, (numeric) The current block height (index)\n"
1120  " \"bestblock\": \"hex\", (string) the best block hash hex\n"
1121  " \"transactions\": n, (numeric) The number of transactions\n"
1122  " \"txouts\": n, (numeric) The number of output transactions\n"
1123  " \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n"
1124  " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n"
1125  " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
1126  " \"total_amount\": x.xxx (numeric) The total amount\n"
1127  "}\n"
1128  "\nExamples:\n"
1129  + HelpExampleCli("gettxoutsetinfo", "")
1130  + HelpExampleRpc("gettxoutsetinfo", "")
1131  );
1132 
1133  UniValue ret(UniValue::VOBJ);
1134 
1135  CCoinsStats stats;
1136  FlushStateToDisk();
1137  if (GetUTXOStats(pcoinsdbview, stats)) {
1138  ret.push_back(Pair("height", (int64_t)stats.nHeight));
1139  ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
1140  ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
1141  ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
1142  ret.push_back(Pair("bogosize", (int64_t)stats.nBogoSize));
1143  ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex()));
1144  ret.push_back(Pair("disk_size", stats.nDiskSize));
1145  ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
1146  } else {
1147  throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1148  }
1149  return ret;
1150 }
1151 
1153 {
1154  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
1155  throw std::runtime_error(
1156  "gettxout \"txid\" n ( include_mempool )\n"
1157  "\nReturns details about an unspent transaction output.\n"
1158  "\nArguments:\n"
1159  "1. \"txid\" (string, required) The transaction id\n"
1160  "2. \"n\" (numeric, required) vout number\n"
1161  "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true."
1162  " Note that an unspent output that is spent in the mempool won't appear.\n"
1163  "\nResult:\n"
1164  "{\n"
1165  " \"bestblock\" : \"hash\", (string) the block hash\n"
1166  " \"confirmations\" : n, (numeric) The number of confirmations\n"
1167  " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
1168  " \"scriptPubKey\" : { (json object)\n"
1169  " \"asm\" : \"code\", (string) \n"
1170  " \"hex\" : \"hex\", (string) \n"
1171  " \"reqSigs\" : n, (numeric) Number of required signatures\n"
1172  " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
1173  " \"addresses\" : [ (array of string) array of raven addresses\n"
1174  " \"address\" (string) raven address\n"
1175  " ,...\n"
1176  " ]\n"
1177  " },\n"
1178  " \"coinbase\" : true|false (boolean) Coinbase or not\n"
1179  "}\n"
1180 
1181  "\nExamples:\n"
1182  "\nGet unspent transactions\n"
1183  + HelpExampleCli("listunspent", "") +
1184  "\nView the details\n"
1185  + HelpExampleCli("gettxout", "\"txid\" 1") +
1186  "\nAs a json rpc call\n"
1187  + HelpExampleRpc("gettxout", "\"txid\", 1")
1188  );
1189 
1190  LOCK(cs_main);
1191 
1192  UniValue ret(UniValue::VOBJ);
1193 
1194  std::string strHash = request.params[0].get_str();
1195  uint256 hash(uint256S(strHash));
1196  int n = request.params[1].get_int();
1197  COutPoint out(hash, n);
1198  bool fMempool = true;
1199  if (!request.params[2].isNull())
1200  fMempool = request.params[2].get_bool();
1201 
1202  Coin coin;
1203  if (fMempool) {
1204  LOCK(mempool.cs);
1206  if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
1207  return NullUniValue;
1208  }
1209  } else {
1210  if (!pcoinsTip->GetCoin(out, coin)) {
1211  return NullUniValue;
1212  }
1213  }
1214 
1215  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
1216  CBlockIndex *pindex = it->second;
1217  ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
1218  if (coin.nHeight == MEMPOOL_HEIGHT) {
1219  ret.push_back(Pair("confirmations", 0));
1220  } else {
1221  ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)));
1222  }
1223  ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
1225  ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
1226  ret.push_back(Pair("scriptPubKey", o));
1227  ret.push_back(Pair("coinbase", (bool)coin.fCoinBase));
1228 
1229  return ret;
1230 }
1231 
1233 {
1234  int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
1235  int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
1236  if (request.fHelp || request.params.size() > 2)
1237  throw std::runtime_error(
1238  "verifychain ( checklevel nblocks )\n"
1239  "\nVerifies blockchain database.\n"
1240  "\nArguments:\n"
1241  "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
1242  "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
1243  "\nResult:\n"
1244  "true|false (boolean) Verified or not\n"
1245  "\nExamples:\n"
1246  + HelpExampleCli("verifychain", "")
1247  + HelpExampleRpc("verifychain", "")
1248  );
1249 
1250  LOCK(cs_main);
1251 
1252  if (!request.params[0].isNull())
1253  nCheckLevel = request.params[0].get_int();
1254  if (!request.params[1].isNull())
1255  nCheckDepth = request.params[1].get_int();
1256 
1257  return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth);
1258 }
1259 
1261 // static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
1262 // {
1263 // UniValue rv(UniValue::VOBJ);
1264 // bool activated = false;
1265 // switch(version)
1266 // {
1267 // case 2:
1268 // activated = pindex->nHeight >= consensusParams.BIP34Height;
1269 // break;
1270 // case 3:
1271 // activated = pindex->nHeight >= consensusParams.BIP66Height;
1272 // break;
1273 // case 4:
1274 // activated = pindex->nHeight >= consensusParams.BIP65Height;
1275 // break;
1276 // }
1277 // rv.push_back(Pair("status", activated));
1278 // return rv;
1279 // }
1280 
1281 // static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
1282 // {
1283 // UniValue rv(UniValue::VOBJ);
1284 // rv.push_back(Pair("id", name));
1285 // rv.push_back(Pair("version", version));
1286 // rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams)));
1287 // return rv;
1288 // }
1289 
1290 static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
1291 {
1293  const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
1294  switch (thresholdState) {
1295  case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
1296  case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
1297  case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
1298  case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
1299  case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
1300  }
1301  if (THRESHOLD_STARTED == thresholdState)
1302  {
1303  rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
1304  }
1305  rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
1306  rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
1307  rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id)));
1308  if (THRESHOLD_STARTED == thresholdState)
1309  {
1310  UniValue statsUV(UniValue::VOBJ);
1311  BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
1312  statsUV.push_back(Pair("period", statsStruct.period));
1313  statsUV.push_back(Pair("threshold", statsStruct.threshold));
1314  statsUV.push_back(Pair("elapsed", statsStruct.elapsed));
1315  statsUV.push_back(Pair("count", statsStruct.count));
1316  statsUV.push_back(Pair("possible", statsStruct.possible));
1317  rv.push_back(Pair("statistics", statsUV));
1318  }
1319  return rv;
1320 }
1321 
1322 void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
1323 {
1324  // Deployments with timeout value of 0 are hidden.
1325  // A timeout value of 0 guarantees a softfork will never be activated.
1326  // This is used when softfork codes are merged without specifying the deployment schedule.
1327  if (consensusParams.vDeployments[id].nTimeout > 0)
1328  bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id)));
1329 }
1330 
1332 {
1333  if (request.fHelp || request.params.size() != 0)
1334  throw std::runtime_error(
1335  "getblockchaininfo\n"
1336  "Returns an object containing various state info regarding blockchain processing.\n"
1337  "\nResult:\n"
1338  "{\n"
1339  " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
1340  " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
1341  " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
1342  " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
1343  " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
1344  " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
1345  " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
1346  " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
1347  " \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n"
1348  " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
1349  " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n"
1350  " \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n"
1351  " \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n"
1352  " \"softforks\": [ (array) status of softforks in progress\n"
1353  " {\n"
1354  " \"id\": \"xxxx\", (string) name of softfork\n"
1355  " \"version\": xx, (numeric) block version\n"
1356  " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
1357  " \"status\": xx, (boolean) true if threshold reached\n"
1358  " },\n"
1359  " }, ...\n"
1360  " ],\n"
1361  " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
1362  " \"xxxx\" : { (string) name of the softfork\n"
1363  " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
1364  " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
1365  " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
1366  " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
1367  " \"since\": xx, (numeric) height of the first block to which the status applies\n"
1368  " \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n"
1369  " \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n"
1370  " \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n"
1371  " \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n"
1372  " \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n"
1373  " \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n"
1374  " }\n"
1375  " }\n"
1376  " }\n"
1377  " \"warnings\" : \"...\", (string) any network and blockchain warnings.\n"
1378  "}\n"
1379  "\nExamples:\n"
1380  + HelpExampleCli("getblockchaininfo", "")
1381  + HelpExampleRpc("getblockchaininfo", "")
1382  );
1383 
1384  LOCK(cs_main);
1385 
1386  UniValue obj(UniValue::VOBJ);
1387  obj.push_back(Pair("chain", Params().NetworkIDString()));
1388  obj.push_back(Pair("blocks", (int)chainActive.Height()));
1389  obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
1390  obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
1391  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
1392  if (IsDGWActive(chainActive.Height())) {
1393  obj.push_back(Pair("difficulty_algorithm", "DGW-180"));
1394  } else {
1395  obj.push_back(Pair("difficulty_algorithm", "BTC"));
1396  obj.push_back(Pair("DGW_activation_height", (int)Params().DGWActivationBlock()));
1397  }
1398  obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
1399  obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip())));
1400  obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
1401  obj.push_back(Pair("size_on_disk", CalculateCurrentUsage()));
1402  obj.push_back(Pair("pruned", fPruneMode));
1403  if (fPruneMode) {
1404  CBlockIndex* block = chainActive.Tip();
1405  assert(block);
1406  while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
1407  block = block->pprev;
1408  }
1409 
1410  obj.push_back(Pair("pruneheight", block->nHeight));
1411 
1412  // if 0, execution bypasses the whole if block.
1413  bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1);
1414  obj.push_back(Pair("automatic_pruning", automatic_pruning));
1415  if (automatic_pruning) {
1416  obj.push_back(Pair("prune_target_size", nPruneTarget));
1417  }
1418  }
1419 
1420  const Consensus::Params& consensusParams = Params().GetConsensus();
1421  //CBlockIndex* tip = chainActive.Tip();
1422 
1423 
1424  UniValue softforks(UniValue::VARR);
1425  UniValue bip9_softforks(UniValue::VOBJ);
1426  // softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
1427  // softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
1428  // softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
1429  // BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
1430  //BIP9SoftForkDescPushBack(bip9_softforks, "segwit", consensusParams, Consensus::DEPLOYMENT_SEGWIT);
1431  BIP9SoftForkDescPushBack(bip9_softforks, "assets", consensusParams, Consensus::DEPLOYMENT_ASSETS);
1432  BIP9SoftForkDescPushBack(bip9_softforks, "messaging", consensusParams, Consensus::DEPLOYMENT_MESSAGING);
1433  BIP9SoftForkDescPushBack(bip9_softforks, "restricted_assets", consensusParams, Consensus::DEPLOYMENT_RESTRICTED_ASSETS);
1434  obj.push_back(Pair("softforks", softforks));
1435  obj.push_back(Pair("bip9_softforks", bip9_softforks));
1436 
1437  obj.push_back(Pair("warnings", GetWarnings("statusbar")));
1438  return obj;
1439 }
1440 
1443 {
1444  bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
1445  {
1446  /* Make sure that unequal blocks with the same height do not compare
1447  equal. Use the pointers themselves to make a distinction. */
1448 
1449  if (a->nHeight != b->nHeight)
1450  return (a->nHeight > b->nHeight);
1451 
1452  return a < b;
1453  }
1454 };
1455 
1457 {
1458  if (request.fHelp || request.params.size() != 0)
1459  throw std::runtime_error(
1460  "getchaintips\n"
1461  "Return information about all known tips in the block tree,"
1462  " including the main chain as well as orphaned branches.\n"
1463  "\nResult:\n"
1464  "[\n"
1465  " {\n"
1466  " \"height\": xxxx, (numeric) height of the chain tip\n"
1467  " \"hash\": \"xxxx\", (string) block hash of the tip\n"
1468  " \"branchlen\": 0 (numeric) zero for main chain\n"
1469  " \"status\": \"active\" (string) \"active\" for the main chain\n"
1470  " },\n"
1471  " {\n"
1472  " \"height\": xxxx,\n"
1473  " \"hash\": \"xxxx\",\n"
1474  " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
1475  " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
1476  " }\n"
1477  "]\n"
1478  "Possible values for status:\n"
1479  "1. \"invalid\" This branch contains at least one invalid block\n"
1480  "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1481  "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1482  "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1483  "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
1484  "\nExamples:\n"
1485  + HelpExampleCli("getchaintips", "")
1486  + HelpExampleRpc("getchaintips", "")
1487  );
1488 
1489  LOCK(cs_main);
1490 
1491  /*
1492  * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
1493  * Algorithm:
1494  * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
1495  * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
1496  * - add chainActive.Tip()
1497  */
1498  std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1499  std::set<const CBlockIndex*> setOrphans;
1500  std::set<const CBlockIndex*> setPrevs;
1501 
1502  for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
1503  {
1504  if (!chainActive.Contains(item.second)) {
1505  setOrphans.insert(item.second);
1506  setPrevs.insert(item.second->pprev);
1507  }
1508  }
1509 
1510  for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
1511  {
1512  if (setPrevs.erase(*it) == 0) {
1513  setTips.insert(*it);
1514  }
1515  }
1516 
1517  // Always report the currently active tip.
1518  setTips.insert(chainActive.Tip());
1519 
1520  /* Construct the output array. */
1521  UniValue res(UniValue::VARR);
1522  for (const CBlockIndex* block : setTips)
1523  {
1524  UniValue obj(UniValue::VOBJ);
1525  obj.push_back(Pair("height", block->nHeight));
1526  obj.push_back(Pair("hash", block->phashBlock->GetHex()));
1527 
1528  const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
1529  obj.push_back(Pair("branchlen", branchLen));
1530 
1531  std::string status;
1532  if (chainActive.Contains(block)) {
1533  // This block is part of the currently active chain.
1534  status = "active";
1535  } else if (block->nStatus & BLOCK_FAILED_MASK) {
1536  // This block or one of its ancestors is invalid.
1537  status = "invalid";
1538  } else if (block->nChainTx == 0) {
1539  // This block cannot be connected because full block data for it or one of its parents is missing.
1540  status = "headers-only";
1541  } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
1542  // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
1543  status = "valid-fork";
1544  } else if (block->IsValid(BLOCK_VALID_TREE)) {
1545  // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
1546  status = "valid-headers";
1547  } else {
1548  // No clue.
1549  status = "unknown";
1550  }
1551  obj.push_back(Pair("status", status));
1552 
1553  res.push_back(obj);
1554  }
1555 
1556  return res;
1557 }
1558 
1560 {
1561  UniValue ret(UniValue::VOBJ);
1562  ret.push_back(Pair("size", (int64_t) mempool.size()));
1563  ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
1564  ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
1565  size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1566  ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
1567  ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
1568 
1569  return ret;
1570 }
1571 
1573 {
1574  if (request.fHelp || request.params.size() != 0)
1575  throw std::runtime_error(
1576  "getmempoolinfo\n"
1577  "\nReturns details on the active state of the TX memory pool.\n"
1578  "\nResult:\n"
1579  "{\n"
1580  " \"size\": xxxxx, (numeric) Current tx count\n"
1581  " \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
1582  " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
1583  " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
1584  " \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted\n"
1585  "}\n"
1586  "\nExamples:\n"
1587  + HelpExampleCli("getmempoolinfo", "")
1588  + HelpExampleRpc("getmempoolinfo", "")
1589  );
1590 
1591  return mempoolInfoToJSON();
1592 }
1593 
1595 {
1596  if (request.fHelp || request.params.size() != 1)
1597  throw std::runtime_error(
1598  "preciousblock \"blockhash\"\n"
1599  "\nTreats a block as if it were received before others with the same work.\n"
1600  "\nA later preciousblock call can override the effect of an earlier one.\n"
1601  "\nThe effects of preciousblock are not retained across restarts.\n"
1602  "\nArguments:\n"
1603  "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n"
1604  "\nResult:\n"
1605  "\nExamples:\n"
1606  + HelpExampleCli("preciousblock", "\"blockhash\"")
1607  + HelpExampleRpc("preciousblock", "\"blockhash\"")
1608  );
1609 
1610  std::string strHash = request.params[0].get_str();
1611  uint256 hash(uint256S(strHash));
1612  CBlockIndex* pblockindex;
1613 
1614  {
1615  LOCK(cs_main);
1616  if (mapBlockIndex.count(hash) == 0)
1617  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1618 
1619  pblockindex = mapBlockIndex[hash];
1620  }
1621 
1622  CValidationState state;
1623  PreciousBlock(state, Params(), pblockindex);
1624 
1625  if (!state.IsValid()) {
1627  }
1628 
1629  return NullUniValue;
1630 }
1631 
1633 {
1634  if (request.fHelp || request.params.size() != 1)
1635  throw std::runtime_error(
1636  "invalidateblock \"blockhash\"\n"
1637  "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
1638  "\nArguments:\n"
1639  "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n"
1640  "\nResult:\n"
1641  "\nExamples:\n"
1642  + HelpExampleCli("invalidateblock", "\"blockhash\"")
1643  + HelpExampleRpc("invalidateblock", "\"blockhash\"")
1644  );
1645 
1646  std::string strHash = request.params[0].get_str();
1647  uint256 hash(uint256S(strHash));
1648  CValidationState state;
1649 
1650  {
1651  LOCK(cs_main);
1652  if (mapBlockIndex.count(hash) == 0)
1653  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1654 
1655  CBlockIndex* pblockindex = mapBlockIndex[hash];
1656  InvalidateBlock(state, Params(), pblockindex);
1657  }
1658 
1659  if (state.IsValid()) {
1660  ActivateBestChain(state, Params());
1661  }
1662 
1663  if (!state.IsValid()) {
1665  }
1666 
1667  return NullUniValue;
1668 }
1669 
1671 {
1672  if (request.fHelp || request.params.size() != 1)
1673  throw std::runtime_error(
1674  "reconsiderblock \"blockhash\"\n"
1675  "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
1676  "This can be used to undo the effects of invalidateblock.\n"
1677  "\nArguments:\n"
1678  "1. \"blockhash\" (string, required) the hash of the block to reconsider\n"
1679  "\nResult:\n"
1680  "\nExamples:\n"
1681  + HelpExampleCli("reconsiderblock", "\"blockhash\"")
1682  + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
1683  );
1684 
1685  std::string strHash = request.params[0].get_str();
1686  uint256 hash(uint256S(strHash));
1687 
1688  {
1689  LOCK(cs_main);
1690  if (mapBlockIndex.count(hash) == 0)
1691  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1692 
1693  CBlockIndex* pblockindex = mapBlockIndex[hash];
1694  ResetBlockFailureFlags(pblockindex);
1695  }
1696 
1697  CValidationState state;
1698  ActivateBestChain(state, Params());
1699 
1700  if (!state.IsValid()) {
1702  }
1703 
1704  return NullUniValue;
1705 }
1706 
1708 {
1709  if (request.fHelp || request.params.size() > 2)
1710  throw std::runtime_error(
1711  "getchaintxstats ( nblocks blockhash )\n"
1712  "\nCompute statistics about the total number and rate of transactions in the chain.\n"
1713  "\nArguments:\n"
1714  "1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n"
1715  "2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n"
1716  "\nResult:\n"
1717  "{\n"
1718  " \"time\": xxxxx, (numeric) The timestamp for the final block in the window in UNIX format.\n"
1719  " \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n"
1720  " \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n"
1721  " \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n"
1722  " \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n"
1723  " \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n"
1724  "}\n"
1725  "\nExamples:\n"
1726  + HelpExampleCli("getchaintxstats", "")
1727  + HelpExampleRpc("getchaintxstats", "2016")
1728  );
1729 
1730  const CBlockIndex* pindex;
1731  int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month
1732 
1733  bool havehash = !request.params[1].isNull();
1734  uint256 hash;
1735  if (havehash) {
1736  hash = uint256S(request.params[1].get_str());
1737  }
1738 
1739  {
1740  LOCK(cs_main);
1741  if (havehash) {
1742  auto it = mapBlockIndex.find(hash);
1743  if (it == mapBlockIndex.end()) {
1744  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1745  }
1746  pindex = it->second;
1747  if (!chainActive.Contains(pindex)) {
1748  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
1749  }
1750  } else {
1751  pindex = chainActive.Tip();
1752  }
1753  }
1754 
1755  assert(pindex != nullptr);
1756 
1757  if (request.params[0].isNull()) {
1758  blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
1759  } else {
1760  blockcount = request.params[0].get_int();
1761 
1762  if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
1763  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
1764  }
1765  }
1766 
1767  const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount);
1768  int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast();
1769  int nTxDiff = pindex->nChainTx - pindexPast->nChainTx;
1770 
1771  UniValue ret(UniValue::VOBJ);
1772  ret.push_back(Pair("time", (int64_t)pindex->nTime));
1773  ret.push_back(Pair("txcount", (int64_t)pindex->nChainTx));
1774  ret.push_back(Pair("window_block_count", blockcount));
1775  if (blockcount > 0) {
1776  ret.push_back(Pair("window_tx_count", nTxDiff));
1777  ret.push_back(Pair("window_interval", nTimeDiff));
1778  if (nTimeDiff > 0) {
1779  ret.push_back(Pair("txrate", ((double)nTxDiff) / nTimeDiff));
1780  }
1781  }
1782 
1783  return ret;
1784 }
1785 
1787 {
1788  if (request.fHelp || request.params.size() != 0) {
1789  throw std::runtime_error(
1790  "savemempool\n"
1791  "\nDumps the mempool to disk.\n"
1792  "\nExamples:\n"
1793  + HelpExampleCli("savemempool", "")
1794  + HelpExampleRpc("savemempool", "")
1795  );
1796  }
1797 
1798  if (!DumpMempool()) {
1799  throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
1800  }
1801 
1802  return NullUniValue;
1803 }
1804 
1805 static const CRPCCommand commands[] =
1806 { // category name actor (function) argNames
1807  // --------------------- ------------------------ ----------------------- ----------
1808  { "blockchain", "getblockchaininfo", &getblockchaininfo, {} },
1809  { "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} },
1810  { "blockchain", "getbestblockhash", &getbestblockhash, {} },
1811  { "blockchain", "getblockcount", &getblockcount, {} },
1812  { "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} },
1813  { "blockchain", "getblockdeltas", &getblockdeltas, {} },
1814  { "blockchain", "getblockhashes", &getblockhashes, {} },
1815  { "blockchain", "getblockhash", &getblockhash, {"height"} },
1816  { "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} },
1817  { "blockchain", "getchaintips", &getchaintips, {} },
1818  { "blockchain", "getdifficulty", &getdifficulty, {} },
1819  { "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} },
1820  { "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} },
1821  { "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} },
1822  { "blockchain", "getmempoolinfo", &getmempoolinfo, {} },
1823  { "blockchain", "getrawmempool", &getrawmempool, {"verbose"} },
1824  { "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} },
1825  { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} },
1826  { "blockchain", "pruneblockchain", &pruneblockchain, {"height"} },
1827  { "blockchain", "savemempool", &savemempool, {} },
1828  { "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} },
1829 
1830  { "blockchain", "preciousblock", &preciousblock, {"blockhash"} },
1831 
1832  /* Not shown in help */
1833  { "hidden", "invalidateblock", &invalidateblock, {"blockhash"} },
1834  { "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} },
1835  { "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} },
1836  { "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} },
1837  { "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} },
1838 };
1839 
1841 {
1842  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1843  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1844 }
uint32_t nNonce
Definition: block.h:30
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:197
CAmount nValue
Definition: transaction.h:140
size_t vTxHashesIdx
Index in mempool&#39;s vTxHashes.
Definition: txmempool.h:134
#define VARINT(obj)
Definition: serialize.h:367
CTxMemPool mempool
bool isObject() const
Definition: univalue.h:86
uint64_t nTransactionOutputs
Definition: blockchain.cpp:995
uint64_t GetSizeWithAncestors() const
Definition: txmempool.h:130
bool isBool() const
Definition: univalue.h:82
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:89
bool DumpMempool(void)
Dump the mempool to disk.
UniValue getmempoolancestors(const JSONRPCRequest &request)
Definition: blockchain.cpp:558
bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, const bool fActiveOnly, std::vector< std::pair< uint256, unsigned int > > &hashes)
Raven RPC command dispatcher.
Definition: server.h:143
UniValue getblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:899
uint256 hashBlock
Definition: blockchain.cpp:993
CScript scriptPubKey
Definition: transaction.h:141
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:179
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:209
bool get_bool() const
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:336
A UTXO entry.
Definition: coins.h:32
Definition: block.h:73
UniValue getbestblockhash(const JSONRPCRequest &request)
Definition: blockchain.cpp:280
size_t GetTxSize() const
Definition: txmempool.cpp:56
UniValue reconsiderblock(const JSONRPCRequest &request)
UniValue blockToDeltasJSON(const CBlock &block, const CBlockIndex *blockindex)
Definition: blockchain.cpp:113
#define strprintf
Definition: tinyformat.h:1054
bool IsPayToScriptHash() const
Definition: script.cpp:221
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:1281
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:1265
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:88
bool isSpent(const COutPoint &outpoint)
Definition: txmempool.cpp:344
UniValue preciousblock(const JSONRPCRequest &request)
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:967
UniValue mempoolInfoToJSON()
Mempool information to JSON.
Comparison function for sorting the getchaintips heads.
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:136
CBlockHeader GetBlockHeader() const
Definition: chain.h:281
int Height() const
Return the maximal height in the chain.
Definition: chain.h:479
CCriticalSection cs_main
Global state.
Definition: validation.cpp:72
bool IsValid() const
Definition: validation.h:69
CTxOut out
unspent transaction output
Definition: coins.h:36
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
CAmount GetModFeesWithDescendants() const
Definition: txmempool.h:125
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:39
sph_u32 high
Definition: keccak.c:370
uint64_t GetTotalTxSize() const
Definition: txmempool.h:654
UniValue blockheaderToJSON(const CBlockIndex *blockindex)
Block header to JSON.
Definition: blockchain.cpp:85
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
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:24
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:499
uint64_t nTransactions
Definition: blockchain.cpp:994
const std::string & get_str() const
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:1160
uint64_t nDiskSize
Definition: blockchain.cpp:998
bool isNum() const
Definition: univalue.h:84
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:527
const std::string CURRENCY_UNIT
Definition: feerate.cpp:11
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
uint32_t nTime
Definition: chain.h:214
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index, or the chain tip if not provided...
Definition: blockchain.cpp:56
ThresholdState
Definition: versionbits.h:27
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 ValueFromAmount(const CAmount &amount, const int8_t units)
Definition: core_write.cpp:38
UniValue getblockcount(const JSONRPCRequest &request)
Definition: blockchain.cpp:263
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:95
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:299
UniValue waitfornewblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:307
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
uint64_t nBogoSize
Definition: blockchain.cpp:996
int threshold
Definition: versionbits.h:49
bool IsCoinBase() const
Definition: transaction.h:360
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:206
UniValue getchaintips(const JSONRPCRequest &request)
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
UniValue getmempooldescendants(const JSONRPCRequest &request)
Definition: blockchain.cpp:622
uint256 hash
Definition: blockchain.cpp:46
const std::vector< CTxIn > vin
Definition: transaction.h:287
Invalid, missing or duplicate parameter.
Definition: protocol.h:54
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: server.cpp:125
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
UniValue waitforblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:345
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:68
void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
Definition: blockchain.cpp:465
std::string ToString() const
Definition: base58.cpp:194
UniValue getblockdeltas(const JSONRPCRequest &request)
Definition: blockchain.cpp:719
indexed_transaction_set mapTx
Definition: txmempool.h:469
CAmount nTotalAmount
Definition: blockchain.cpp:999
uint256 hashSerialized
Definition: blockchain.cpp:997
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
uint256 GetBlockHash() const
Definition: chain.h:294
#define AssertLockHeld(cs)
Definition: sync.h:86
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:42
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:223
std::string name
Definition: server.h:135
std::vector< std::pair< uint256, txiter > > vTxHashes
All tx witness hashes/entries in mapTx, in random order.
Definition: txmempool.h:492
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:387
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry)
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:150
base58-encoded Raven addresses.
Definition: base58.h:103
unsigned long size()
Definition: txmempool.h:648
uint256 hashMerkleRoot
Definition: block.h:27
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
uint32_t nNonce
Definition: chain.h:216
Abstract view on the open txout dataset.
Definition: coins.h:152
unsigned int GetHeight() const
Definition: txmempool.h:107
UniValue params
Definition: server.h:45
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:76
DeploymentPos
Definition: params.h:16
An input of a transaction.
Definition: transaction.h:67
int period
Definition: versionbits.h:48
#define LOCK(cs)
Definition: sync.h:176
const uint256 & GetHash() const
Definition: transaction.h:320
const CAmount & GetFee() const
Definition: txmempool.h:103
UniValue getmempoolinfo(const JSONRPCRequest &request)
bool IsDGWActive(unsigned int nBlockNumber)
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:466
uint256 uint256S(const char *str)
Definition: uint256.h:150
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:63
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:693
int64_t nPowTargetSpacing
Definition: params.h:71
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:471
UniValue getdifficulty(const JSONRPCRequest &request)
Definition: blockchain.cpp:429
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:471
std::string GetRejectReason() const
Definition: validation.h:92
uint32_t n
Definition: transaction.h:26
const std::vector< CTxOut > vout
Definition: transaction.h:288
UniValue getchaintxstats(const JSONRPCRequest &request)
UniValue gettxoutsetinfo(const JSONRPCRequest &request)
uint256 hashMerkleRoot
Definition: chain.h:213
UniValue getblockhash(const JSONRPCRequest &request)
Definition: blockchain.cpp:815
General application defined errors.
Definition: protocol.h:49
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:660
An output of a transaction.
Definition: transaction.h:137
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:75
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:63
Invalid address or key.
Definition: protocol.h:52
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:522
UniValue getmempoolentry(const JSONRPCRequest &request)
Definition: blockchain.cpp:686
bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Parameters that influence chain consensus.
Definition: params.h:47
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
UniValue getblockhashes(const JSONRPCRequest &request)
Definition: blockchain.cpp:742
int64_t GetBlockTime() const
Definition: block.h:66
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:1357
UniValue gettxout(const JSONRPCRequest &request)
bool isNull() const
Definition: univalue.h:79
void BIP9SoftForkDescPushBack(UniValue &bip9_softforks, const std::string &name, const Consensus::Params &consensusParams, Consensus::DeploymentPos id)
int64_t GetMedianTimePast() const
Definition: chain.h:311
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:491
CCriticalSection cs
Definition: txmempool.h:468
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
UniValue mempoolToJSON(bool fVerbose)
Mempool to JSON.
Definition: blockchain.cpp:498
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:409
Database error.
Definition: protocol.h:55
#define LogPrint(category,...)
Definition: util.h:160
uint256 GetHash()
Definition: hash.h:250
uint64_t GetCountWithAncestors() const
Definition: txmempool.h:129
uint256 GetHash() const
Definition: block.cpp:14
bool fHelp
Definition: server.h:46
int32_t nVersion
block header
Definition: chain.h:212
RVN END.
Definition: validation.h:30
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:94
std::vector< CTransactionRef > vtx
Definition: block.h:77
UniValue invalidateblock(const JSONRPCRequest &request)
const_iterator end() const
Definition: streams.h:236
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:67
#define ARRAYLEN(array)
const_iterator begin() const
Definition: streams.h:234
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
UniValue getrawmempool(const JSONRPCRequest &request)
Definition: blockchain.cpp:526
UniValue savemempool(const JSONRPCRequest &request)
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:184
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:172
const CChainParams & Params()
Return the currently selected parameters.
int64_t GetTime() const
Definition: txmempool.h:106
int RPCSerializationFlags()
Definition: server.cpp:559
const CTransaction & GetTx() const
Definition: txmempool.h:101
const UniValue & get_obj() const
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:454
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:840
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
uint160 addressHash
Definition: spentindex.h:46
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:30
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:448
std::string GetHex() const
Definition: uint256.cpp:22
sph_u32 low
Definition: keccak.c:370
160-bit opaque blob.
Definition: uint256.h:112
const UniValue NullUniValue
Definition: univalue.cpp:15
int elapsed
Definition: versionbits.h:50
bool error(const char *fmt, const Args &... args)
Definition: util.h:168
iterator begin()
Definition: prevector.h:291
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:150
bool possible
Definition: versionbits.h:52
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:23
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:231
CAmount satoshis
Definition: spentindex.h:44
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:297
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
Definition: core_write.cpp:252
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:55
std::string GetHex() const
size_t size() const
Definition: univalue.h:70
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:185
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:61
std::string EntryDescriptionString()
Definition: blockchain.cpp:446
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.
CCoinsViewDB * pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:222
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:84
full block available in blk*.dat
Definition: chain.h:156
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
UniValue blockToJSON(const CBlock &block, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
Definition: blockchain.cpp:219
COutPoint prevout
Definition: transaction.h:70
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:52
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:725
int32_t nVersion
Definition: block.h:25
bool IsPayToPublicKeyHash() const
Definition: script.cpp:210
BlockMap mapBlockIndex
Definition: validation.cpp:74
uint32_t nBits
Definition: chain.h:215
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:42
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:201
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:66
uint32_t nBits
Definition: block.h:29
uint256 hash
Definition: transaction.h:25