Rename fields
[novacoin.git] / src / rpcblockchain.cpp
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "main.h"
7 #include "bitcoinrpc.h"
8
9 using namespace json_spirit;
10 using namespace std;
11
12 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
13 extern enum Checkpoints::CPMode CheckpointsMode;
14
15 double GetDifficulty(const CBlockIndex* blockindex)
16 {
17     // Floating point number that is a multiple of the minimum difficulty,
18     // minimum difficulty = 1.0.
19     if (blockindex == NULL)
20     {
21         if (pindexBest == NULL)
22             return 1.0;
23         else
24             blockindex = GetLastBlockIndex(pindexBest, false);
25     }
26
27     int nShift = (blockindex->nBits >> 24) & 0xff;
28
29     double dDiff =
30         (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
31
32     while (nShift < 29)
33     {
34         dDiff *= 256.0;
35         nShift++;
36     }
37     while (nShift > 29)
38     {
39         dDiff /= 256.0;
40         nShift--;
41     }
42
43     return dDiff;
44 }
45
46 double GetPoWMHashPS()
47 {
48     int nPoWInterval = 72;
49     int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
50
51     CBlockIndex* pindex = pindexGenesisBlock;
52     CBlockIndex* pindexPrevWork = pindexGenesisBlock;
53
54     while (pindex)
55     {
56         if (pindex->IsProofOfWork())
57         {
58             int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
59             nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
60             nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
61             pindexPrevWork = pindex;
62         }
63
64         pindex = pindex->pnext;
65     }
66
67     return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
68 }
69
70 double GetPoSKernelPS()
71 {
72     int nPoSInterval = 72;
73     double dStakeKernelsTriedAvg = 0;
74     int nStakesHandled = 0, nStakesTime = 0;
75
76     CBlockIndex* pindex = pindexBest;;
77     CBlockIndex* pindexPrevStake = NULL;
78
79     while (pindex && nStakesHandled < nPoSInterval)
80     {
81         if (pindex->IsProofOfStake())
82         {
83             dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
84             nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
85             pindexPrevStake = pindex;
86             nStakesHandled++;
87         }
88
89         pindex = pindex->pprev;
90     }
91
92     return dStakeKernelsTriedAvg / nStakesTime;
93 }
94
95 Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
96 {
97     Object result;
98     result.push_back(Pair("hash", block.GetHash().GetHex()));
99     CMerkleTx txGen(block.vtx[0]);
100     txGen.SetMerkleBranch(&block);
101     result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
102     result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
103     result.push_back(Pair("height", blockindex->nHeight));
104     result.push_back(Pair("version", block.nVersion));
105     result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
106     result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
107     result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
108     result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
109     result.push_back(Pair("bits", HexBits(block.nBits)));
110     result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
111     result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
112     result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
113     if (blockindex->pprev)
114         result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
115     if (blockindex->pnext)
116         result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
117
118     result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
119     result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
120     result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
121     result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier)));
122     result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
123     Array txinfo;
124     BOOST_FOREACH (const CTransaction& tx, block.vtx)
125     {
126         if (fPrintTransactionDetail)
127         {
128             CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
129             ssTx << tx;
130             string strHex = HexStr(ssTx.begin(), ssTx.end());
131
132             txinfo.push_back(strHex);
133         }
134         else
135             txinfo.push_back(tx.GetHash().GetHex());
136     }
137
138     result.push_back(Pair("tx", txinfo));
139
140     if ( block.IsProofOfStake() || (!fTestNet && block.GetBlockTime() < ENTROPY_SWITCH_TIME) )
141         result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
142
143     return result;
144 }
145
146 Value getbestblockhash(const Array& params, bool fHelp)
147 {
148     if (fHelp || params.size() != 0)
149         throw runtime_error(
150             "getbestblockhash\n"
151             "Returns the hash of the best block in the longest block chain.");
152
153     return hashBestChain.GetHex();
154 }
155
156 Value getblockcount(const Array& params, bool fHelp)
157 {
158     if (fHelp || params.size() != 0)
159         throw runtime_error(
160             "getblockcount\n"
161             "Returns the number of blocks in the longest block chain.");
162
163     return nBestHeight;
164 }
165
166
167 Value getdifficulty(const Array& params, bool fHelp)
168 {
169     if (fHelp || params.size() != 0)
170         throw runtime_error(
171             "getdifficulty\n"
172             "Returns the difficulty as a multiple of the minimum difficulty.");
173
174     Object obj;
175     obj.push_back(Pair("proof-of-work",        GetDifficulty()));
176     obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
177     obj.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
178     return obj;
179 }
180
181
182 Value settxfee(const Array& params, bool fHelp)
183 {
184     if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
185         throw runtime_error(
186             "settxfee <amount>\n"
187             "<amount> is a real and is rounded to the nearest " + FormatMoney(MIN_TX_FEE));
188
189     nTransactionFee = AmountFromValue(params[0]);
190     nTransactionFee = (nTransactionFee / MIN_TX_FEE) * MIN_TX_FEE;  // round to minimum fee
191
192     return true;
193 }
194
195 Value getrawmempool(const Array& params, bool fHelp)
196 {
197     if (fHelp || params.size() != 0)
198         throw runtime_error(
199             "getrawmempool\n"
200             "Returns all transaction ids in memory pool.");
201
202     vector<uint256> vtxid;
203     mempool.queryHashes(vtxid);
204
205     Array a;
206     BOOST_FOREACH(const uint256& hash, vtxid)
207         a.push_back(hash.ToString());
208
209     return a;
210 }
211
212 Value getblockhash(const Array& params, bool fHelp)
213 {
214     if (fHelp || params.size() != 1)
215         throw runtime_error(
216             "getblockhash <index>\n"
217             "Returns hash of block in best-block-chain at <index>.");
218
219     int nHeight = params[0].get_int();
220     if (nHeight < 0 || nHeight > nBestHeight)
221         throw runtime_error("Block number out of range.");
222
223     CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
224     return pblockindex->phashBlock->GetHex();
225 }
226
227 Value getblock(const Array& params, bool fHelp)
228 {
229     if (fHelp || params.size() < 1 || params.size() > 2)
230         throw runtime_error(
231             "getblock <hash> [txinfo]\n"
232             "txinfo optional to print more detailed tx info\n"
233             "Returns details of a block with given block-hash.");
234
235     std::string strHash = params[0].get_str();
236     uint256 hash(strHash);
237
238     if (mapBlockIndex.count(hash) == 0)
239         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
240
241     CBlock block;
242     CBlockIndex* pblockindex = mapBlockIndex[hash];
243     block.ReadFromDisk(pblockindex, true);
244
245     return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
246 }
247
248 Value getblockbynumber(const Array& params, bool fHelp)
249 {
250     if (fHelp || params.size() < 1 || params.size() > 2)
251         throw runtime_error(
252             "getblock <number> [txinfo]\n"
253             "txinfo optional to print more detailed tx info\n"
254             "Returns details of a block with given block-number.");
255
256     int nHeight = params[0].get_int();
257     if (nHeight < 0 || nHeight > nBestHeight)
258         throw runtime_error("Block number out of range.");
259
260     CBlock block;
261     CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
262     while (pblockindex->nHeight > nHeight)
263         pblockindex = pblockindex->pprev;
264
265     uint256 hash = *pblockindex->phashBlock;
266
267     pblockindex = mapBlockIndex[hash];
268     block.ReadFromDisk(pblockindex, true);
269
270     return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
271 }
272
273 // get information of sync-checkpoint
274 Value getcheckpoint(const Array& params, bool fHelp)
275 {
276     if (fHelp || params.size() != 0)
277         throw runtime_error(
278             "getcheckpoint\n"
279             "Show info of synchronized checkpoint.\n");
280
281     Object result;
282     CBlockIndex* pindexCheckpoint;
283
284     result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
285     pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
286     result.push_back(Pair("height", pindexCheckpoint->nHeight));
287     result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
288
289     if (Checkpoints::checkpointMessage.vchSig.size() != 0)
290     {
291         Object msgdata;
292         CUnsignedSyncCheckpoint checkpoint;
293
294         CDataStream sMsg(Checkpoints::checkpointMessage.vchMsg, SER_NETWORK, PROTOCOL_VERSION);
295         sMsg >> checkpoint;
296
297         Object parsed; // message version and data (block hash)
298         parsed.push_back(Pair("version", checkpoint.nVersion));
299         parsed.push_back(Pair("hash", checkpoint.hashCheckpoint.GetHex().c_str()));
300         msgdata.push_back(Pair("parsed", parsed));
301
302         Object raw; // raw checkpoint message data
303         raw.push_back(Pair("data", HexStr(Checkpoints::checkpointMessage.vchMsg).c_str()));
304         raw.push_back(Pair("signature", HexStr(Checkpoints::checkpointMessage.vchSig).c_str()));
305         msgdata.push_back(Pair("raw", raw));
306
307         result.push_back(Pair("data", msgdata));
308     }
309
310     // Check that the block satisfies synchronized checkpoint
311     if (CheckpointsMode == Checkpoints::STRICT)
312         result.push_back(Pair("policy", "strict"));
313
314     if (CheckpointsMode == Checkpoints::ADVISORY)
315         result.push_back(Pair("policy", "advisory"));
316
317     if (CheckpointsMode == Checkpoints::PERMISSIVE)
318         result.push_back(Pair("policy", "permissive"));
319
320     if (mapArgs.count("-checkpointkey"))
321         result.push_back(Pair("checkpointmaster", true));
322
323     return result;
324 }