]> Git Repo - VerusCoin.git/blame - src/rpcblockchain.cpp
test
[VerusCoin.git] / src / rpcblockchain.cpp
CommitLineData
c625ae04 1// Copyright (c) 2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
72fb3d29 3// Distributed under the MIT software license, see the accompanying
c625ae04
JG
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
ac14bcc1 6#include "checkpoints.h"
da29ecbc 7#include "consensus/validation.h"
51ed9ec9 8#include "main.h"
da29ecbc 9#include "primitives/transaction.h"
ac14bcc1 10#include "rpcserver.h"
51ed9ec9 11#include "sync.h"
ad49c256 12#include "util.h"
51ed9ec9
BD
13
14#include <stdint.h>
15
16#include "json/json_spirit_value.h"
c625ae04
JG
17
18using namespace json_spirit;
19using namespace std;
20
73351c36 21extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry);
be066fad 22void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex);
4e68391a 23
695a7a88 24double GetDifficultyINTERNAL(const CBlockIndex* blockindex, bool networkDifficulty)
c625ae04
JG
25{
26 // Floating point number that is a multiple of the minimum difficulty,
27 // minimum difficulty = 1.0.
28 if (blockindex == NULL)
29 {
4c6d41b8 30 if (chainActive.Tip() == NULL)
c625ae04
JG
31 return 1.0;
32 else
4c6d41b8 33 blockindex = chainActive.Tip();
c625ae04
JG
34 }
35
333ea3c4
JG
36 uint32_t bits;
37 if (networkDifficulty) {
38 bits = GetNextWorkRequired(blockindex, nullptr, Params().GetConsensus());
39 } else {
40 bits = blockindex->nBits;
695a7a88
JG
41 }
42
333ea3c4 43 uint32_t powLimit =
f50e8313 44 UintToArith256(Params().GetConsensus().powLimit).GetCompact();
333ea3c4 45 int nShift = (bits >> 24) & 0xff;
24809b16 46 int nShiftAmount = (powLimit >> 24) & 0xff;
c625ae04
JG
47
48 double dDiff =
24809b16 49 (double)(powLimit & 0x00ffffff) /
333ea3c4 50 (double)(bits & 0x00ffffff);
c625ae04 51
24809b16 52 while (nShift < nShiftAmount)
c625ae04
JG
53 {
54 dDiff *= 256.0;
55 nShift++;
56 }
24809b16 57 while (nShift > nShiftAmount)
c625ae04
JG
58 {
59 dDiff /= 256.0;
60 nShift--;
61 }
62
63 return dDiff;
64}
65
695a7a88
JG
66double GetDifficulty(const CBlockIndex* blockindex)
67{
68 return GetDifficultyINTERNAL(blockindex, false);
69}
70
71double GetNetworkDifficulty(const CBlockIndex* blockindex)
72{
73 return GetDifficultyINTERNAL(blockindex, true);
74}
75
c625ae04 76
73351c36 77Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
c625ae04
JG
78{
79 Object result;
80 result.push_back(Pair("hash", block.GetHash().GetHex()));
57153d4e
WL
81 int confirmations = -1;
82 // Only report confirmations if the block is on the main chain
83 if (chainActive.Contains(blockindex))
84 confirmations = chainActive.Height() - blockindex->nHeight + 1;
85 result.push_back(Pair("confirmations", confirmations));
c625ae04
JG
86 result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
87 result.push_back(Pair("height", blockindex->nHeight));
88 result.push_back(Pair("version", block.nVersion));
89 result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
90 Array txs;
91 BOOST_FOREACH(const CTransaction&tx, block.vtx)
73351c36
JS
92 {
93 if(txDetails)
94 {
95 Object objTx;
4f152496 96 TxToJSON(tx, uint256(), objTx);
73351c36
JS
97 txs.push_back(objTx);
98 }
99 else
805344dc 100 txs.push_back(tx.GetHash().GetHex());
73351c36 101 }
c625ae04 102 result.push_back(Pair("tx", txs));
d56e30ca 103 result.push_back(Pair("time", block.GetBlockTime()));
fdda3c50 104 result.push_back(Pair("nonce", block.nNonce.GetHex()));
e1dde421 105 result.push_back(Pair("solution", HexStr(block.nSolution)));
645d497a 106 result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
c625ae04 107 result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
1b3656d5 108 result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
c625ae04
JG
109
110 if (blockindex->pprev)
111 result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
4c6d41b8 112 CBlockIndex *pnext = chainActive.Next(blockindex);
0fe8010a
PW
113 if (pnext)
114 result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
c625ae04
JG
115 return result;
116}
117
118
119Value getblockcount(const Array& params, bool fHelp)
120{
121 if (fHelp || params.size() != 0)
122 throw runtime_error(
123 "getblockcount\n"
a6099ef3 124 "\nReturns the number of blocks in the longest block chain.\n"
125 "\nResult:\n"
126 "n (numeric) The current block count\n"
127 "\nExamples:\n"
128 + HelpExampleCli("getblockcount", "")
129 + HelpExampleRpc("getblockcount", "")
130 );
c625ae04 131
4401b2d7 132 LOCK(cs_main);
4c6d41b8 133 return chainActive.Height();
c625ae04
JG
134}
135
091aa8da
JG
136Value getbestblockhash(const Array& params, bool fHelp)
137{
138 if (fHelp || params.size() != 0)
139 throw runtime_error(
140 "getbestblockhash\n"
a6099ef3 141 "\nReturns the hash of the best (tip) block in the longest block chain.\n"
142 "\nResult\n"
143 "\"hex\" (string) the block hash hex encoded\n"
144 "\nExamples\n"
145 + HelpExampleCli("getbestblockhash", "")
146 + HelpExampleRpc("getbestblockhash", "")
147 );
091aa8da 148
4401b2d7 149 LOCK(cs_main);
4c6d41b8 150 return chainActive.Tip()->GetBlockHash().GetHex();
091aa8da 151}
c625ae04
JG
152
153Value getdifficulty(const Array& params, bool fHelp)
154{
155 if (fHelp || params.size() != 0)
156 throw runtime_error(
157 "getdifficulty\n"
a6099ef3 158 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
159 "\nResult:\n"
160 "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
161 "\nExamples:\n"
162 + HelpExampleCli("getdifficulty", "")
163 + HelpExampleRpc("getdifficulty", "")
164 );
c625ae04 165
4401b2d7 166 LOCK(cs_main);
695a7a88 167 return GetNetworkDifficulty();
c625ae04
JG
168}
169
170
c625ae04
JG
171Value getrawmempool(const Array& params, bool fHelp)
172{
4d707d51 173 if (fHelp || params.size() > 1)
c625ae04 174 throw runtime_error(
4d707d51 175 "getrawmempool ( verbose )\n"
a6099ef3 176 "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
4d707d51
GA
177 "\nArguments:\n"
178 "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
179 "\nResult: (for verbose = false):\n"
180 "[ (json array of string)\n"
a6099ef3 181 " \"transactionid\" (string) The transaction id\n"
182 " ,...\n"
183 "]\n"
4d707d51
GA
184 "\nResult: (for verbose = true):\n"
185 "{ (json object)\n"
186 " \"transactionid\" : { (json object)\n"
187 " \"size\" : n, (numeric) transaction size in bytes\n"
188 " \"fee\" : n, (numeric) transaction fee in bitcoins\n"
189 " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
190 " \"height\" : n, (numeric) block height when transaction entered pool\n"
191 " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
192 " \"currentpriority\" : n, (numeric) transaction priority now\n"
193 " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
194 " \"transactionid\", (string) parent transaction id\n"
195 " ... ]\n"
196 " }, ...\n"
803f51ef 197 "}\n"
a6099ef3 198 "\nExamples\n"
4d707d51
GA
199 + HelpExampleCli("getrawmempool", "true")
200 + HelpExampleRpc("getrawmempool", "true")
a6099ef3 201 );
c625ae04 202
4401b2d7
EL
203 LOCK(cs_main);
204
4d707d51
GA
205 bool fVerbose = false;
206 if (params.size() > 0)
207 fVerbose = params[0].get_bool();
c625ae04 208
4d707d51
GA
209 if (fVerbose)
210 {
211 LOCK(mempool.cs);
212 Object o;
213 BOOST_FOREACH(const PAIRTYPE(uint256, CTxMemPoolEntry)& entry, mempool.mapTx)
214 {
215 const uint256& hash = entry.first;
216 const CTxMemPoolEntry& e = entry.second;
217 Object info;
218 info.push_back(Pair("size", (int)e.GetTxSize()));
219 info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
d56e30ca 220 info.push_back(Pair("time", e.GetTime()));
4d707d51
GA
221 info.push_back(Pair("height", (int)e.GetHeight()));
222 info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
223 info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
224 const CTransaction& tx = e.GetTx();
225 set<string> setDepends;
226 BOOST_FOREACH(const CTxIn& txin, tx.vin)
227 {
228 if (mempool.exists(txin.prevout.hash))
229 setDepends.insert(txin.prevout.hash.ToString());
230 }
231 Array depends(setDepends.begin(), setDepends.end());
232 info.push_back(Pair("depends", depends));
233 o.push_back(Pair(hash.ToString(), info));
234 }
235 return o;
236 }
237 else
238 {
239 vector<uint256> vtxid;
240 mempool.queryHashes(vtxid);
c625ae04 241
4d707d51
GA
242 Array a;
243 BOOST_FOREACH(const uint256& hash, vtxid)
244 a.push_back(hash.ToString());
245
246 return a;
247 }
c625ae04
JG
248}
249
250Value getblockhash(const Array& params, bool fHelp)
251{
252 if (fHelp || params.size() != 1)
253 throw runtime_error(
a6099ef3 254 "getblockhash index\n"
255 "\nReturns hash of block in best-block-chain at index provided.\n"
256 "\nArguments:\n"
257 "1. index (numeric, required) The block index\n"
258 "\nResult:\n"
259 "\"hash\" (string) The block hash\n"
260 "\nExamples:\n"
261 + HelpExampleCli("getblockhash", "1000")
262 + HelpExampleRpc("getblockhash", "1000")
263 );
c625ae04 264
4401b2d7
EL
265 LOCK(cs_main);
266
c625ae04 267 int nHeight = params[0].get_int();
4c6d41b8 268 if (nHeight < 0 || nHeight > chainActive.Height())
6261e6e6 269 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
c625ae04 270
4c6d41b8
PW
271 CBlockIndex* pblockindex = chainActive[nHeight];
272 return pblockindex->GetBlockHash().GetHex();
c625ae04
JG
273}
274
275Value getblock(const Array& params, bool fHelp)
276{
23319521 277 if (fHelp || params.size() < 1 || params.size() > 2)
c625ae04 278 throw runtime_error(
a6099ef3 279 "getblock \"hash\" ( verbose )\n"
280 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
281 "If verbose is true, returns an Object with information about block <hash>.\n"
282 "\nArguments:\n"
283 "1. \"hash\" (string, required) The block hash\n"
284 "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
285 "\nResult (for verbose = true):\n"
286 "{\n"
287 " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
57153d4e 288 " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
a6099ef3 289 " \"size\" : n, (numeric) The block size\n"
290 " \"height\" : n, (numeric) The block height or index\n"
291 " \"version\" : n, (numeric) The block version\n"
292 " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
293 " \"tx\" : [ (array of string) The transaction ids\n"
294 " \"transactionid\" (string) The transaction id\n"
295 " ,...\n"
296 " ],\n"
297 " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
298 " \"nonce\" : n, (numeric) The nonce\n"
299 " \"bits\" : \"1d00ffff\", (string) The bits\n"
300 " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
301 " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
302 " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
303 "}\n"
304 "\nResult (for verbose=false):\n"
305 "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
306 "\nExamples:\n"
307 + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
308 + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
23319521 309 );
c625ae04 310
4401b2d7
EL
311 LOCK(cs_main);
312
c625ae04 313 std::string strHash = params[0].get_str();
34cdc411 314 uint256 hash(uint256S(strHash));
c625ae04 315
23319521
LD
316 bool fVerbose = true;
317 if (params.size() > 1)
318 fVerbose = params[1].get_bool();
319
c625ae04 320 if (mapBlockIndex.count(hash) == 0)
738835d7 321 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
c625ae04
JG
322
323 CBlock block;
324 CBlockIndex* pblockindex = mapBlockIndex[hash];
954d2e72 325
03c56872
JS
326 if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
327 throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
328
f2dd868d 329 if(!ReadBlockFromDisk(block, pblockindex))
954d2e72 330 throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
c625ae04 331
23319521
LD
332 if (!fVerbose)
333 {
334 CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
335 ssBlock << block;
336 std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
337 return strHex;
338 }
339
c625ae04
JG
340 return blockToJSON(block, pblockindex);
341}
342
beeb5761
PW
343Value gettxoutsetinfo(const Array& params, bool fHelp)
344{
345 if (fHelp || params.size() != 0)
346 throw runtime_error(
347 "gettxoutsetinfo\n"
a6099ef3 348 "\nReturns statistics about the unspent transaction output set.\n"
349 "Note this call may take some time.\n"
350 "\nResult:\n"
351 "{\n"
352 " \"height\":n, (numeric) The current block height (index)\n"
353 " \"bestblock\": \"hex\", (string) the best block hash hex\n"
354 " \"transactions\": n, (numeric) The number of transactions\n"
355 " \"txouts\": n, (numeric) The number of output transactions\n"
356 " \"bytes_serialized\": n, (numeric) The serialized size\n"
357 " \"hash_serialized\": \"hash\", (string) The serialized hash\n"
358 " \"total_amount\": x.xxx (numeric) The total amount\n"
359 "}\n"
360 "\nExamples:\n"
361 + HelpExampleCli("gettxoutsetinfo", "")
362 + HelpExampleRpc("gettxoutsetinfo", "")
363 );
beeb5761 364
4401b2d7
EL
365 LOCK(cs_main);
366
beeb5761
PW
367 Object ret;
368
369 CCoinsStats stats;
51ce901a 370 FlushStateToDisk();
beeb5761 371 if (pcoinsTip->GetStats(stats)) {
4b61a6a4 372 ret.push_back(Pair("height", (int64_t)stats.nHeight));
e31aa7c9 373 ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
4b61a6a4
KD
374 ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
375 ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
376 ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
e31aa7c9
PW
377 ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
378 ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
beeb5761
PW
379 }
380 return ret;
381}
c625ae04 382
17878015 383uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
7a77c443 384uint32_t komodo_txtime(uint256 hash);
0bda6249 385uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume);
d836ec3f 386int32_t komodo_paxprices(int32_t *heights,uint64_t *prices,int32_t max,char *base,char *rel);
1e9d15c6 387int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height);
388char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len);
50760585 389uint32_t komodo_interest_args(int32_t *txheightp,uint32_t *tiptimep,uint64_t *valuep,uint256 hash,int32_t n);
e596e202 390
1e9d15c6 391Value notaries(const Array& params, bool fHelp)
392{
ff4657a7 393 Array a; Object ret; int32_t i,j,n,m; char *hexstr; uint8_t pubkeys[64][33]; char btcaddr[64],kmdaddr[64],*ptr;
1e9d15c6 394 if ( fHelp || params.size() != 1 )
395 throw runtime_error("notaries height\n");
396 LOCK(cs_main);
a8af456e 397 int32_t height = atoi(params[0].get_str().c_str());
895f044a 398 if ( height < 0 )
399 height = 0;
6677fa31 400 //fprintf(stderr,"notaries as of height.%d\n",height);
895f044a 401 if ( height > chainActive.Height()+20000 )
1e9d15c6 402 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
403 else
404 {
1e9d15c6 405 if ( (n= komodo_notaries(pubkeys,height)) > 0 )
406 {
407 for (i=0; i<n; i++)
408 {
98622aa7 409 Object item;
ff4657a7 410 std::string btcaddress,kmdaddress,hex;
1ffa653a 411 hex.resize(66);
412 hexstr = (char *)hex.data();
413 for (j=0; j<33; j++)
414 sprintf(&hexstr[j*2],"%02x",pubkeys[i][j]);
415 item.push_back(Pair("pubkey", hex));
416
1e9d15c6 417 bitcoin_address(btcaddr,0,pubkeys[i],33);
418 m = (int32_t)strlen(btcaddr);
69900ca4 419 btcaddress.resize(m);
1e9d15c6 420 ptr = (char *)btcaddress.data();
6eb6f5f7 421 memcpy(ptr,btcaddr,m);
1ffa653a 422 item.push_back(Pair("BTCaddress", btcaddress));
423
1e9d15c6 424 bitcoin_address(kmdaddr,60,pubkeys[i],33);
425 m = (int32_t)strlen(kmdaddr);
69900ca4 426 kmdaddress.resize(m);
1e9d15c6 427 ptr = (char *)kmdaddress.data();
69900ca4 428 memcpy(ptr,kmdaddr,m);
1e9d15c6 429 item.push_back(Pair("KMDaddress", kmdaddress));
430 a.push_back(item);
431 }
432 }
433 ret.push_back(Pair("notaries", a));
434 }
435 return ret;
436}
a9869d0d 437
438Value paxprice(const Array& params, bool fHelp)
439{
1f346363 440 if ( fHelp || params.size() < 3 || params.size() > 4 )
05f1a5d1 441 throw runtime_error("paxprice \"base\" \"rel\" height amount\n");
a9869d0d 442 LOCK(cs_main);
0bda6249 443 Object ret; uint64_t basevolume=0,relvolume,seed;
a9869d0d 444 std::string base = params[0].get_str();
445 std::string rel = params[1].get_str();
96eb75ee 446 int32_t height = atoi(params[2].get_str().c_str());
05f1a5d1 447 if ( params.size() == 3 || (basevolume= COIN * atof(params[3].get_str().c_str())) == 0 )
1f346363 448 basevolume = COIN;
0bda6249 449 relvolume = komodo_paxprice(&seed,height,(char *)base.c_str(),(char *)rel.c_str(),basevolume);
a9869d0d 450 ret.push_back(Pair("base", base));
451 ret.push_back(Pair("rel", rel));
452 ret.push_back(Pair("height", height));
73ccdf55 453 char seedstr[32];
454 sprintf(seedstr,"%llu",(long long)seed);
455 ret.push_back(Pair("seed", seedstr));
d019c447 456 if ( height < 0 || height > chainActive.Height() )
457 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
458 else
1f346363 459 {
d019c447 460 CBlockIndex *pblockindex = chainActive[height];
1d8bddf7 461 ret.push_back(Pair("timestamp", (int64_t)pblockindex->nTime));
d019c447 462 if ( basevolume != 0 && relvolume != 0 )
463 {
464 ret.push_back(Pair("price",((double)relvolume / (double)basevolume)));
465 ret.push_back(Pair("invprice",((double)basevolume / (double)relvolume)));
466 ret.push_back(Pair("basevolume", ValueFromAmount(basevolume)));
467 ret.push_back(Pair("relvolume", ValueFromAmount(relvolume)));
46e78b7f 468 } else ret.push_back(Pair("error", "overflow or error in one or more of parameters"));
a4ebaad7 469 }
470 return ret;
471}
472
473Value paxprices(const Array& params, bool fHelp)
474{
475 if ( fHelp || params.size() != 3 )
d836ec3f 476 throw runtime_error("paxprices \"base\" \"rel\" maxsamples\n");
a4ebaad7 477 LOCK(cs_main);
d836ec3f 478 Object ret; uint64_t relvolume,prices[4096]; uint32_t i,n; int32_t heights[sizeof(prices)/sizeof(*prices)];
a4ebaad7 479 std::string base = params[0].get_str();
480 std::string rel = params[1].get_str();
0d195951 481 int32_t maxsamples = atoi(params[2].get_str().c_str());
05dfe053 482 if ( maxsamples < 1 )
483 maxsamples = 1;
d836ec3f 484 else if ( maxsamples > sizeof(heights)/sizeof(*heights) )
485 maxsamples = sizeof(heights)/sizeof(*heights);
a4ebaad7 486 ret.push_back(Pair("base", base));
487 ret.push_back(Pair("rel", rel));
d836ec3f 488 n = komodo_paxprices(heights,prices,maxsamples,(char *)base.c_str(),(char *)rel.c_str());
96eb75ee 489 Array a;
490 for (i=0; i<n; i++)
a4ebaad7 491 {
96eb75ee 492 Object item;
56d91e9c 493 if ( heights[i] < 0 || heights[i] > chainActive.Height() )
494 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
495 else
496 {
497 CBlockIndex *pblockindex = chainActive[heights[i]];
498
499 item.push_back(Pair("t", (int64_t)pblockindex->nTime));
500 item.push_back(Pair("p", (double)prices[i] / COIN));
501 a.push_back(item);
502 }
1f346363 503 }
96eb75ee 504 ret.push_back(Pair("array", a));
a9869d0d 505 return ret;
506}
7a77c443 507
798f28c7 508uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue);
0fec0cc4 509
beeb5761
PW
510Value gettxout(const Array& params, bool fHelp)
511{
512 if (fHelp || params.size() < 2 || params.size() > 3)
513 throw runtime_error(
a6099ef3 514 "gettxout \"txid\" n ( includemempool )\n"
515 "\nReturns details about an unspent transaction output.\n"
516 "\nArguments:\n"
517 "1. \"txid\" (string, required) The transaction id\n"
518 "2. n (numeric, required) vout value\n"
519 "3. includemempool (boolean, optional) Whether to included the mem pool\n"
520 "\nResult:\n"
521 "{\n"
522 " \"bestblock\" : \"hash\", (string) the block hash\n"
523 " \"confirmations\" : n, (numeric) The number of confirmations\n"
524 " \"value\" : x.xxx, (numeric) The transaction value in btc\n"
525 " \"scriptPubKey\" : { (json object)\n"
526 " \"asm\" : \"code\", (string) \n"
527 " \"hex\" : \"hex\", (string) \n"
528 " \"reqSigs\" : n, (numeric) Number of required signatures\n"
529 " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
530 " \"addresses\" : [ (array of string) array of bitcoin addresses\n"
531 " \"bitcoinaddress\" (string) bitcoin address\n"
532 " ,...\n"
533 " ]\n"
534 " },\n"
535 " \"version\" : n, (numeric) The version\n"
536 " \"coinbase\" : true|false (boolean) Coinbase or not\n"
537 "}\n"
538
539 "\nExamples:\n"
540 "\nGet unspent transactions\n"
541 + HelpExampleCli("listunspent", "") +
542 "\nView the details\n"
543 + HelpExampleCli("gettxout", "\"txid\" 1") +
544 "\nAs a json rpc call\n"
545 + HelpExampleRpc("gettxout", "\"txid\", 1")
546 );
c625ae04 547
4401b2d7
EL
548 LOCK(cs_main);
549
beeb5761
PW
550 Object ret;
551
552 std::string strHash = params[0].get_str();
34cdc411 553 uint256 hash(uint256S(strHash));
beeb5761
PW
554 int n = params[1].get_int();
555 bool fMempool = true;
556 if (params.size() > 2)
557 fMempool = params[2].get_bool();
558
559 CCoins coins;
560 if (fMempool) {
561 LOCK(mempool.cs);
7c70438d 562 CCoinsViewMemPool view(pcoinsTip, mempool);
beeb5761
PW
563 if (!view.GetCoins(hash, coins))
564 return Value::null;
565 mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
566 } else {
567 if (!pcoinsTip->GetCoins(hash, coins))
568 return Value::null;
569 }
570 if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
571 return Value::null;
572
145d5be8 573 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
7a77c443 574 CBlockIndex *pindex = it->second;
84674082 575 ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
beeb5761
PW
576 if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
577 ret.push_back(Pair("confirmations", 0));
cad0d1ca 578 else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
4e68391a 579 ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
798f28c7 580 uint64_t interest; int32_t txheight; uint32_t locktime;
581 if ( (interest= komodo_accrued_interest(&txheight,&locktime,hash,n,coins.nHeight,coins.vout[n].nValue)) != 0 )
0fec0cc4 582 ret.push_back(Pair("interest", ValueFromAmount(interest)));
beeb5761 583 Object o;
be066fad 584 ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
beeb5761
PW
585 ret.push_back(Pair("scriptPubKey", o));
586 ret.push_back(Pair("version", coins.nVersion));
587 ret.push_back(Pair("coinbase", coins.fCoinBase));
588
589 return ret;
590}
c625ae04 591
29eccc7c 592int32_t gettxout_scriptPubKey(uint8_t *scriptPubKey,int32_t maxsize,uint256 txid,int32_t n)
fc318ffe 593{
594 int32_t i,m; uint8_t *ptr;
595 LOCK(cs_main);
596 CCoins coins;
29eccc7c 597 if ( 1 )
fc318ffe 598 {
599 LOCK(mempool.cs);
600 CCoinsViewMemPool view(pcoinsTip,mempool);
601 if ( view.GetCoins(txid,coins) == 0 )
602 return(-1);
603 mempool.pruneSpent(txid, coins); // TODO: this should be done by the CCoinsViewMemPool
604 } else if ( pcoinsTip->GetCoins(txid,coins) == 0 )
605 return(-1);
606 if ( n < 0 || (unsigned int)n >= coins.vout.size() || coins.vout[n].IsNull() )
607 return(-1);
608 ptr = (uint8_t *)coins.vout[n].scriptPubKey.data();
609 m = coins.vout[n].scriptPubKey.size();
610 for (i=0; i<maxsize&&i<m; i++)
611 scriptPubKey[i] = ptr[i];
612 return(i);
613}
614
f5906533
JG
615Value verifychain(const Array& params, bool fHelp)
616{
617 if (fHelp || params.size() > 2)
618 throw runtime_error(
a6099ef3 619 "verifychain ( checklevel numblocks )\n"
620 "\nVerifies blockchain database.\n"
621 "\nArguments:\n"
6943cb9b
PK
622 "1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n"
623 "2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
a6099ef3 624 "\nResult:\n"
625 "true|false (boolean) Verified or not\n"
626 "\nExamples:\n"
627 + HelpExampleCli("verifychain", "")
628 + HelpExampleRpc("verifychain", "")
629 );
f5906533 630
4401b2d7
EL
631 LOCK(cs_main);
632
f5906533
JG
633 int nCheckLevel = GetArg("-checklevel", 3);
634 int nCheckDepth = GetArg("-checkblocks", 288);
635 if (params.size() > 0)
636 nCheckLevel = params[0].get_int();
637 if (params.size() > 1)
638 nCheckDepth = params[1].get_int();
639
2e280311 640 return CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth);
f5906533 641}
c625ae04 642
ba1da90b
WL
643/** Implementation of IsSuperMajority with better feedback */
644Object SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams)
645{
646 int nFound = 0;
647 CBlockIndex* pstart = pindex;
648 for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++)
649 {
650 if (pstart->nVersion >= minVersion)
651 ++nFound;
652 pstart = pstart->pprev;
653 }
654
655 Object rv;
656 rv.push_back(Pair("status", nFound >= nRequired));
657 rv.push_back(Pair("found", nFound));
658 rv.push_back(Pair("required", nRequired));
659 rv.push_back(Pair("window", consensusParams.nMajorityWindow));
660 return rv;
661}
662
663Object SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
664{
665 Object rv;
666 rv.push_back(Pair("id", name));
667 rv.push_back(Pair("version", version));
668 rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams)));
669 rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams)));
670 return rv;
671}
672
d387b8ec
WL
673Value getblockchaininfo(const Array& params, bool fHelp)
674{
675 if (fHelp || params.size() != 0)
676 throw runtime_error(
677 "getblockchaininfo\n"
678 "Returns an object containing various state info regarding block chain processing.\n"
679 "\nResult:\n"
680 "{\n"
f6984e81 681 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
d387b8ec 682 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
ad6e6017 683 " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
d387b8ec
WL
684 " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
685 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
686 " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
687 " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
ba1da90b
WL
688 " \"softforks\": [ (array) status of softforks in progress\n"
689 " {\n"
690 " \"id\": \"xxxx\", (string) name of softfork\n"
691 " \"version\": xx, (numeric) block version\n"
692 " \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n"
693 " \"status\": xx, (boolean) true if threshold reached\n"
694 " \"found\": xx, (numeric) number of blocks with the new version found\n"
695 " \"required\": xx, (numeric) number of blocks required to trigger\n"
696 " \"window\": xx, (numeric) maximum size of examined window of recent blocks\n"
697 " },\n"
698 " \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n"
699 " }, ...\n"
700 " ]\n"
d387b8ec
WL
701 "}\n"
702 "\nExamples:\n"
703 + HelpExampleCli("getblockchaininfo", "")
704 + HelpExampleRpc("getblockchaininfo", "")
705 );
706
4401b2d7
EL
707 LOCK(cs_main);
708
d387b8ec 709 Object obj;
f5ae6c98
PK
710 obj.push_back(Pair("chain", Params().NetworkIDString()));
711 obj.push_back(Pair("blocks", (int)chainActive.Height()));
ad6e6017 712 obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
f5ae6c98 713 obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
695a7a88 714 obj.push_back(Pair("difficulty", (double)GetNetworkDifficulty()));
11982d36 715 obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip())));
f5ae6c98 716 obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
1b2e5555 717 obj.push_back(Pair("pruned", fPruneMode));
ba1da90b
WL
718
719 const Consensus::Params& consensusParams = Params().GetConsensus();
720 CBlockIndex* tip = chainActive.Tip();
721 Array softforks;
722 softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
723 softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
6af25b0f 724 softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
ba1da90b
WL
725 obj.push_back(Pair("softforks", softforks));
726
1b2e5555
JS
727 if (fPruneMode)
728 {
729 CBlockIndex *block = chainActive.Tip();
730 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
731 block = block->pprev;
732
733 obj.push_back(Pair("pruneheight", block->nHeight));
734 }
d387b8ec
WL
735 return obj;
736}
b33bd7a3 737
72fb3d29 738/** Comparison function for sorting the getchaintips heads. */
b33bd7a3
DK
739struct CompareBlocksByHeight
740{
741 bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
742 {
743 /* Make sure that unequal blocks with the same height do not compare
771d5002 744 equal. Use the pointers themselves to make a distinction. */
b33bd7a3
DK
745
746 if (a->nHeight != b->nHeight)
747 return (a->nHeight > b->nHeight);
748
749 return a < b;
750 }
751};
752
753Value getchaintips(const Array& params, bool fHelp)
754{
755 if (fHelp || params.size() != 0)
756 throw runtime_error(
757 "getchaintips\n"
758 "Return information about all known tips in the block tree,"
759 " including the main chain as well as orphaned branches.\n"
760 "\nResult:\n"
761 "[\n"
762 " {\n"
763 " \"height\": xxxx, (numeric) height of the chain tip\n"
764 " \"hash\": \"xxxx\", (string) block hash of the tip\n"
765 " \"branchlen\": 0 (numeric) zero for main chain\n"
1b91be49 766 " \"status\": \"active\" (string) \"active\" for the main chain\n"
b33bd7a3
DK
767 " },\n"
768 " {\n"
769 " \"height\": xxxx,\n"
770 " \"hash\": \"xxxx\",\n"
771 " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
1b91be49 772 " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
b33bd7a3
DK
773 " }\n"
774 "]\n"
32b93a1b
PW
775 "Possible values for status:\n"
776 "1. \"invalid\" This branch contains at least one invalid block\n"
777 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
778 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
779 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
780 "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
b33bd7a3
DK
781 "\nExamples:\n"
782 + HelpExampleCli("getchaintips", "")
783 + HelpExampleRpc("getchaintips", "")
784 );
785
4401b2d7
EL
786 LOCK(cs_main);
787
b33bd7a3
DK
788 /* Build up a list of chain tips. We start with the list of all
789 known blocks, and successively remove blocks that appear as pprev
790 of another block. */
791 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
792 BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
793 setTips.insert(item.second);
794 BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
795 {
796 const CBlockIndex* pprev = item.second->pprev;
797 if (pprev)
798 setTips.erase(pprev);
799 }
800
1b91be49
PW
801 // Always report the currently active tip.
802 setTips.insert(chainActive.Tip());
803
b33bd7a3
DK
804 /* Construct the output array. */
805 Array res;
806 BOOST_FOREACH(const CBlockIndex* block, setTips)
807 {
808 Object obj;
809 obj.push_back(Pair("height", block->nHeight));
810 obj.push_back(Pair("hash", block->phashBlock->GetHex()));
811
812 const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
813 obj.push_back(Pair("branchlen", branchLen));
814
1b91be49
PW
815 string status;
816 if (chainActive.Contains(block)) {
817 // This block is part of the currently active chain.
818 status = "active";
819 } else if (block->nStatus & BLOCK_FAILED_MASK) {
820 // This block or one of its ancestors is invalid.
821 status = "invalid";
822 } else if (block->nChainTx == 0) {
823 // This block cannot be connected because full block data for it or one of its parents is missing.
824 status = "headers-only";
825 } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
826 // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
827 status = "valid-fork";
828 } else if (block->IsValid(BLOCK_VALID_TREE)) {
829 // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
830 status = "valid-headers";
831 } else {
832 // No clue.
833 status = "unknown";
834 }
835 obj.push_back(Pair("status", status));
836
b33bd7a3
DK
837 res.push_back(obj);
838 }
839
840 return res;
841}
6f2c26a4
JG
842
843Value getmempoolinfo(const Array& params, bool fHelp)
844{
845 if (fHelp || params.size() != 0)
846 throw runtime_error(
847 "getmempoolinfo\n"
848 "\nReturns details on the active state of the TX memory pool.\n"
849 "\nResult:\n"
850 "{\n"
851 " \"size\": xxxxx (numeric) Current tx count\n"
852 " \"bytes\": xxxxx (numeric) Sum of all tx sizes\n"
853 "}\n"
854 "\nExamples:\n"
855 + HelpExampleCli("getmempoolinfo", "")
856 + HelpExampleRpc("getmempoolinfo", "")
857 );
858
859 Object ret;
860 ret.push_back(Pair("size", (int64_t) mempool.size()));
861 ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
862
863 return ret;
864}
865
9b0a8d31
PW
866Value invalidateblock(const Array& params, bool fHelp)
867{
868 if (fHelp || params.size() != 1)
869 throw runtime_error(
870 "invalidateblock \"hash\"\n"
871 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
872 "\nArguments:\n"
873 "1. hash (string, required) the hash of the block to mark as invalid\n"
874 "\nResult:\n"
875 "\nExamples:\n"
876 + HelpExampleCli("invalidateblock", "\"blockhash\"")
877 + HelpExampleRpc("invalidateblock", "\"blockhash\"")
878 );
879
880 std::string strHash = params[0].get_str();
34cdc411 881 uint256 hash(uint256S(strHash));
9b0a8d31
PW
882 CValidationState state;
883
884 {
885 LOCK(cs_main);
886 if (mapBlockIndex.count(hash) == 0)
887 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
888
889 CBlockIndex* pblockindex = mapBlockIndex[hash];
890 InvalidateBlock(state, pblockindex);
891 }
892
893 if (state.IsValid()) {
894 ActivateBestChain(state);
895 }
896
897 if (!state.IsValid()) {
898 throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
899 }
900
901 return Value::null;
902}
903
904Value reconsiderblock(const Array& params, bool fHelp)
905{
906 if (fHelp || params.size() != 1)
907 throw runtime_error(
908 "reconsiderblock \"hash\"\n"
909 "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
910 "This can be used to undo the effects of invalidateblock.\n"
911 "\nArguments:\n"
912 "1. hash (string, required) the hash of the block to reconsider\n"
913 "\nResult:\n"
914 "\nExamples:\n"
915 + HelpExampleCli("reconsiderblock", "\"blockhash\"")
916 + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
917 );
918
919 std::string strHash = params[0].get_str();
34cdc411 920 uint256 hash(uint256S(strHash));
9b0a8d31
PW
921 CValidationState state;
922
923 {
924 LOCK(cs_main);
925 if (mapBlockIndex.count(hash) == 0)
926 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
927
928 CBlockIndex* pblockindex = mapBlockIndex[hash];
929 ReconsiderBlock(state, pblockindex);
930 }
931
932 if (state.IsValid()) {
933 ActivateBestChain(state);
934 }
935
936 if (!state.IsValid()) {
937 throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
938 }
939
940 return Value::null;
941}
This page took 0.344496 seconds and 4 git commands to generate.