Fabcoin Core  0.16.2
P2P Digital Currency
blockchain.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <rpc/blockchain.h>
7 
8 #include <amount.h>
9 #include <base58.h>
10 #include <chain.h>
11 #include <chainparams.h>
12 #include <checkpoints.h>
13 #include <coins.h>
14 #include <consensus/validation.h>
15 #include <consensus/params.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 <streams.h>
23 #include <sync.h>
24 #include <txdb.h>
25 #include <txmempool.h>
26 #include <util.h>
27 #include <utilstrencodings.h>
28 #include <hash.h>
29 #include <libdevcore/CommonData.h>
30 #include <txdb.h>
31 
32 #include <stdint.h>
33 
34 #include <univalue.h>
35 
36 #include <boost/thread/thread.hpp> // boost::thread::interrupt
37 
38 #include <mutex>
39 #include <condition_variable>
40 
41 
42 
43 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
44 void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
45 
46 double GetDifficultyINTERNAL(const CBlockIndex* blockindex)
47 {
48  // Floating point number that is a multiple of the minimum difficulty,
49  // minimum difficulty = 1.0.
50 
51  if (blockindex == nullptr)
52  {
53  if (chainActive.Tip() == nullptr)
54  return 1.0;
55  else
56  blockindex = chainActive.Tip();
57  }
58 
59  uint32_t bits = blockindex->nBits;
60 
61  uint32_t powLimit =
62  UintToArith256(Params().GetConsensus().powLimit).GetCompact();
63  int nShift = (bits >> 24) & 0xff;
64  int nShiftAmount = (powLimit >> 24) & 0xff;
65 
66  double dDiff =
67  (double)(powLimit & 0x00ffffff) /
68  (double)(bits & 0x00ffffff);
69 
70  while (nShift < nShiftAmount)
71  {
72  dDiff *= 256.0;
73  nShift++;
74  }
75  while (nShift > nShiftAmount)
76  {
77  dDiff /= 256.0;
78  nShift--;
79  }
80 
81  return dDiff;
82 }
83 
84 double GetDifficultyBitcoin(const CBlockIndex* blockindex)
85 {
86  int nShift = (blockindex->nBits >> 24) & 0xff;
87 
88  double dDiff =
89  (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
90 
91  while (nShift < 29)
92  {
93  dDiff *= 256.0;
94  nShift++;
95  }
96  while (nShift > 29)
97  {
98  dDiff /= 256.0;
99  nShift--;
100  }
101 
102  return dDiff;
103 }
104 
105 double GetDifficulty(const CBlockIndex* blockindex)
106 {
107  if (blockindex == nullptr)
108  {
109  if (chainActive.Tip() == nullptr)
110  return 1.0;
111  else
112  blockindex = chainActive.Tip();
113  }
114 
115  if ((uint32_t) blockindex->nHeight >= Params().GetConsensus().FABHeight)
116  {
117  return GetDifficultyINTERNAL(blockindex);
118  }
119  else
120  {
121  return GetDifficultyBitcoin(blockindex);
122  }
123 }
124 
126 {
127 
128  UniValue result(UniValue::VOBJ);
129  result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
130  int confirmations = -1;
131  // Only report confirmations if the block is on the main chain
132  if (chainActive.Contains(blockindex))
133  confirmations = chainActive.Height() - blockindex->nHeight + 1;
134 
135  bool contract_format = blockindex->IsSupportContract();
136  bool legacy_format = blockindex->IsLegacyFormat() ;
137 
138  result.push_back(Pair("confirmations", confirmations));
139  result.push_back(Pair("height", blockindex->nHeight));
140 
141  result.push_back(Pair("version", blockindex->nVersion));
142  result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
143  result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
144 
145  if ( contract_format ) {
146  result.push_back(Pair("hashStateRoot", blockindex->hashStateRoot.GetHex())); // fasc
147  result.push_back(Pair("hashUTXORoot", blockindex->hashUTXORoot.GetHex())); // fasc
148  }
149 
150  result.push_back(Pair("time", (int64_t)blockindex->nTime));
151  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
152 
153  if ( legacy_format ){
154  result.push_back(Pair("nonce", (uint64_t)((uint32_t)blockindex->nNonce.GetUint64(0))));
155  }
156  else {
157  result.push_back(Pair("nonce", blockindex->nNonce.GetHex()));
158  result.push_back(Pair("solution", HexStr(blockindex->nSolution)));
159  }
160  result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
161 
162  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
163  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
164 
165  if (blockindex->pprev)
166  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
167  CBlockIndex *pnext = chainActive.Next(blockindex);
168 
169  if (pnext)
170  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
171 
172  return result;
173 }
174 
175 UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails)
176 {
177  UniValue result(UniValue::VOBJ);
178  result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
179  int confirmations = -1;
180  // Only report confirmations if the block is on the main chain
181  if (chainActive.Contains(blockindex))
182  confirmations = chainActive.Height() - blockindex->nHeight + 1;
183  result.push_back(Pair("confirmations", confirmations));
184  const Consensus::Params& consensusParams = Params().GetConsensus();
185  result.push_back(
186  Pair("strippedsize",
187  (int)::GetSerializeSize(block, SER_NETWORK,
188  PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS )));
189  result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION )));
190  result.push_back(Pair("weight", (int)::GetBlockWeight(block, consensusParams)));
191  result.push_back(Pair("height", blockindex->nHeight));
192  result.push_back(Pair("version", block.nVersion));
193  result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
194  result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
195 
196  bool contract_format = blockindex->IsSupportContract();
197  bool legacy_format = blockindex->IsLegacyFormat() ;
198  if ( contract_format ) {
199  result.push_back(Pair("hashStateRoot", block.hashStateRoot.GetHex())); // fasc
200  result.push_back(Pair("hashUTXORoot", block.hashUTXORoot.GetHex())); // fasc
201  }
203  for(const auto& tx : block.vtx)
204  {
205  if(txDetails)
206  {
207  UniValue objTx(UniValue::VOBJ);
208  TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());
209  txs.push_back(objTx);
210  }
211  else
212  txs.push_back(tx->GetHash().GetHex());
213  }
214  result.push_back(Pair("tx", txs));
215  result.push_back(Pair("time", block.GetBlockTime()));
216  result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
217 
218  if ( legacy_format )
219  result.push_back(Pair("nonce", (uint64_t)((uint32_t)block.nNonce.GetUint64(0))));
220  else result.push_back(Pair("nonce", block.nNonce.GetHex()));
221 
222  result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
223  result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
224  result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
225 
226  if (blockindex->pprev)
227  result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
228  CBlockIndex *pnext = chainActive.Next(blockindex);
229  if (pnext)
230  result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
231  return result;
232 }
235 {
236  UniValue result(UniValue::VOBJ);
237  result.push_back(Pair("gasUsed", CAmount(exRes.gasUsed)));
238  std::stringstream ss;
239  ss << exRes.excepted;
240  result.push_back(Pair("excepted", ss.str()));
241  result.push_back(Pair("newAddress", exRes.newAddress.hex()));
242  result.push_back(Pair("output", HexStr(exRes.output)));
243  result.push_back(Pair("codeDeposit", static_cast<int32_t>(exRes.codeDeposit)));
244  result.push_back(Pair("gasRefunded", CAmount(exRes.gasRefunded)));
245  result.push_back(Pair("depositSize", static_cast<int32_t>(exRes.depositSize)));
246  result.push_back(Pair("gasForDeposit", CAmount(exRes.gasForDeposit)));
247  return result;
248 }
249 
251 {
252  UniValue result(UniValue::VOBJ);
253  result.push_back(Pair("stateRoot", txRec.stateRoot().hex()));
254  result.push_back(Pair("gasUsed", CAmount(txRec.gasUsed())));
255  result.push_back(Pair("bloom", txRec.bloom().hex()));
256  UniValue logEntries(UniValue::VARR);
257  dev::eth::LogEntries logs = txRec.log();
258  for(dev::eth::LogEntry log : logs){
259  UniValue logEntrie(UniValue::VOBJ);
260  logEntrie.push_back(Pair("address", log.address.hex()));
261  UniValue topics(UniValue::VARR);
262  for(dev::h256 l : log.topics){
263  topics.push_back(l.hex());
264  }
265  logEntrie.push_back(Pair("topics", topics));
266  logEntrie.push_back(Pair("data", HexStr(log.data)));
267  logEntries.push_back(logEntrie);
268  }
269  result.push_back(Pair("log", logEntries));
270  return result;
271 }
273 
275 {
276  if (request.fHelp || request.params.size() != 0)
277  throw std::runtime_error(
278  "getblockcount\n"
279  "\nReturns the number of blocks in the longest blockchain.\n"
280  "\nResult:\n"
281  "n (numeric) The current block count\n"
282  "\nExamples:\n"
283  + HelpExampleCli("getblockcount", "")
284  + HelpExampleRpc("getblockcount", "")
285  );
286 
287  LOCK(cs_main);
288  return chainActive.Height();
289 }
290 
292 {
293  if (request.fHelp || request.params.size() != 0)
294  throw std::runtime_error(
295  "getbestblockhash\n"
296  "\nReturns the hash of the best (tip) block in the longest blockchain.\n"
297  "\nResult:\n"
298  "\"hex\" (string) the block hash hex encoded\n"
299  "\nExamples:\n"
300  + HelpExampleCli("getbestblockhash", "")
301  + HelpExampleRpc("getbestblockhash", "")
302  );
303 
304  LOCK(cs_main);
305  return chainActive.Tip()->GetBlockHash().GetHex();
306 }
307 
308 void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
309 {
310  if(pindex) {
311  std::lock_guard<std::mutex> lock(cs_blockchange);
312  latestblock.hash = pindex->GetBlockHash();
313  latestblock.height = pindex->nHeight;
314  }
315  cond_blockchange.notify_all();
316 }
317 
319 {
320  if (request.fHelp || request.params.size() > 1)
321  throw std::runtime_error(
322  "waitfornewblock (timeout)\n"
323  "\nWaits for a specific new block and returns useful info about it.\n"
324  "\nReturns the current block on timeout or exit.\n"
325  "\nArguments:\n"
326  "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
327  "\nResult:\n"
328  "{ (json object)\n"
329  " \"hash\" : { (string) The blockhash\n"
330  " \"height\" : { (int) Block height\n"
331  "}\n"
332  "\nExamples:\n"
333  + HelpExampleCli("waitfornewblock", "1000")
334  + HelpExampleRpc("waitfornewblock", "1000")
335  );
336  int timeout = 0;
337  if (!request.params[0].isNull())
338  timeout = request.params[0].get_int();
339 
340  CUpdatedBlock block;
341  {
342  std::unique_lock<std::mutex> lock(cs_blockchange);
343  block = latestblock;
344  if(timeout)
345  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
346  else
347  cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
348  block = latestblock;
349  }
351  ret.push_back(Pair("hash", block.hash.GetHex()));
352  ret.push_back(Pair("height", block.height));
353  return ret;
354 }
355 
357 {
358  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
359  throw std::runtime_error(
360  "waitforblock <blockhash> (timeout)\n"
361  "\nWaits for a specific new block and returns useful info about it.\n"
362  "\nReturns the current block on timeout or exit.\n"
363  "\nArguments:\n"
364  "1. \"blockhash\" (required, string) Block hash to wait for.\n"
365  "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
366  "\nResult:\n"
367  "{ (json object)\n"
368  " \"hash\" : { (string) The blockhash\n"
369  " \"height\" : { (int) Block height\n"
370  "}\n"
371  "\nExamples:\n"
372  + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
373  + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
374  );
375  int timeout = 0;
376 
377  uint256 hash = uint256S(request.params[0].get_str());
378 
379  if (!request.params[1].isNull())
380  timeout = request.params[1].get_int();
381 
382  CUpdatedBlock block;
383  {
384  std::unique_lock<std::mutex> lock(cs_blockchange);
385  if(timeout)
386  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
387  else
388  cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
389  block = latestblock;
390  }
391 
393  ret.push_back(Pair("hash", block.hash.GetHex()));
394  ret.push_back(Pair("height", block.height));
395  return ret;
396 }
397 
399 {
400  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
401  throw std::runtime_error(
402  "waitforblockheight <height> (timeout)\n"
403  "\nWaits for (at least) block height and returns the height and hash\n"
404  "of the current tip.\n"
405  "\nReturns the current block on timeout or exit.\n"
406  "\nArguments:\n"
407  "1. height (required, int) Block height to wait for (int)\n"
408  "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
409  "\nResult:\n"
410  "{ (json object)\n"
411  " \"hash\" : { (string) The blockhash\n"
412  " \"height\" : { (int) Block height\n"
413  "}\n"
414  "\nExamples:\n"
415  + HelpExampleCli("waitforblockheight", "\"100\", 1000")
416  + HelpExampleRpc("waitforblockheight", "\"100\", 1000")
417  );
418  int timeout = 0;
419 
420  int height = request.params[0].get_int();
421 
422  if (!request.params[1].isNull())
423  timeout = request.params[1].get_int();
424 
425  CUpdatedBlock block;
426  {
427  std::unique_lock<std::mutex> lock(cs_blockchange);
428  if(timeout)
429  cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
430  else
431  cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
432  block = latestblock;
433  }
435  ret.push_back(Pair("hash", block.hash.GetHex()));
436  ret.push_back(Pair("height", block.height));
437  return ret;
438 }
439 
441 {
442  if (request.fHelp || request.params.size() != 0)
443  throw std::runtime_error(
444  "getdifficulty\n"
445  "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
446  "\nResult:\n"
447  "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
448  "\nExamples:\n"
449  + HelpExampleCli("getdifficulty", "")
450  + HelpExampleRpc("getdifficulty", "")
451  );
452 
453  LOCK(cs_main);
454  return GetDifficulty();
455 }
456 
458 {
459  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"
460  " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
461  " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
462  " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
463  " \"height\" : n, (numeric) block height when transaction entered pool\n"
464  " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
465  " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n"
466  " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
467  " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
468  " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n"
469  " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
470  " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
471  " \"transactionid\", (string) parent transaction id\n"
472  " ... ]\n";
473 }
474 
476 {
478 
479  info.push_back(Pair("size", (int)e.GetTxSize()));
480  info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
481  info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
482  info.push_back(Pair("time", e.GetTime()));
483  info.push_back(Pair("height", (int)e.GetHeight()));
484  info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
485  info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
486  info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
487  info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
488  info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
489  info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
490  const CTransaction& tx = e.GetTx();
491  std::set<std::string> setDepends;
492  for (const CTxIn& txin : tx.vin)
493  {
494  if (mempool.exists(txin.prevout.hash))
495  setDepends.insert(txin.prevout.hash.ToString());
496  }
497 
498  UniValue depends(UniValue::VARR);
499  for (const std::string& dep : setDepends)
500  {
501  depends.push_back(dep);
502  }
503 
504  info.push_back(Pair("depends", depends));
505 }
506 
507 UniValue mempoolToJSON(bool fVerbose)
508 {
509  if (fVerbose)
510  {
511  LOCK(mempool.cs);
513  for (const CTxMemPoolEntry& e : mempool.mapTx)
514  {
515  const uint256& hash = e.GetTx().GetHash();
516  UniValue info(UniValue::VOBJ);
517  entryToJSON(info, e);
518  o.push_back(Pair(hash.ToString(), info));
519  }
520  return o;
521  }
522  else
523  {
524  std::vector<uint256> vtxid;
525  mempool.queryHashes(vtxid);
526 
528  for (const uint256& hash : vtxid)
529  a.push_back(hash.ToString());
530 
531  return a;
532  }
533 }
534 
536 {
537  if (request.fHelp || request.params.size() > 1)
538  throw std::runtime_error(
539  "getrawmempool ( verbose )\n"
540  "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
541  "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n"
542  "\nArguments:\n"
543  "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
544  "\nResult: (for verbose = false):\n"
545  "[ (json array of string)\n"
546  " \"transactionid\" (string) The transaction id\n"
547  " ,...\n"
548  "]\n"
549  "\nResult: (for verbose = true):\n"
550  "{ (json object)\n"
551  " \"transactionid\" : { (json object)\n"
553  + " }, ...\n"
554  "}\n"
555  "\nExamples:\n"
556  + HelpExampleCli("getrawmempool", "true")
557  + HelpExampleRpc("getrawmempool", "true")
558  );
559 
560  bool fVerbose = false;
561  if (!request.params[0].isNull())
562  fVerbose = request.params[0].get_bool();
563 
564  return mempoolToJSON(fVerbose);
565 }
566 
568 {
569  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
570  throw std::runtime_error(
571  "getmempoolancestors txid (verbose)\n"
572  "\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
573  "\nArguments:\n"
574  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
575  "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
576  "\nResult (for verbose=false):\n"
577  "[ (json array of strings)\n"
578  " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
579  " ,...\n"
580  "]\n"
581  "\nResult (for verbose=true):\n"
582  "{ (json object)\n"
583  " \"transactionid\" : { (json object)\n"
585  + " }, ...\n"
586  "}\n"
587  "\nExamples:\n"
588  + HelpExampleCli("getmempoolancestors", "\"mytxid\"")
589  + HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
590  );
591  }
592 
593  bool fVerbose = false;
594  if (!request.params[1].isNull())
595  fVerbose = request.params[1].get_bool();
596 
597  uint256 hash = ParseHashV(request.params[0], "parameter 1");
598 
599  LOCK(mempool.cs);
600 
601  CTxMemPool::txiter it = mempool.mapTx.find(hash);
602  if (it == mempool.mapTx.end()) {
603  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
604  }
605 
606  CTxMemPool::setEntries setAncestors;
607  uint64_t noLimit = std::numeric_limits<uint64_t>::max();
608  std::string dummy;
609  mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
610 
611  if (!fVerbose) {
613  for (CTxMemPool::txiter ancestorIt : setAncestors) {
614  o.push_back(ancestorIt->GetTx().GetHash().ToString());
615  }
616 
617  return o;
618  } else {
620  for (CTxMemPool::txiter ancestorIt : setAncestors) {
621  const CTxMemPoolEntry &e = *ancestorIt;
622  const uint256& _hash = e.GetTx().GetHash();
623  UniValue info(UniValue::VOBJ);
624  entryToJSON(info, e);
625  o.push_back(Pair(_hash.ToString(), info));
626  }
627  return o;
628  }
629 }
630 
632 {
633  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
634  throw std::runtime_error(
635  "getmempooldescendants txid (verbose)\n"
636  "\nIf txid is in the mempool, returns all in-mempool descendants.\n"
637  "\nArguments:\n"
638  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
639  "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
640  "\nResult (for verbose=false):\n"
641  "[ (json array of strings)\n"
642  " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
643  " ,...\n"
644  "]\n"
645  "\nResult (for verbose=true):\n"
646  "{ (json object)\n"
647  " \"transactionid\" : { (json object)\n"
649  + " }, ...\n"
650  "}\n"
651  "\nExamples:\n"
652  + HelpExampleCli("getmempooldescendants", "\"mytxid\"")
653  + HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
654  );
655  }
656 
657  bool fVerbose = false;
658  if (!request.params[1].isNull())
659  fVerbose = request.params[1].get_bool();
660 
661  uint256 hash = ParseHashV(request.params[0], "parameter 1");
662 
663  LOCK(mempool.cs);
664 
665  CTxMemPool::txiter it = mempool.mapTx.find(hash);
666  if (it == mempool.mapTx.end()) {
667  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
668  }
669 
670  CTxMemPool::setEntries setDescendants;
671  mempool.CalculateDescendants(it, setDescendants);
672  // CTxMemPool::CalculateDescendants will include the given tx
673  setDescendants.erase(it);
674 
675  if (!fVerbose) {
677  for (CTxMemPool::txiter descendantIt : setDescendants) {
678  o.push_back(descendantIt->GetTx().GetHash().ToString());
679  }
680 
681  return o;
682  } else {
684  for (CTxMemPool::txiter descendantIt : setDescendants) {
685  const CTxMemPoolEntry &e = *descendantIt;
686  const uint256& _hash = e.GetTx().GetHash();
687  UniValue info(UniValue::VOBJ);
688  entryToJSON(info, e);
689  o.push_back(Pair(_hash.ToString(), info));
690  }
691  return o;
692  }
693 }
694 
696 {
697  if (request.fHelp || request.params.size() != 1) {
698  throw std::runtime_error(
699  "getmempoolentry txid\n"
700  "\nReturns mempool data for given transaction\n"
701  "\nArguments:\n"
702  "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
703  "\nResult:\n"
704  "{ (json object)\n"
706  + "}\n"
707  "\nExamples:\n"
708  + HelpExampleCli("getmempoolentry", "\"mytxid\"")
709  + HelpExampleRpc("getmempoolentry", "\"mytxid\"")
710  );
711  }
712 
713  uint256 hash = ParseHashV(request.params[0], "parameter 1");
714 
715  LOCK(mempool.cs);
716 
717  CTxMemPool::txiter it = mempool.mapTx.find(hash);
718  if (it == mempool.mapTx.end()) {
719  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
720  }
721 
722  const CTxMemPoolEntry &e = *it;
723  UniValue info(UniValue::VOBJ);
724  entryToJSON(info, e);
725  return info;
726 }
727 
729 {
730  if (request.fHelp || request.params.size() != 1)
731  throw std::runtime_error(
732  "getblockhash height\n"
733  "\nReturns hash of block in best-block-chain at height provided.\n"
734  "\nArguments:\n"
735  "1. height (numeric, required) The height index\n"
736  "\nResult:\n"
737  "\"hash\" (string) The block hash\n"
738  "\nExamples:\n"
739  + HelpExampleCli("getblockhash", "1000")
740  + HelpExampleRpc("getblockhash", "1000")
741  );
742 
743  LOCK(cs_main);
744 
745  int nHeight = request.params[0].get_int();
746  if (nHeight < 0 || nHeight > chainActive.Height())
747  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
748 
749  CBlockIndex* pblockindex = chainActive[nHeight];
750  return pblockindex->GetBlockHash().GetHex();
751 }
752 
754 {
755  if (request.fHelp || request.params.size() < 1)
756  throw std::runtime_error(
757  "getaccountinfo \"address\"\n"
758  "\nArgument:\n"
759  "1. \"address\" (string, required) The account address\n"
760  );
761 
762  LOCK(cs_main);
763 
764  std::string strAddr = request.params[0].get_str();
765  if(strAddr.size() != 40 || !CheckHex(strAddr))
766  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect address");
767 
768  dev::Address addrAccount(strAddr);
769  if(!globalState->addressInUse(addrAccount))
770  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Address does not exist");
771 
772  UniValue result(UniValue::VOBJ);
773 
774  result.push_back(Pair("address", strAddr));
775  result.push_back(Pair("balance", CAmount(globalState->balance(addrAccount))));
776  std::vector<uint8_t> code(globalState->code(addrAccount));
777  auto storage(globalState->storage(addrAccount));
778 
779  UniValue storageUV(UniValue::VOBJ);
780  for (auto j: storage)
781  {
783  e.push_back(Pair(dev::toHex(j.second.first), dev::toHex(j.second.second)));
784  storageUV.push_back(Pair(j.first.hex(), e));
785  }
786 
787  result.push_back(Pair("storage", storageUV));
788 
789  result.push_back(Pair("code", HexStr(code.begin(), code.end())));
790 
791  std::unordered_map<dev::Address, Vin> vins = globalState->vins();
792  if(vins.count(addrAccount)){
794  valtype vchHash(vins[addrAccount].hash.asBytes());
795  vin.push_back(Pair("hash", HexStr(vchHash.rbegin(), vchHash.rend())));
796  vin.push_back(Pair("nVout", uint64_t(vins[addrAccount].nVout)));
797  vin.push_back(Pair("value", uint64_t(vins[addrAccount].value)));
798  result.push_back(Pair("vin", vin));
799  }
800  return result;
801 }
802 
804 {
805  if (request.fHelp || request.params.size() < 1)
806  throw std::runtime_error(
807  "getstorage \"address\"\n"
808  "\nArgument:\n"
809  "1. \"address\" (string, required) The address to get the storage from\n"
810  "2. \"blockNum\" (string, optional) Number of block to get state from, \"latest\" keyword supported. Latest if not passed.\n"
811  "3. \"index\" (number, optional) Zero-based index position of the storage\n"
812  );
813 
814  LOCK(cs_main);
815 
816  std::string strAddr = request.params[0].get_str();
817  if(strAddr.size() != 40 || !CheckHex(strAddr))
818  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect address");
819 
821  if (request.params.size() > 1)
822  {
823  if (request.params[1].isNum())
824  {
825  auto blockNum = request.params[1].get_int();
826  if((blockNum < 0 && blockNum != -1) || blockNum > chainActive.Height())
827  throw JSONRPCError(RPC_INVALID_PARAMS, "Incorrect block number");
828 
829  if(blockNum != -1)
830  ts.SetRoot(uintToh256(chainActive[blockNum]->hashStateRoot), uintToh256(chainActive[blockNum]->hashUTXORoot));
831 
832  } else {
833  throw JSONRPCError(RPC_INVALID_PARAMS, "Incorrect block number");
834  }
835  }
836 
837  dev::Address addrAccount(strAddr);
838  if(!globalState->addressInUse(addrAccount))
839  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Address does not exist");
840 
841  UniValue result(UniValue::VOBJ);
842 
843  bool onlyIndex = request.params.size() > 2;
844  unsigned index = 0;
845  if (onlyIndex)
846  index = request.params[2].get_int();
847 
848  auto storage(globalState->storage(addrAccount));
849 
850  if (onlyIndex)
851  {
852  if (index >= storage.size())
853  {
854  std::ostringstream stringStream;
855  stringStream << "Storage size: " << storage.size() << " got index: " << index;
856  throw JSONRPCError(RPC_INVALID_PARAMS, stringStream.str());
857  }
858  auto elem = std::next(storage.begin(), index);
860 
861  storage = {{elem->first, {elem->second.first, elem->second.second}}};
862  }
863  for (const auto& j: storage)
864  {
866  e.push_back(Pair(dev::toHex(j.second.first), dev::toHex(j.second.second)));
867  result.push_back(Pair(j.first.hex(), e));
868  }
869  return result;
870 }
872 {
873  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
874  throw std::runtime_error(
875  "getblockheader \"hash\" ( verbose legacy no_contract)\n"
876  "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
877  "If verbose is true, returns an Object with information about blockheader <hash>.\n"
878  "\nArguments:\n"
879  "1. \"hash\" (string, required) The block hash\n"
880  "2. \"verbose\" (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
881  "3. \"legacy \" (boolean, optional, default=false) indicates if the block should be in legacy format\n"
882  "4. \"no_contract\" (boolean, optional, default=false) indicates if the block should be in non-contract format\n"
883  "\nResult (for verbose = true):\n"
884  "{\n"
885  " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
886  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
887  " \"height\" : n, (numeric) The block height or index\n"
888  " \"version\" : n, (numeric) The block version\n"
889  " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
890  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
891  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
892  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
893  " \"nonce\" : n, (numeric) The nonce\n"
894  " \"bits\" : \"1d00ffff\", (string) The bits\n"
895  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
896  " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
897  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
898  " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
899  "}\n"
900  "\nResult (for verbose=false):\n"
901  "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
902  "\nExamples:\n"
903  + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
904  + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
905  );
906 
907  LOCK(cs_main);
908 
909  std::string strHash = request.params[0].get_str();
910  uint256 hash(uint256S(strHash));
911 
912  bool fVerbose = true;
913  if (!request.params[1].isNull())
914  fVerbose = request.params[1].get_bool();
915 
916  if (mapBlockIndex.count(hash) == 0)
917  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
918 
919  CBlockIndex* pblockindex = mapBlockIndex[hash];
920 
921  if (!fVerbose)
922  {
923  CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION );
924  ssBlock << pblockindex->GetBlockHeader();
925  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
926 
927  return strHex;
928  }
929 
930  return blockheaderToJSON(pblockindex);
931 }
932 
934 {
935  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
936  throw std::runtime_error(
937  "getblock \"blockhash\" ( verbosity legacy no_contract) \n"
938  "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
939  "If verbosity is 1, returns an Object with information about block <hash>.\n"
940  "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
941  "\nArguments:\n"
942  "1. \"blockhash\" (string, required) The block hash\n"
943  "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"
944  "3. \"legacy\" (boolean, optional, default=false) indicates if the block should be in legacy format\n"
945  "4. \"no_contract\" (boolean, optional, default=false) indicates if the block should be in non-contract format\n"
946  "\nResult (for verbosity = 0):\n"
947  "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
948  "\nResult (for verbosity = 1):\n"
949  "{\n"
950  " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
951  " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
952  " \"size\" : n, (numeric) The block size\n"
953  " \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
954  " \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
955  " \"height\" : n, (numeric) The block height or index\n"
956  " \"version\" : n, (numeric) The block version\n"
957  " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
958  " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
959  " \"tx\" : [ (array of string) The transaction ids\n"
960  " \"transactionid\" (string) The transaction id\n"
961  " ,...\n"
962  " ],\n"
963  " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
964  " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
965  " \"nonce\" : n, (numeric) The nonce\n"
966  " \"bits\" : \"1d00ffff\", (string) The bits\n"
967  " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
968  " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
969  " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
970  " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
971  "}\n"
972  "\nResult (for verbosity = 2):\n"
973  "{\n"
974  " ..., Same output as verbosity = 1.\n"
975  " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
976  " ,...\n"
977  " ],\n"
978  " ,... Same output as verbosity = 1.\n"
979  "}\n"
980  "\nExamples:\n"
981  + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
982  + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
983  );
984 
985  LOCK(cs_main);
986 
987  std::string strHash = request.params[0].get_str();
988  uint256 hash(uint256S(strHash));
989 
990  int verbosity = 1;
991  if (!request.params[1].isNull()) {
992  if(request.params[1].isNum())
993  verbosity = request.params[1].get_int();
994  else
995  verbosity = request.params[1].get_bool() ? 1 : 0;
996  }
997 
998  if (mapBlockIndex.count(hash) == 0)
999  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1000 
1001  CBlock block;
1002  CBlockIndex* pblockindex = mapBlockIndex[hash];
1003 
1004  if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
1005  throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
1006 
1007  if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
1008  // Block not found on disk. This could be because we have the block
1009  // header in our index but don't have the block (for example if a
1010  // non-whitelisted node sends us an unrequested long chain of valid
1011  // blocks, we add the headers to our index, but don't accept the
1012  // block).
1013  throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
1014 
1015  LogPrintf("debug getblock()=%s", block.ToString());
1016 
1017  if (verbosity <= 0)
1018  {
1019  CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
1020  ssBlock << block;
1021  std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
1022  return strHex;
1023  }
1024 
1025  return blockToJSON(block, pblockindex, verbosity >= 2);
1026 }
1029 {
1030  if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
1031  throw std::runtime_error(
1032  "callcontract \"address\" \"data\" ( address gasLimit )\n"
1033  "\nArgument:\n"
1034  "1. \"address\" (string, required) The account address\n"
1035  "2. \"data\" (string, required) The data hex string\n"
1036  "3. address (string, optional) The sender address hex string\n"
1037  "4. gasLimit (numeric, optional) The gas limit for executing the contract\n"
1038  );
1039 
1040  LOCK(cs_main);
1041 
1042  std::string strAddr = request.params[0].get_str();
1043  std::string data = request.params[1].get_str();
1044 
1046  throw JSONRPCError(RPC_METHOD_NOT_FOUND, std::string ("This method can only be used after fasc fork, block ") + std::to_string(Params().GetConsensus().ContractHeight ));
1047 
1048  if(data.size() % 2 != 0 || !CheckHex(data))
1049  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid data (data not hex)");
1050 
1051  if(strAddr.size() != 40 || !CheckHex(strAddr))
1052  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect address");
1053 
1054  dev::Address addrAccount(strAddr);
1055  if(!globalState->addressInUse(addrAccount))
1056  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Address does not exist");
1057 
1058  dev::Address senderAddress;
1059  if(request.params.size() >= 3){
1060  CFabcoinAddress fascSenderAddress(request.params[2].get_str());
1061  if(fascSenderAddress.IsValid()){
1062  CKeyID keyid;
1063  fascSenderAddress.GetKeyID(keyid);
1064  senderAddress = dev::Address(HexStr(valtype(keyid.begin(),keyid.end())));
1065  }else{
1066  senderAddress = dev::Address(request.params[2].get_str());
1067  }
1068  }
1069  uint64_t gasLimit = request.params.size() >= 4 ? request.params[3].get_int64() : 0;
1070 
1071  std::vector<ResultExecute> execResults = CallContract(addrAccount, ParseHex(data), senderAddress, gasLimit);
1072 
1073  if(fRecordLogOpcodes){
1074  writeVMlog(execResults);
1075  }
1076 
1077  UniValue result(UniValue::VOBJ);
1078  result.push_back(Pair("address", strAddr));
1079  result.push_back(Pair("executionResult", executionResultToJSON(execResults[0].execRes)));
1080  result.push_back(Pair("transactionReceipt", transactionReceiptToJSON(execResults[0].txRec)));
1081 
1082  return result;
1083 }
1084 
1085 void assignJSON(UniValue& entry, const TransactionReceiptInfo& resExec) {
1086  entry.push_back(Pair("blockHash", resExec.blockHash.GetHex()));
1087  entry.push_back(Pair("blockNumber", uint64_t(resExec.blockNumber)));
1088  entry.push_back(Pair("transactionHash", resExec.transactionHash.GetHex()));
1089  entry.push_back(
1090  Pair("transactionIndex", uint64_t(resExec.transactionIndex)));
1091  entry.push_back(Pair("from", resExec.from.hex()));
1092  entry.push_back(Pair("to", resExec.to.hex()));
1093  entry.push_back(
1094  Pair("cumulativeGasUsed", CAmount(resExec.cumulativeGasUsed)));
1095  entry.push_back(Pair("gasUsed", CAmount(resExec.gasUsed)));
1096  entry.push_back(Pair("contractAddress", resExec.contractAddress.hex()));
1097  std::stringstream ss;
1098  ss << resExec.excepted;
1099  entry.push_back(Pair("excepted",ss.str()));
1100 }
1101 
1102 void assignJSON(UniValue& logEntry, const dev::eth::LogEntry& log,
1103  bool includeAddress) {
1104  if (includeAddress) {
1105  logEntry.push_back(Pair("address", log.address.hex()));
1106  }
1107 
1108  UniValue topics(UniValue::VARR);
1109  for (dev::h256 hash : log.topics) {
1110  topics.push_back(hash.hex());
1111  }
1112  logEntry.push_back(Pair("topics", topics));
1113  logEntry.push_back(Pair("data", HexStr(log.data)));
1114 }
1115 
1117  assignJSON(entry, resExec);
1118 
1119  const auto& logs = resExec.logs;
1120  UniValue logEntries(UniValue::VARR);
1121  for(const auto&log : logs){
1122  UniValue logEntry(UniValue::VOBJ);
1123  assignJSON(logEntry, log, true);
1124  logEntries.push_back(logEntry);
1125  }
1126  entry.push_back(Pair("log", logEntries));
1127 }
1128 
1129 size_t parseUInt(const UniValue& val, size_t defaultVal) {
1130  if (val.isNull()) {
1131  return defaultVal;
1132  } else {
1133  int n = val.get_int();
1134  if (n < 0) {
1135  throw JSONRPCError(RPC_INVALID_PARAMS, "Expects unsigned integer");
1136  }
1137 
1138  return n;
1139  }
1140 }
1141 
1142 int parseBlockHeight(const UniValue& val) {
1143  if (val.isStr()) {
1144  auto blockKey = val.get_str();
1145 
1146  if (blockKey == "latest") {
1147  return latestblock.height;
1148  } else {
1149  throw JSONRPCError(RPC_INVALID_PARAMS, "invalid block number");
1150  }
1151  }
1152 
1153  if (val.isNum()) {
1154  int blockHeight = val.get_int();
1155 
1156  if (blockHeight < 0) {
1157  return latestblock.height;
1158  }
1159 
1160  return blockHeight;
1161  }
1162 
1163  throw JSONRPCError(RPC_INVALID_PARAMS, "invalid block number");
1164 }
1165 
1166 int parseBlockHeight(const UniValue& val, int defaultVal) {
1167  if (val.isNull()) {
1168  return defaultVal;
1169  } else {
1170  return parseBlockHeight(val);
1171  }
1172 }
1173 
1175  if (!val.isStr()) {
1176  throw JSONRPCError(RPC_INVALID_PARAMS, "Invalid hex 160");
1177  }
1178 
1179  auto addrStr = val.get_str();
1180 
1181  if (addrStr.length() != 40 || !CheckHex(addrStr)) {
1182  throw JSONRPCError(RPC_INVALID_PARAMS, "Invalid hex 160 string");
1183  }
1184  return dev::h160(addrStr);
1185 }
1186 
1187 void parseParam(const UniValue& val, std::vector<dev::h160> &h160s) {
1188  if (val.isNull()) {
1189  return;
1190  }
1191 
1192  // Treat a string as an array of length 1
1193  if (val.isStr()) {
1194  h160s.push_back(parseParamH160(val.get_str()));
1195  return;
1196  }
1197 
1198  if (!val.isArray()) {
1199  throw JSONRPCError(RPC_INVALID_PARAMS, "Expect an array of hex 160 strings");
1200  }
1201 
1202  auto vals = val.getValues();
1203  h160s.resize(vals.size());
1204 
1205  std::transform(vals.begin(), vals.end(), h160s.begin(), [](UniValue val) -> dev::h160 {
1206  return parseParamH160(val);
1207  });
1208 }
1209 
1210 void parseParam(const UniValue& val, std::set<dev::h160> &h160s) {
1211  std::vector<dev::h160> v;
1212  parseParam(val, v);
1213  h160s.insert(v.begin(), v.end());
1214 }
1215 
1216 void parseParam(const UniValue& val, std::vector<boost::optional<dev::h256>> &h256s) {
1217  if (val.isNull()) {
1218  return;
1219  }
1220 
1221  if (!val.isArray()) {
1222  throw JSONRPCError(RPC_INVALID_PARAMS, "Expect an array of hex 256 strings");
1223  }
1224 
1225  auto vals = val.getValues();
1226  h256s.resize(vals.size());
1227 
1228  std::transform(vals.begin(), vals.end(), h256s.begin(), [](UniValue val) -> boost::optional<dev::h256> {
1229  if (val.isNull()) {
1230  return boost::optional<dev::h256>();
1231  }
1232 
1233  if (!val.isStr()) {
1234  throw JSONRPCError(RPC_INVALID_PARAMS, "Invalid hex 256 string");
1235  }
1236 
1237  auto addrStr = val.get_str();
1238 
1239  if (addrStr.length() != 64 || !CheckHex(addrStr)) {
1240  throw JSONRPCError(RPC_INVALID_PARAMS, "Invalid hex 256 string");
1241  }
1242 
1243  return boost::optional<dev::h256>(dev::h256(addrStr));
1244  });
1245 }
1246 
1248 public:
1250  int toBlock;
1251 
1252  int minconf;
1253 
1254  std::set<dev::h160> addresses;
1255  std::vector<boost::optional<dev::h256>> topics;
1256 
1257  // bool wait;
1258 
1259  WaitForLogsParams(const UniValue& params) {
1260  std::unique_lock<std::mutex> lock(cs_blockchange);
1261 
1262  fromBlock = parseBlockHeight(params[0], latestblock.height + 1);
1263  toBlock = parseBlockHeight(params[1], -1);
1264 
1265  parseFilter(params[2]);
1266  minconf = parseUInt(params[3], 6);
1267  }
1268 
1269 private:
1270  void parseFilter(const UniValue& val) {
1271  if (val.isNull()) {
1272  return;
1273  }
1274 
1275  parseParam(val["addresses"], addresses);
1276  parseParam(val["topics"], topics);
1277  }
1278 };
1279 
1281  // this is a long poll function. force cast to non const pointer
1282  JSONRPCRequest& request = (JSONRPCRequest&) request_;
1283 
1284  if (request.fHelp) {
1285  throw std::runtime_error(
1286  "waitforlogs (fromBlock) (toBlock) (filter) (minconf)\n"
1287  "requires -logevents to be enabled\n"
1288  "\nWaits for a new logs and return matching log entries. When the call returns, it also specifies the next block number to start waiting for new logs.\n"
1289  "By calling waitforlogs repeatedly using the returned `nextBlock` number, a client can receive a stream of up-to-date log entires.\n"
1290  "\nThis call is different from the similarly named `waitforlogs`. This call returns individual matching log entries, `searchlogs` returns a transaction receipt if one of the log entries of that transaction matches the filter conditions.\n"
1291  "\nArguments:\n"
1292  "1. fromBlock (int | \"latest\", optional, default=null) The block number to start looking for logs. ()\n"
1293  "2. toBlock (int | \"latest\", optional, default=null) The block number to stop looking for logs. If null, will wait indefinitely into the future.\n"
1294  "3. filter ({ addresses?: Hex160String[], topics?: Hex256String[] }, optional default={}) Filter conditions for logs. Addresses and topics are specified as array of hexadecimal strings\n"
1295  "4. minconf (uint, optional, default=6) Minimal number of confirmations before a log is returned\n"
1296  "\nResult:\n"
1297  "An object with the following properties:\n"
1298  "1. logs (LogEntry[]) Array of matchiing log entries. This may be empty if `filter` removed all entries."
1299  "2. count (int) How many log entries are returned."
1300  "3. nextBlock (int) To wait for new log entries haven't seen before, use this number as `fromBlock`"
1301  "\nUsage:\n"
1302  "`waitforlogs` waits for new logs, starting from the tip of the chain.\n"
1303  "`waitforlogs 600` waits for new logs, but starting from block 600. If there are logs available, this call will return immediately.\n"
1304  "`waitforlogs 600 700` waits for new logs, but only up to 700th block\n"
1305  "`waitforlogs null null` this is equivalent to `waitforlogs`, using default parameter values\n"
1306  "`waitforlogs null null` { \"addresses\": [ \"ff0011...\" ], \"topics\": [ \"c0fefe\"] }` waits for logs in the future matching the specified conditions\n"
1307  "\nSample Output:\n"
1308  "{\n \"entries\": [\n {\n \"blockHash\": \"56d5f1f5ec239ef9c822d9ed600fe9aa63727071770ac7c0eabfc903bf7316d4\",\n \"blockNumber\": 3286,\n \"transactionHash\": \"00aa0f041ce333bc3a855b2cba03c41427cda04f0334d7f6cb0acad62f338ddc\",\n \"transactionIndex\": 2,\n \"from\": \"3f6866e2b59121ada1ddfc8edc84a92d9655675f\",\n \"to\": \"8e1ee0b38b719abe8fa984c986eabb5bb5071b6b\",\n \"cumulativeGasUsed\": 23709,\n \"gasUsed\": 23709,\n \"contractAddress\": \"8e1ee0b38b719abe8fa984c986eabb5bb5071b6b\",\n \"topics\": [\n \"f0e1159fa6dc12bb31e0098b7a1270c2bd50e760522991c6f0119160028d9916\",\n \"0000000000000000000000000000000000000000000000000000000000000002\"\n ],\n \"data\": \"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003\"\n }\n ],\n\n \"count\": 7,\n \"nextblock\": 801\n}\n"
1309  );
1310  }
1311 
1312  if (!fLogEvents)
1313  throw JSONRPCError(RPC_INTERNAL_ERROR, "Events indexing disabled");
1314 
1315  WaitForLogsParams params(request.params);
1316 
1317  request.PollStart();
1318 
1319  std::vector<std::vector<uint256>> hashesToBlock;
1320 
1321  int curheight = 0;
1322 
1323  auto& addresses = params.addresses;
1324  auto& filterTopics = params.topics;
1325 
1326  while (curheight == 0) {
1327  {
1328  LOCK(cs_main);
1329  curheight = pblocktree->ReadHeightIndex(params.fromBlock, params.toBlock, params.minconf,
1330  hashesToBlock, addresses);
1331  }
1332 
1333  // if curheight >= fromBlock. Blockchain extended with new log entries. Return next block height to client.
1334  // nextBlock = curheight + 1
1335  // if curheight == 0. No log entry found in index. Wait for new block then try again.
1336  // nextBlock = fromBlock
1337  // if curheight == -1. Incorrect parameters has entered.
1338  //
1339  // if curheight advanced, but all filtered out, API should return empty array, but advancing the cursor anyway.
1340 
1341  if (curheight > 0) {
1342  break;
1343  }
1344 
1345  if (curheight == -1) {
1346  throw JSONRPCError(RPC_INVALID_PARAMETER, "Incorrect params");
1347  }
1348 
1349  // wait for a new block to arrive
1350  {
1351  while (true) {
1352  std::unique_lock<std::mutex> lock(cs_blockchange);
1353  auto blockHeight = latestblock.height;
1354 
1355  request.PollPing();
1356 
1357  cond_blockchange.wait_for(lock, std::chrono::milliseconds(1000));
1358  if (latestblock.height > blockHeight) {
1359  break;
1360  }
1361 
1362  // TODO: maybe just merge `IsRPCRunning` this into PollAlive
1363  if (!request.PollAlive() || !IsRPCRunning()) {
1364  LogPrintf("waitforlogs client disconnected\n");
1365  return NullUniValue;
1366  }
1367  }
1368  }
1369  }
1370 
1371  LOCK(cs_main);
1372 
1373  UniValue jsonLogs(UniValue::VARR);
1374 
1375  for (const auto& txHashes : hashesToBlock) {
1376  for (const auto& txHash : txHashes) {
1377  std::vector<TransactionReceiptInfo> receipts = pstorageresult->getResult(
1378  uintToh256(txHash));
1379 
1380  for (const auto& receipt : receipts) {
1381  for (const auto& log : receipt.logs) {
1382 
1383  bool includeLog = true;
1384 
1385  if (!filterTopics.empty()) {
1386  for (size_t i = 0; i < filterTopics.size(); i++) {
1387  auto filterTopic = filterTopics[i];
1388 
1389  if (!filterTopic) {
1390  continue;
1391  }
1392 
1393  auto filterTopicContent = filterTopic.get();
1394  auto topicContent = log.topics[i];
1395 
1396  if (topicContent != filterTopicContent) {
1397  includeLog = false;
1398  break;
1399  }
1400  }
1401  }
1402 
1403 
1404  if (!includeLog) {
1405  continue;
1406  }
1407 
1408  UniValue jsonLog(UniValue::VOBJ);
1409 
1410  assignJSON(jsonLog, receipt);
1411  assignJSON(jsonLog, log, false);
1412 
1413  jsonLogs.push_back(jsonLog);
1414  }
1415  }
1416  }
1417  }
1418 
1419  UniValue result(UniValue::VOBJ);
1420  result.push_back(Pair("entries", jsonLogs));
1421  result.push_back(Pair("count", (int) jsonLogs.size()));
1422  result.push_back(Pair("nextblock", curheight + 1));
1423 
1424  return result;
1425 }
1426 
1428 public:
1429  size_t fromBlock;
1430  size_t toBlock;
1431  size_t minconf;
1432 
1433  std::set<dev::h160> addresses;
1434  std::vector<boost::optional<dev::h256>> topics;
1435 
1436  SearchLogsParams(const UniValue& params) {
1437  std::unique_lock<std::mutex> lock(cs_blockchange);
1438 
1439  setFromBlock(params[0]);
1440  setToBlock(params[1]);
1441 
1442  parseParam(params[2]["addresses"], addresses);
1443  parseParam(params[3]["topics"], topics);
1444 
1445  minconf = parseUInt(params[4], 0);
1446  }
1447 
1448 private:
1449  void setFromBlock(const UniValue& val) {
1450  if (!val.isNull()) {
1451  fromBlock = parseBlockHeight(val);
1452  } else {
1453  fromBlock = latestblock.height;
1454  }
1455  }
1456 
1457  void setToBlock(const UniValue& val) {
1458  if (!val.isNull()) {
1459  toBlock = parseBlockHeight(val);
1460  } else {
1461  toBlock = latestblock.height;
1462  }
1463  }
1464 
1465 };
1466 
1468 {
1469  if (request.fHelp || request.params.size() < 2)
1470  throw std::runtime_error(
1471  "searchlogs <fromBlock> <toBlock> (address) (topics)\n"
1472  "requires -logevents to be enabled"
1473  "\nArgument:\n"
1474  "1. \"fromBlock\" (numeric, required) The number of the earliest block (latest may be given to mean the most recent block).\n"
1475  "2. \"toBlock\" (string, required) The number of the latest block (-1 may be given to mean the most recent block).\n"
1476  "3. \"address\" (string, optional) An address or a list of addresses to only get logs from particular account(s).\n"
1477  "4. \"topics\" (string, optional) An array of values from which at least one must appear in the log entries. The order is important, if you want to leave topics out use null, e.g. [\"null\", \"0x00...\"]. \n"
1478  "5. \"minconf\" (uint, optional, default=0) Minimal number of confirmations before a log is returned\n"
1479  "\nExamples:\n"
1480  + HelpExampleCli("searchlogs", "0 100 '{\"addresses\": [\"12ae42729af478ca92c8c66773a3e32115717be4\"]}' '{\"topics\": [\"null\",\"b436c2bf863ccd7b8f63171201efd4792066b4ce8e543dde9c3e9e9ab98e216c\"]}'")
1481  + HelpExampleRpc("searchlogs", "0 100 {\"addresses\": [\"12ae42729af478ca92c8c66773a3e32115717be4\"]} {\"topics\": [\"null\",\"b436c2bf863ccd7b8f63171201efd4792066b4ce8e543dde9c3e9e9ab98e216c\"]}")
1482  );
1483 
1484  if(!fLogEvents)
1485  throw JSONRPCError(RPC_INTERNAL_ERROR, "Events indexing disabled");
1486 
1488  throw JSONRPCError(RPC_METHOD_NOT_FOUND, std::string ("This method can only be used after fork, block ") + std::to_string(Params().GetConsensus().ContractHeight ));
1489 
1490  int curheight = 0;
1491 
1492  LOCK(cs_main);
1493 
1494  SearchLogsParams params(request.params);
1495 
1496  std::vector<std::vector<uint256>> hashesToBlock;
1497 
1498  curheight = pblocktree->ReadHeightIndex(params.fromBlock, params.toBlock, params.minconf, hashesToBlock, params.addresses);
1499 
1500  if (curheight == -1) {
1501  throw JSONRPCError(RPC_INVALID_PARAMETER, "Incorrect params");
1502  }
1503 
1504  UniValue result(UniValue::VARR);
1505 
1506  auto topics = params.topics;
1507 
1508  for(const auto& hashesTx : hashesToBlock)
1509  {
1510  for(const auto& e : hashesTx)
1511  {
1512  std::vector<TransactionReceiptInfo> receipts = pstorageresult->getResult(uintToh256(e));
1513 
1514  for(const auto& receipt : receipts) {
1515  if(receipt.logs.empty()) {
1516  continue;
1517  }
1518 
1519  if (!topics.empty()) {
1520  for (size_t i = 0; i < topics.size(); i++) {
1521  const auto& tc = topics[i];
1522 
1523  if (!tc) {
1524  continue;
1525  }
1526 
1527  for (const auto& log: receipt.logs) {
1528  auto filterTopicContent = tc.get();
1529 
1530  if (i >= log.topics.size()) {
1531  continue;
1532  }
1533 
1534  if (filterTopicContent == log.topics[i]) {
1535  goto push;
1536  }
1537  }
1538  }
1539 
1540  // Skip the log if none of the topics are matched
1541  continue;
1542  }
1543 
1544  push:
1545 
1546  UniValue tri(UniValue::VOBJ);
1547  transactionReceiptInfoToJSON(receipt, tri);
1548  result.push_back(tri);
1549  }
1550  }
1551  }
1552 
1553  return result;
1554 }
1555 
1557 {
1558  if (request.fHelp || request.params.size() < 1)
1559  throw std::runtime_error(
1560  "gettransactionreceipt \"hash\"\n"
1561  "requires -logevents to be enabled"
1562  "\nArgument:\n"
1563  "1. \"hash\" (string, required) The transaction hash\n"
1564  );
1565 
1566  if(!fLogEvents)
1567  throw JSONRPCError(RPC_INTERNAL_ERROR, "Events indexing disabled");
1568 
1569  LOCK(cs_main);
1570 
1571  std::string hashTemp = request.params[0].get_str();
1572  if(hashTemp.size() != 64){
1573  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect hash");
1574  }
1575 
1576  uint256 hash(uint256S(hashTemp));
1577 
1578  std::vector<TransactionReceiptInfo> transactionReceiptInfo = pstorageresult->getResult(uintToh256(hash));
1579 
1580  UniValue result(UniValue::VARR);
1581  for(TransactionReceiptInfo& t : transactionReceiptInfo){
1582  UniValue tri(UniValue::VOBJ);
1584  result.push_back(tri);
1585  }
1586  return result;
1587 }
1589 
1591 {
1592  if (request.fHelp)
1593  throw std::runtime_error(
1594  "listcontracts (start maxDisplay)\n"
1595  "\nArgument:\n"
1596  "1. start (numeric or string, optional) The starting account index, default 1\n"
1597  "2. maxDisplay (numeric or string, optional) Max accounts to list, default 20\n"
1598  );
1599 
1600  LOCK(cs_main);
1601 
1603  throw JSONRPCError(RPC_METHOD_NOT_FOUND, std::string ("This method can only be used after fork, block ") + std::to_string(Params().GetConsensus().ContractHeight ));
1604 
1605  int start=1;
1606  if (request.params.size() > 0){
1607  start = request.params[0].get_int();
1608  if (start<= 0)
1609  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid start, min=1");
1610  }
1611 
1612  int maxDisplay=20;
1613  if (request.params.size() > 1){
1614  maxDisplay = request.params[1].get_int();
1615  if (maxDisplay <= 0)
1616  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid maxDisplay");
1617  }
1618 
1619  UniValue result(UniValue::VOBJ);
1620 
1621  auto map = globalState->addresses();
1622  int contractsCount=(int)map.size();
1623 
1624  if (contractsCount>0 && start > contractsCount)
1625  throw JSONRPCError(RPC_TYPE_ERROR, "start greater than max index "+ itostr(contractsCount));
1626 
1627  int itStartPos=std::min(start-1,contractsCount);
1628  int i=0;
1629  for (auto it = std::next(map.begin(),itStartPos); it!=map.end(); it++)
1630  {
1631  result.push_back(Pair(it->first.hex(),ValueFromAmount(CAmount(globalState->balance(it->first)))));
1632  i++;
1633  if(i==maxDisplay)break;
1634  }
1635 
1636  return result;
1637 }
1638 
1639 
1641 {
1642  int nHeight;
1644  uint64_t nTransactions;
1646  uint64_t nBogoSize;
1648  uint64_t nDiskSize;
1650 
1651  CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {}
1652 };
1653 
1654 static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
1655 {
1656  assert(!outputs.empty());
1657  ss << hash;
1658  ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
1659  stats.nTransactions++;
1660  for (const auto output : outputs) {
1661  ss << VARINT(output.first + 1);
1662  ss << output.second.out.scriptPubKey;
1663  ss << VARINT(output.second.out.nValue);
1664  stats.nTransactionOutputs++;
1665  stats.nTotalAmount += output.second.out.nValue;
1666  stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ +
1667  2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */;
1668  }
1669  ss << VARINT(0);
1670 }
1671 
1673 static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
1674 {
1675  std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
1676 
1677  CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
1678  stats.hashBlock = pcursor->GetBestBlock();
1679  {
1680  LOCK(cs_main);
1681  stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
1682  }
1683  ss << stats.hashBlock;
1684  uint256 prevkey;
1685  std::map<uint32_t, Coin> outputs;
1686  while (pcursor->Valid()) {
1687  boost::this_thread::interruption_point();
1688  COutPoint key;
1689  Coin coin;
1690  if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
1691  if (!outputs.empty() && key.hash != prevkey) {
1692  ApplyStats(stats, ss, prevkey, outputs);
1693  outputs.clear();
1694  }
1695  prevkey = key.hash;
1696  outputs[key.n] = std::move(coin);
1697  } else {
1698  return error("%s: unable to read value", __func__);
1699  }
1700  pcursor->Next();
1701  }
1702  if (!outputs.empty()) {
1703  ApplyStats(stats, ss, prevkey, outputs);
1704  }
1705  stats.hashSerialized = ss.GetHash();
1706  stats.nDiskSize = view->EstimateSize();
1707  return true;
1708 }
1709 
1711 {
1712  if (request.fHelp || request.params.size() != 1)
1713  throw std::runtime_error(
1714  "pruneblockchain\n"
1715  "\nArguments:\n"
1716  "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n"
1717  " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n"
1718  "\nResult:\n"
1719  "n (numeric) Height of the last block pruned.\n"
1720  "\nExamples:\n"
1721  + HelpExampleCli("pruneblockchain", "1000")
1722  + HelpExampleRpc("pruneblockchain", "1000"));
1723 
1724  if (!fPruneMode)
1725  throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
1726 
1727  LOCK(cs_main);
1728 
1729  int heightParam = request.params[0].get_int();
1730  if (heightParam < 0)
1731  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
1732 
1733  // Height value more than a billion is too high to be a block height, and
1734  // too low to be a block time (corresponds to timestamp from Sep 2001).
1735  if (heightParam > 1000000000) {
1736  // Add a 2 hour buffer to include blocks which might have had old timestamps
1737  CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW);
1738  if (!pindex) {
1739  throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
1740  }
1741  heightParam = pindex->nHeight;
1742  }
1743 
1744  unsigned int height = (unsigned int) heightParam;
1745  unsigned int chainHeight = (unsigned int) chainActive.Height();
1746  if (chainHeight < Params().PruneAfterHeight())
1747  throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
1748  else if (height > chainHeight)
1749  throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
1750  else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
1751  LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.");
1752  height = chainHeight - MIN_BLOCKS_TO_KEEP;
1753  }
1754 
1755  PruneBlockFilesManual(height);
1756  return uint64_t(height);
1757 }
1758 
1760 {
1761  if (request.fHelp || request.params.size() != 0)
1762  throw std::runtime_error(
1763  "gettxoutsetinfo\n"
1764  "\nReturns statistics about the unspent transaction output set.\n"
1765  "Note this call may take some time.\n"
1766  "\nResult:\n"
1767  "{\n"
1768  " \"height\":n, (numeric) The current block height (index)\n"
1769  " \"bestblock\": \"hex\", (string) the best block hash hex\n"
1770  " \"transactions\": n, (numeric) The number of transactions\n"
1771  " \"txouts\": n, (numeric) The number of output transactions\n"
1772  " \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n"
1773  " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n"
1774  " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
1775  " \"total_amount\": x.xxx (numeric) The total amount\n"
1776  "}\n"
1777  "\nExamples:\n"
1778  + HelpExampleCli("gettxoutsetinfo", "")
1779  + HelpExampleRpc("gettxoutsetinfo", "")
1780  );
1781 
1782  UniValue ret(UniValue::VOBJ);
1783 
1784  CCoinsStats stats;
1785  FlushStateToDisk();
1786  if (GetUTXOStats(pcoinsdbview, stats)) {
1787  ret.push_back(Pair("height", (int64_t)stats.nHeight));
1788  ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
1789  ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
1790  ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
1791  ret.push_back(Pair("bogosize", (int64_t)stats.nBogoSize));
1792  ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex()));
1793  ret.push_back(Pair("disk_size", stats.nDiskSize));
1794  ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
1795  } else {
1796  throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
1797  }
1798  return ret;
1799 }
1800 
1801 
1803 {
1804  if (request.fHelp || request.params.size() != 0)
1805  throw std::runtime_error(
1806  "gettxoutset\n"
1807  "\nReturns the unspent transaction output set.\n"
1808  "Note this call may take some time.\n"
1809  "\nResult:\n"
1810  "{\n"
1811  " \"UTXO\": \"height, address, amount\"\n"
1812  "}\n"
1813  "\nExamples:\n"
1814  + HelpExampleCli("gettxoutset", "")
1815  + HelpExampleRpc("gettxoutset", "")
1816  );
1817 
1818  UniValue ret(UniValue::VARR);
1819 
1820  CCoinsStats stats;
1821  FlushStateToDisk();
1822 
1823  std::unique_ptr<CCoinsViewCursor> pcursor(pcoinsdbview->Cursor());
1824 
1825  uint256 prevkey;
1826  std::map<uint32_t, Coin> outputs;
1827 
1828  while (pcursor->Valid()) {
1829  boost::this_thread::interruption_point();
1830  COutPoint key;
1831  Coin coin;
1832 
1833 
1834  if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
1835  if (!outputs.empty() && key.hash != prevkey) {
1836  outputs.clear();
1837  }
1838  prevkey = key.hash;
1839  txnouttype type;
1840  std::vector<CTxDestination> addresses;
1841  int nRequired;
1842  std::stringstream strUtxo;
1843  if( ExtractDestinations(coin.out.scriptPubKey, type, addresses, nRequired))
1844  {
1845  for( const CTxDestination addr: addresses )
1846  {
1847  //strUtxo << coin.nHeight << ", " << CFabcoinAddress(addr).ToString() << ", " << coin.out.nValue ;
1848 
1849  strUtxo << coin.nHeight << ", " << key.hash.ToString() << ", " << key.n << ", " << CFabcoinAddress(addr).ToString() << ", " << coin.out.nValue ;
1850  ret.push_back(strUtxo.str());
1851  }
1852  }
1853  else
1854  {
1855  strUtxo << coin.nHeight << ", " << key.hash.ToString() << ", " << key.n << ", " << "noaddress" << ", " << coin.out.nValue ;
1856  ret.push_back(strUtxo.str());
1857  }
1858  outputs[key.n] = std::move(coin);
1859  }
1860  else
1861  {
1862  ret.push_back("ERROR: unable to read value");
1863  return ret;
1864  }
1865  pcursor->Next();
1866  }
1867 
1868  return ret;
1869 }
1870 
1871 
1873 {
1874  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
1875  throw std::runtime_error(
1876  "gettxout \"txid\" n ( include_mempool )\n"
1877  "\nReturns details about an unspent transaction output.\n"
1878  "\nArguments:\n"
1879  "1. \"txid\" (string, required) The transaction id\n"
1880  "2. \"n\" (numeric, required) vout number\n"
1881  "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true."
1882  " Note that an unspent output that is spent in the mempool won't appear.\n"
1883  "\nResult:\n"
1884  "{\n"
1885  " \"bestblock\" : \"hash\", (string) the block hash\n"
1886  " \"confirmations\" : n, (numeric) The number of confirmations\n"
1887  " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
1888  " \"scriptPubKey\" : { (json object)\n"
1889  " \"asm\" : \"code\", (string) \n"
1890  " \"hex\" : \"hex\", (string) \n"
1891  " \"reqSigs\" : n, (numeric) Number of required signatures\n"
1892  " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
1893  " \"addresses\" : [ (array of string) array of fabcoin addresses\n"
1894  " \"address\" (string) fabcoin address\n"
1895  " ,...\n"
1896  " ]\n"
1897  " },\n"
1898  " \"coinbase\" : true|false (boolean) Coinbase or not\n"
1899  "}\n"
1900 
1901  "\nExamples:\n"
1902  "\nGet unspent transactions\n"
1903  + HelpExampleCli("listunspent", "") +
1904  "\nView the details\n"
1905  + HelpExampleCli("gettxout", "\"txid\" 1") +
1906  "\nAs a json rpc call\n"
1907  + HelpExampleRpc("gettxout", "\"txid\", 1")
1908  );
1909 
1910  LOCK(cs_main);
1911 
1912  UniValue ret(UniValue::VOBJ);
1913 
1914  std::string strHash = request.params[0].get_str();
1915  uint256 hash(uint256S(strHash));
1916  int n = request.params[1].get_int();
1917  COutPoint out(hash, n);
1918  bool fMempool = true;
1919  if (!request.params[2].isNull())
1920  fMempool = request.params[2].get_bool();
1921 
1922  Coin coin;
1923  if (fMempool) {
1924  LOCK(mempool.cs);
1926  if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
1927  return NullUniValue;
1928  }
1929  } else {
1930  if (!pcoinsTip->GetCoin(out, coin)) {
1931  return NullUniValue;
1932  }
1933  }
1934 
1935  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
1936  CBlockIndex *pindex = it->second;
1937  ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
1938  if (coin.nHeight == MEMPOOL_HEIGHT) {
1939  ret.push_back(Pair("confirmations", 0));
1940  } else {
1941  ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)));
1942  }
1943  ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
1945  ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
1946  ret.push_back(Pair("scriptPubKey", o));
1947  ret.push_back(Pair("coinbase", (bool)coin.fCoinBase));
1948 
1949  return ret;
1950 }
1951 
1953 {
1954  int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
1955  int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
1956  if (request.fHelp || request.params.size() > 2)
1957  throw std::runtime_error(
1958  "verifychain ( checklevel nblocks )\n"
1959  "\nVerifies blockchain database.\n"
1960  "\nArguments:\n"
1961  "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
1962  "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
1963  "\nResult:\n"
1964  "true|false (boolean) Verified or not\n"
1965  "\nExamples:\n"
1966  + HelpExampleCli("verifychain", "")
1967  + HelpExampleRpc("verifychain", "")
1968  );
1969 
1970  LOCK(cs_main);
1971 
1972  if (!request.params[0].isNull())
1973  nCheckLevel = request.params[0].get_int();
1974  if (!request.params[1].isNull())
1975  nCheckDepth = request.params[1].get_int();
1976 
1977  return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth);
1978 }
1979 
1981 static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
1982 {
1984  bool activated = false;
1985  switch(version)
1986  {
1987  case 2:
1988  activated = pindex->nHeight >= consensusParams.BIP34Height;
1989  break;
1990  case 3:
1991  activated = pindex->nHeight >= consensusParams.BIP66Height;
1992  break;
1993  case 4:
1994  activated = pindex->nHeight >= consensusParams.BIP65Height;
1995  break;
1996  }
1997  rv.push_back(Pair("status", activated));
1998  return rv;
1999 }
2000 
2001 static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
2002 {
2004  rv.push_back(Pair("id", name));
2005  rv.push_back(Pair("version", version));
2006  rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams)));
2007  return rv;
2008 }
2009 
2010 static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
2011 {
2013  const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
2014  switch (thresholdState) {
2015  case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
2016  case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
2017  case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
2018  case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
2019  case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
2020  }
2021  if (THRESHOLD_STARTED == thresholdState)
2022  {
2023  rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
2024  }
2025  rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
2026  rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
2027  rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id)));
2028  if (THRESHOLD_STARTED == thresholdState)
2029  {
2030  UniValue statsUV(UniValue::VOBJ);
2031  BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
2032  statsUV.push_back(Pair("period", statsStruct.period));
2033  statsUV.push_back(Pair("threshold", statsStruct.threshold));
2034  statsUV.push_back(Pair("elapsed", statsStruct.elapsed));
2035  statsUV.push_back(Pair("count", statsStruct.count));
2036  statsUV.push_back(Pair("possible", statsStruct.possible));
2037  rv.push_back(Pair("statistics", statsUV));
2038  }
2039  return rv;
2040 }
2041 
2042 void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
2043 {
2044  // Deployments with timeout value of 0 are hidden.
2045  // A timeout value of 0 guarantees a softfork will never be activated.
2046  // This is used when softfork codes are merged without specifying the deployment schedule.
2047  if (consensusParams.vDeployments[id].nTimeout > 0)
2048  bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id)));
2049 }
2050 
2052 {
2053  if (request.fHelp || request.params.size() != 0)
2054  throw std::runtime_error(
2055  "getblockchaininfo\n"
2056  "Returns an object containing various state info regarding blockchain processing.\n"
2057  "\nResult:\n"
2058  "{\n"
2059  " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
2060  " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
2061  " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
2062  " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
2063  " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
2064  " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
2065  " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
2066  " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
2067  " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
2068  " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored\n"
2069  " \"softforks\": [ (array) status of softforks in progress\n"
2070  " {\n"
2071  " \"id\": \"xxxx\", (string) name of softfork\n"
2072  " \"version\": xx, (numeric) block version\n"
2073  " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
2074  " \"status\": xx, (boolean) true if threshold reached\n"
2075  " },\n"
2076  " }, ...\n"
2077  " ],\n"
2078  " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
2079  " \"xxxx\" : { (string) name of the softfork\n"
2080  " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
2081  " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
2082  " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
2083  " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
2084  " \"since\": xx, (numeric) height of the first block to which the status applies\n"
2085  " \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n"
2086  " \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n"
2087  " \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n"
2088  " \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n"
2089  " \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n"
2090  " \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n"
2091  " }\n"
2092  " }\n"
2093  " }\n"
2094  "}\n"
2095  "\nExamples:\n"
2096  + HelpExampleCli("getblockchaininfo", "")
2097  + HelpExampleRpc("getblockchaininfo", "")
2098  );
2099 
2100  LOCK(cs_main);
2101 
2102  UniValue obj(UniValue::VOBJ);
2103  obj.push_back(Pair("chain", Params().NetworkIDString()));
2104  obj.push_back(Pair("blocks", (int)chainActive.Height()));
2105  obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
2106  obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
2107  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
2108  obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
2109  obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip())));
2110  obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
2111  obj.push_back(Pair("pruned", fPruneMode));
2112 
2113  const Consensus::Params& consensusParams = Params().GetConsensus();
2114  CBlockIndex* tip = chainActive.Tip();
2115  UniValue softforks(UniValue::VARR);
2116  UniValue bip9_softforks(UniValue::VOBJ);
2117  softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
2118  softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
2119  softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
2120  BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
2121  BIP9SoftForkDescPushBack(bip9_softforks, "segwit", consensusParams, Consensus::DEPLOYMENT_SEGWIT);
2122  obj.push_back(Pair("softforks", softforks));
2123  obj.push_back(Pair("bip9_softforks", bip9_softforks));
2124 
2125  if (fPruneMode)
2126  {
2127  CBlockIndex *block = chainActive.Tip();
2128  while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
2129  block = block->pprev;
2130 
2131  obj.push_back(Pair("pruneheight", block->nHeight));
2132  }
2133  return obj;
2134 }
2135 
2138 {
2139  bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
2140  {
2141  /* Make sure that unequal blocks with the same height do not compare
2142  equal. Use the pointers themselves to make a distinction. */
2143 
2144  if (a->nHeight != b->nHeight)
2145  return (a->nHeight > b->nHeight);
2146 
2147  return a < b;
2148  }
2149 };
2150 
2152 {
2153  if (request.fHelp || request.params.size() != 0)
2154  throw std::runtime_error(
2155  "getchaintips\n"
2156  "Return information about all known tips in the block tree,"
2157  " including the main chain as well as orphaned branches.\n"
2158  "\nResult:\n"
2159  "[\n"
2160  " {\n"
2161  " \"height\": xxxx, (numeric) height of the chain tip\n"
2162  " \"hash\": \"xxxx\", (string) block hash of the tip\n"
2163  " \"branchlen\": 0 (numeric) zero for main chain\n"
2164  " \"status\": \"active\" (string) \"active\" for the main chain\n"
2165  " },\n"
2166  " {\n"
2167  " \"height\": xxxx,\n"
2168  " \"hash\": \"xxxx\",\n"
2169  " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
2170  " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
2171  " }\n"
2172  "]\n"
2173  "Possible values for status:\n"
2174  "1. \"invalid\" This branch contains at least one invalid block\n"
2175  "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
2176  "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
2177  "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
2178  "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
2179  "\nExamples:\n"
2180  + HelpExampleCli("getchaintips", "")
2181  + HelpExampleRpc("getchaintips", "")
2182  );
2183 
2184  LOCK(cs_main);
2185 
2186  /*
2187  * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
2188  * Algorithm:
2189  * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
2190  * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
2191  * - add chainActive.Tip()
2192  */
2193  std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
2194  std::set<const CBlockIndex*> setOrphans;
2195  std::set<const CBlockIndex*> setPrevs;
2196 
2197  for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
2198  {
2199  if (!chainActive.Contains(item.second)) {
2200  setOrphans.insert(item.second);
2201  setPrevs.insert(item.second->pprev);
2202  }
2203  }
2204 
2205  for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
2206  {
2207  if (setPrevs.erase(*it) == 0) {
2208  setTips.insert(*it);
2209  }
2210  }
2211 
2212  // Always report the currently active tip.
2213  setTips.insert(chainActive.Tip());
2214 
2215  /* Construct the output array. */
2216  UniValue res(UniValue::VARR);
2217  for (const CBlockIndex* block : setTips)
2218  {
2219  UniValue obj(UniValue::VOBJ);
2220  obj.push_back(Pair("height", block->nHeight));
2221  obj.push_back(Pair("hash", block->phashBlock->GetHex()));
2222 
2223  const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
2224  obj.push_back(Pair("branchlen", branchLen));
2225 
2226  std::string status;
2227  if (chainActive.Contains(block)) {
2228  // This block is part of the currently active chain.
2229  status = "active";
2230  } else if (block->nStatus & BLOCK_FAILED_MASK) {
2231  // This block or one of its ancestors is invalid.
2232  status = "invalid";
2233  } else if (block->nChainTx == 0) {
2234  // This block cannot be connected because full block data for it or one of its parents is missing.
2235  status = "headers-only";
2236  } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
2237  // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
2238  status = "valid-fork";
2239  } else if (block->IsValid(BLOCK_VALID_TREE)) {
2240  // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
2241  status = "valid-headers";
2242  } else {
2243  // No clue.
2244  status = "unknown";
2245  }
2246  obj.push_back(Pair("status", status));
2247 
2248  res.push_back(obj);
2249  }
2250 
2251  return res;
2252 }
2253 
2255 {
2256  UniValue ret(UniValue::VOBJ);
2257  ret.push_back(Pair("size", (int64_t) mempool.size()));
2258  ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
2259  ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
2260  size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2261  ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
2262  ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
2263 
2264  return ret;
2265 }
2266 
2268 {
2269  if (request.fHelp || request.params.size() != 0)
2270  throw std::runtime_error(
2271  "getmempoolinfo\n"
2272  "\nReturns details on the active state of the TX memory pool.\n"
2273  "\nResult:\n"
2274  "{\n"
2275  " \"size\": xxxxx, (numeric) Current tx count\n"
2276  " \"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"
2277  " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
2278  " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
2279  " \"mempoolminfee\": xxxxx (numeric) Minimum feerate (" + CURRENCY_UNIT + " per KB) for tx to be accepted\n"
2280  "}\n"
2281  "\nExamples:\n"
2282  + HelpExampleCli("getmempoolinfo", "")
2283  + HelpExampleRpc("getmempoolinfo", "")
2284  );
2285 
2286  return mempoolInfoToJSON();
2287 }
2288 
2290 {
2291  if (request.fHelp || request.params.size() != 1)
2292  throw std::runtime_error(
2293  "preciousblock \"blockhash\"\n"
2294  "\nTreats a block as if it were received before others with the same work.\n"
2295  "\nA later preciousblock call can override the effect of an earlier one.\n"
2296  "\nThe effects of preciousblock are not retained across restarts.\n"
2297  "\nArguments:\n"
2298  "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n"
2299  "\nResult:\n"
2300  "\nExamples:\n"
2301  + HelpExampleCli("preciousblock", "\"blockhash\"")
2302  + HelpExampleRpc("preciousblock", "\"blockhash\"")
2303  );
2304 
2305  std::string strHash = request.params[0].get_str();
2306  uint256 hash(uint256S(strHash));
2307  CBlockIndex* pblockindex;
2308 
2309  {
2310  LOCK(cs_main);
2311  if (mapBlockIndex.count(hash) == 0)
2312  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2313 
2314  pblockindex = mapBlockIndex[hash];
2315  }
2316 
2317  CValidationState state;
2318  PreciousBlock(state, Params(), pblockindex);
2319 
2320  if (!state.IsValid()) {
2322  }
2323 
2324  return NullUniValue;
2325 }
2326 
2328 {
2329  if (request.fHelp || request.params.size() != 1)
2330  throw std::runtime_error(
2331  "invalidateblock \"blockhash\"\n"
2332  "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
2333  "\nArguments:\n"
2334  "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n"
2335  "\nResult:\n"
2336  "\nExamples:\n"
2337  + HelpExampleCli("invalidateblock", "\"blockhash\"")
2338  + HelpExampleRpc("invalidateblock", "\"blockhash\"")
2339  );
2340 
2341  std::string strHash = request.params[0].get_str();
2342  uint256 hash(uint256S(strHash));
2343  CValidationState state;
2344 
2345  {
2346  LOCK(cs_main);
2347  if (mapBlockIndex.count(hash) == 0)
2348  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2349 
2350  CBlockIndex* pblockindex = mapBlockIndex[hash];
2351  InvalidateBlock(state, Params(), pblockindex);
2352  }
2353 
2354  if (state.IsValid()) {
2355  ActivateBestChain(state, Params());
2356  }
2357 
2358  if (!state.IsValid()) {
2360  }
2361 
2362  return NullUniValue;
2363 }
2364 
2366 {
2367  if (request.fHelp || request.params.size() != 1)
2368  throw std::runtime_error(
2369  "reconsiderblock \"blockhash\"\n"
2370  "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
2371  "This can be used to undo the effects of invalidateblock.\n"
2372  "\nArguments:\n"
2373  "1. \"blockhash\" (string, required) the hash of the block to reconsider\n"
2374  "\nResult:\n"
2375  "\nExamples:\n"
2376  + HelpExampleCli("reconsiderblock", "\"blockhash\"")
2377  + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
2378  );
2379 
2380  std::string strHash = request.params[0].get_str();
2381  uint256 hash(uint256S(strHash));
2382 
2383  {
2384  LOCK(cs_main);
2385  if (mapBlockIndex.count(hash) == 0)
2386  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2387 
2388  CBlockIndex* pblockindex = mapBlockIndex[hash];
2389  ResetBlockFailureFlags(pblockindex);
2390  }
2391 
2392  CValidationState state;
2393  ActivateBestChain(state, Params());
2394 
2395  if (!state.IsValid()) {
2397  }
2398 
2399  return NullUniValue;
2400 }
2401 
2403 {
2404  if (request.fHelp || request.params.size() > 2)
2405  throw std::runtime_error(
2406  "getchaintxstats ( nblocks blockhash )\n"
2407  "\nCompute statistics about the total number and rate of transactions in the chain.\n"
2408  "\nArguments:\n"
2409  "1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n"
2410  "2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n"
2411  "\nResult:\n"
2412  "{\n"
2413  " \"time\": xxxxx, (numeric) The timestamp for the statistics in UNIX format.\n"
2414  " \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n"
2415  " \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window.\n"
2416  "}\n"
2417  "\nExamples:\n"
2418  + HelpExampleCli("getchaintxstats", "")
2419  + HelpExampleRpc("getchaintxstats", "2016")
2420  );
2421 
2422  const CBlockIndex* pindex;
2423  int blockcount = 30 * 24 * 60 * 60 / Params().GetnPowTargetSpacing(chainActive.Height()); // By default: 1 month
2424 
2425  if (request.params.size() > 0 && !request.params[0].isNull()) {
2426  blockcount = request.params[0].get_int();
2427  }
2428 
2429  bool havehash = request.params.size() > 1 && !request.params[1].isNull();
2430  uint256 hash;
2431  if (havehash) {
2432  hash = uint256S(request.params[1].get_str());
2433  }
2434 
2435  {
2436  LOCK(cs_main);
2437  if (havehash) {
2438  auto it = mapBlockIndex.find(hash);
2439  if (it == mapBlockIndex.end()) {
2440  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
2441  }
2442  pindex = it->second;
2443  if (!chainActive.Contains(pindex)) {
2444  throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
2445  }
2446  } else {
2447  pindex = chainActive.Tip();
2448  }
2449  }
2450 
2451  if (blockcount < 1 || blockcount >= pindex->nHeight) {
2452  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 1 and the block's height");
2453  }
2454 
2455  const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount);
2456  int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast();
2457  int nTxDiff = pindex->nChainTx - pindexPast->nChainTx;
2458 
2459  UniValue ret(UniValue::VOBJ);
2460  ret.push_back(Pair("time", (int64_t)pindex->nTime));
2461  ret.push_back(Pair("txcount", (int64_t)pindex->nChainTx));
2462  ret.push_back(Pair("txrate", ((double)nTxDiff) / nTimeDiff));
2463 
2464  return ret;
2465 }
2466 
2467 static const CRPCCommand commands[] =
2468 { // category name actor (function) okSafe argNames
2469  // --------------------- ------------------------ ----------------------- ------ ----------
2470  { "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} },
2471  { "blockchain", "getchaintxstats", &getchaintxstats, true, {"nblocks", "blockhash"} },
2472  { "blockchain", "getbestblockhash", &getbestblockhash, true, {} },
2473  { "blockchain", "getblockcount", &getblockcount, true, {} },
2474  { "blockchain", "getblock", &getblock, true, {"blockhash","verbosity|verbose","legacy"} },
2475  { "blockchain", "getblockhash", &getblockhash, true, {"height"} },
2476  { "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose","legacy"} },
2477  { "blockchain", "getchaintips", &getchaintips, true, {} },
2478  { "blockchain", "getdifficulty", &getdifficulty, true, {} },
2479  { "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} },
2480  { "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} },
2481  { "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} },
2482  { "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} },
2483  { "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} },
2484  { "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} },
2485  { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} },
2486  { "blockchain", "gettxoutset", &gettxoutset, true, {} },
2487  { "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} },
2488  { "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} },
2489  { "blockchain", "getaccountinfo", &getaccountinfo, true, {"contract_address"} },
2490  { "blockchain", "getstorage", &getstorage, true, {"address, index, blockNum"} },
2491 
2492  { "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} },
2493 
2494  { "blockchain", "callcontract", &callcontract, true, {"address","data"} }, // fasc
2495  /* Not shown in help */
2496  { "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} },
2497  { "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} },
2498  { "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} },
2499  { "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} },
2500  { "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} },
2501  { "blockchain", "listcontracts", &listcontracts, true, {"start", "maxDisplay"} },
2502  { "blockchain", "gettransactionreceipt", &gettransactionreceipt, true, {"hash"} },
2503  { "blockchain", "searchlogs", &searchlogs, true, {"fromBlock", "toBlock", "address", "topics"} },
2504  { "blockchain", "waitforlogs", &waitforlogs, true, {"fromBlock", "nblocks", "address", "topics"} },
2505 };
2506 
2508 {
2509  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
2510  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
2511 }
int get_int() const
bool fLogEvents
Definition: validation.cpp:88
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:205
CAmount nValue
Definition: transaction.h:134
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
CAmount GetFeePerK() const
Return the fee in liu for a size of 1000 bytes.
Definition: feerate.h:38
#define VARINT(obj)
Definition: serialize.h:389
CodeDeposit codeDeposit
Failed if an attempted deposit failed due to lack of gas.
Definition: Transaction.h:75
CTxMemPool mempool
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:996
CAmount GetModFeesWithAncestors() const
Definition: txmempool.h:133
bool error(const char *fmt, const Args &...args)
Definition: util.h:178
const std::string & get_str() const
size_t size() const
Definition: univalue.h:70
uint64_t nTransactionOutputs
std::string toHex(T const &_data, int _w=2, HexPrefix _prefix=HexPrefix::DontAdd)
Definition: CommonData.h:54
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:79
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:90
unsigned int GetHeight() const
Definition: txmempool.h:108
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
std::vector< TransactionReceiptInfo > getResult(dev::h256 const &hashTx)
UniValue getmempoolancestors(const JSONRPCRequest &request)
Definition: blockchain.cpp:567
uint256 nNonce
Definition: block.h:53
Fabcoin RPC command dispatcher.
Definition: server.h:200
UniValue getblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:933
uint256 hashBlock
const_iterator begin() const
Definition: streams.h:233
CScript scriptPubKey
Definition: transaction.h:135
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:184
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:335
uint64_t GetCountWithAncestors() const
Definition: txmempool.h:131
uint64_t GetCountWithDescendants() const
Definition: txmempool.h:125
A UTXO entry.
Definition: coins.h:29
Definition: block.h:155
UniValue getbestblockhash(const JSONRPCRequest &request)
Definition: blockchain.cpp:291
UniValue reconsiderblock(const JSONRPCRequest &request)
int height
Definition: server.h:28
#define strprintf
Definition: tinyformat.h:1054
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.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:900
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:89
bool isSpent(const COutPoint &outpoint)
Definition: txmempool.cpp:348
LogBloom const & bloom() const
void assignJSON(UniValue &entry, const TransactionReceiptInfo &resExec)
UniValue preciousblock(const JSONRPCRequest &request)
bool fRecordLogOpcodes
Definition: validation.cpp:72
UniValue transactionReceiptToJSON(const dev::eth::TransactionReceipt &txRec)
Definition: blockchain.cpp:250
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:989
UniValue mempoolInfoToJSON()
Mempool information to JSON.
Comparison function for sorting the getchaintips heads.
const std::vector< UniValue > & getValues() const
std::string GetHex() const
Definition: uint256.cpp:21
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:141
bool FlushStateToDisk()
Flush all state, indexes and buffers to disk.
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
CCriticalSection cs_main
Definition: validation.cpp:77
base58-encoded Fabcoin addresses.
Definition: base58.h:104
void setToBlock(const UniValue &val)
CTxOut out
unspent transaction output
Definition: coins.h:33
h160 Address
An Ethereum address: 20 bytes.
Definition: Common.h:62
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:19
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:36
UniValue blockheaderToJSON(const CBlockIndex *blockindex)
Block header to JSON.
Definition: blockchain.cpp:125
int BIP66Height
Block height at which BIP66 becomes active.
Definition: params.h:50
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...
bool isArray() const
Definition: univalue.h:85
h256 const & stateRoot() const
uint64_t GetTotalTxSize()
Definition: txmempool.h:665
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:534
uint64_t nTransactions
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:795
uint64_t nDiskSize
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:559
assert(len-trim+(2 *lenIndices)<=WIDTH)
UniValue listcontracts(const JSONRPCRequest &request)
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:920
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
size_t parseUInt(const UniValue &val, size_t defaultVal)
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index, or the chain tip if not provided...
Definition: blockchain.cpp:105
ThresholdState
Definition: versionbits.h:20
SearchLogsParams(const UniValue &params)
bool IsSupportContract() const
Definition: chain.cpp:127
UniValue verifychain(const JSONRPCRequest &request)
uint64_t GetUint64(int pos) const
Definition: uint256.h:90
std::vector< boost::optional< dev::h256 > > topics
ExecStats::duration min
Definition: ExecStats.cpp:35
Description of the result of executing a transaction.
Definition: Transaction.h:69
UniValue getblockcount(const JSONRPCRequest &request)
Definition: blockchain.cpp:274
bytes code
Definition: SmartVM.cpp:45
UniValue executionResultToJSON(const dev::eth::ExecutionResult &exRes)
Definition: blockchain.cpp:234
unsigned char * begin()
Definition: uint256.h:65
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:298
UniValue waitfornewblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:318
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
uint64_t nBogoSize
void version()
Definition: main.cpp:53
int threshold
Definition: versionbits.h:42
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:17
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:214
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.
unsigned char * end()
Definition: uint256.h:70
UniValue getmempooldescendants(const JSONRPCRequest &request)
Definition: blockchain.cpp:631
uint256 hash
Definition: server.h:27
const std::vector< CTxIn > vin
Definition: transaction.h:292
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:126
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
u256 const & gasUsed() const
arith_uint256 UintToArith256(const uint256 &a)
UniValue gettxoutset(const JSONRPCRequest &request)
UniValue waitforblock(const JSONRPCRequest &request)
Definition: blockchain.cpp:356
std::string ToString() const
Definition: uint256.cpp:95
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:66
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:302
void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
Definition: blockchain.cpp:475
indexed_transaction_set mapTx
Definition: txmempool.h:524
CAmount nTotalAmount
uint256 hashSerialized
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
int64_t GetnPowTargetSpacing(uint32_t nHeight=0) const
Definition: chainparams.h:74
UniValue gettransactionreceipt(const JSONRPCRequest &request)
uint64_t GetSizeWithDescendants() const
Definition: txmempool.h:126
UniValue searchlogs(const JSONRPCRequest &request)
bool ReadBlockFromDisk(Block &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
#define a(i)
#define AssertLockHeld(cs)
Definition: sync.h:85
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
const CAmount & GetFee() const
Definition: txmempool.h:104
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:512
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:252
std::string name
Definition: server.h:191
void setFromBlock(const UniValue &val)
UniValue getaccountinfo(const JSONRPCRequest &request)
Definition: blockchain.cpp:753
int Height() const
Return the maximal height in the chain.
Definition: chain.h:543
uint32_t GetCompact(bool fNegative=false) const
int64_t get_int64() const
unsigned int nTime
Definition: chain.h:223
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
#define LogPrintf(...)
Definition: util.h:153
dev::h256 uintToh256(const uint256 &in)
Definition: uint256.h:171
dev::eth::LogEntries logs
UniValue pruneblockchain(const JSONRPCRequest &request)
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:217
UniValue waitforblockheight(const JSONRPCRequest &request)
Definition: blockchain.cpp:398
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:535
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry)
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:155
CBlockHeader GetBlockHeader() const
Definition: chain.h:306
unsigned long size()
Definition: txmempool.h:659
uint256 hashMerkleRoot
Definition: block.h:45
std::set< dev::h160 > addresses
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
Abstract view on the open txout dataset.
Definition: coins.h:145
void parseParam(const UniValue &val, std::vector< dev::h160 > &h160s)
UniValue params
Definition: server.h:59
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:81
int64_t GetBlockTime() const
Definition: block.h:127
DeploymentPos
Definition: params.h:15
An input of a transaction.
Definition: transaction.h:61
int period
Definition: versionbits.h:41
#define LOCK(cs)
Definition: sync.h:175
const char * name
Definition: rest.cpp:36
ExecStats::duration max
Definition: ExecStats.cpp:36
UniValue getmempoolinfo(const JSONRPCRequest &request)
bool isNum() const
Definition: univalue.h:84
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:45
CAmount GetModFeesWithDescendants() const
Definition: txmempool.h:127
uint256 uint256S(const char *str)
Definition: uint256.h:153
int64_t nStartTime
Start MedianTime for version bits miner confirmation.
Definition: params.h:31
dev::Address contractAddress
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:456
uint32_t ContractHeight
Block height at which Fabcoin Smart Contract hard fork becomes active.
Definition: params.h:56
UniValue getdifficulty(const JSONRPCRequest &request)
Definition: blockchain.cpp:440
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:619
uint32_t n
Definition: transaction.h:22
double GetDifficultyINTERNAL(const CBlockIndex *blockindex)
Definition: blockchain.cpp:46
Unexpected type was passed as parameter.
Definition: protocol.h:50
UniValue getchaintxstats(const JSONRPCRequest &request)
unsigned int nBits
Definition: chain.h:224
UniValue callcontract(const JSONRPCRequest &request)
UniValue gettxoutsetinfo(const JSONRPCRequest &request)
h256s topics
Definition: ExtVMFace.h:106
int64_t GetTime() const
Definition: txmempool.h:107
uint256 hashMerkleRoot
Definition: chain.h:221
UniValue getblockhash(const JSONRPCRequest &request)
Definition: blockchain.cpp:728
std::string ToString() const
Definition: base58.cpp:193
General application defined errors.
Definition: protocol.h:48
FixedHash< 32 > h256
Definition: FixedHash.h:340
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...
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:53
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
bool IsValid() const
Definition: validation.h:66
Invalid address or key.
Definition: protocol.h:51
std::set< dev::h160 > addresses
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:554
UniValue getmempoolentry(const JSONRPCRequest &request)
Definition: blockchain.cpp:695
Parameters that influence chain consensus.
Definition: params.h:39
UniValue waitforlogs(const JSONRPCRequest &request_)
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
int parseBlockHeight(const UniValue &val)
std::string GetHex() const
uint64_t GetSizeWithAncestors() const
Definition: txmempool.h:132
UniValue gettxout(const JSONRPCRequest &request)
void BIP9SoftForkDescPushBack(UniValue &bip9_softforks, const std::string &name, const Consensus::Params &consensusParams, Consensus::DeploymentPos id)
void PollStart()
Start long-polling.
Definition: server.cpp:369
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:526
CCriticalSection cs
Definition: txmempool.h:523
TransactionException excepted
Definition: Transaction.h:72
UniValue mempoolToJSON(bool fVerbose)
Mempool to JSON.
Definition: blockchain.cpp:507
#define b(i, j)
Address address
Definition: ExtVMFace.h:105
bool PollAlive()
Returns whether the underlying long-poll connection is still alive.
Definition: server.cpp:365
int BIP65Height
Block height at which BIP65 becomes active.
Definition: params.h:48
dev::h160 parseParamH160(const UniValue &val)
bool exists(uint256 hash) const
Definition: txmempool.h:671
int nVersion
block header
Definition: chain.h:220
bool CheckHex(const std::string &str)
Definition: util.cpp:985
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
Definition: chain.cpp:64
WaitForLogsParams(const UniValue &params)
std::string GetRejectReason() const
Definition: validation.h:89
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:138
Database error.
Definition: protocol.h:54
#define LogPrint(category,...)
Definition: util.h:164
std::string ToString() const
Definition: block.cpp:66
UniValue getstorage(const JSONRPCRequest &request)
Definition: blockchain.cpp:803
void SetRoot(dev::h256 newHashStateRoot, dev::h256 newHashUTXORoot)
Definition: fascstate.h:140
bool fHelp
Definition: server.h:60
std::vector< ResultExecute > CallContract(const dev::Address &addrContract, std::vector< unsigned char > opcode, const dev::Address &sender, uint64_t gasLimit)
void PollPing()
Ping long-poll connection with an empty character to make sure it&#39;s still alive.
Definition: server.cpp:378
txnouttype
Definition: standard.h:51
Capture information about block/transaction validation.
Definition: validation.h:27
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Definition: params.h:33
256-bit opaque blob.
Definition: uint256.h:132
bool IsLegacyFormat() const
Definition: chain.cpp:145
ArgsManager gArgs
Definition: util.cpp:94
u256 gasForDeposit
Amount of gas remaining for the code deposit phase.
Definition: Transaction.h:78
const CTransaction & GetTx() const
Definition: txmempool.h:102
std::vector< CTransactionRef > vtx
Definition: block.h:159
std::vector< h160 > h160s
Definition: FixedHash.h:346
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:177
UniValue invalidateblock(const JSONRPCRequest &request)
int64_t GetModifiedFee() const
Definition: txmempool.h:110
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:60
#define ARRAYLEN(array)
dev::eth::TransactionException excepted
bytes data
Definition: ExtVMFace.h:107
double GetDifficultyBitcoin(const CBlockIndex *blockindex)
Definition: blockchain.cpp:84
PlatformStyle::TableColorType type
Definition: rpcconsole.cpp:61
void transactionReceiptInfoToJSON(const TransactionReceiptInfo &resExec, UniValue &entry)
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
UniValue getrawmempool(const JSONRPCRequest &request)
Definition: blockchain.cpp:535
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:177
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
int RPCSerializationFlags()
Definition: server.cpp:591
UniValue getblockchaininfo(const JSONRPCRequest &request)
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
UniValue getblockheader(const JSONRPCRequest &request)
Definition: blockchain.cpp:871
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:530
unsigned depositSize
Amount of code of the creation&#39;s attempted deposit.
Definition: Transaction.h:77
const UniValue NullUniValue
Definition: univalue.cpp:15
uint256 hashUTXORoot
Definition: chain.h:227
int elapsed
Definition: versionbits.h:43
void writeVMlog(const std::vector< ResultExecute > &res, const CTransaction &tx, const CBlock &block)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:131
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:253
#define e(i)
Definition: sha.cpp:733
bool possible
Definition: versionbits.h:45
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:130
void parseFilter(const UniValue &val)
uint256 hashStateRoot
Definition: block.h:50
const uint256 & GetHash() const
Definition: transaction.h:325
std::vector< unsigned char > valtype
Definition: fascstate.h:17
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:308
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
Definition: core_write.cpp:156
FixedHash< 20 > h160
Definition: FixedHash.h:341
bool get_bool() const
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: txdb.cpp:177
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
std::string EntryDescriptionString()
Definition: blockchain.cpp:457
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:29
CCoinsViewDB * pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:251
uint256 hashStateRoot
Definition: chain.h:226
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:85
full block available in blk*.dat
Definition: chain.h:161
uint256 hashUTXORoot
Definition: block.h:51
std::vector< h256 > h256s
Definition: FixedHash.h:345
bool isNull() const
Definition: univalue.h:79
UniValue blockToJSON(const CBlock &block, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
Definition: blockchain.cpp:175
COutPoint prevout
Definition: transaction.h:64
std::vector< boost::optional< dev::h256 > > topics
void ScriptPubKeyToJSON(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Config::Pair_type Pair
int64_t GetMedianTimePast() const
Definition: chain.h:341
uint256 nNonce
Definition: chain.h:225
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:743
int32_t nVersion
Definition: block.h:43
uint8_t const * data
Definition: sha3.h:19
BlockMap mapBlockIndex
Definition: validation.cpp:79
int ReadHeightIndex(int low, int high, int minconf, std::vector< std::vector< uint256 >> &blocksOfHashes, std::set< dev::h160 > const &addresses)
Iterates through blocks by height, starting from low.
Definition: txdb.cpp:273
bool isStr() const
Definition: univalue.h:83
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:209
std::unique_ptr< FascState > globalState
Global state.
Definition: validation.cpp:70
StorageResults * pstorageresult
Definition: validation.cpp:254
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:158
std::vector< unsigned char > nSolution
Definition: chain.h:229
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:72
std::string itostr(int n)
size_t GetTxSize() const
Definition: txmempool.cpp:60
uint256 GetBlockHash() const
Definition: chain.h:324
std::vector< LogEntry > LogEntries
Definition: ExtVMFace.h:110
uint32_t nBits
Definition: block.h:49
const_iterator end() const
Definition: streams.h:235
std::string hex() const
Definition: FixedHash.h:130
std::vector< unsigned char > ParseHex(const char *psz)
LogEntries const & log() const
Definition: ExtVMFace.h:88
uint256 hash
Definition: transaction.h:21