61ba2589bb6aaf3f75e177eb54a2131306a99753
[novacoin.git] / src / rpcmining.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 "db.h"
8 #include "txdb.h"
9 #include "init.h"
10 #include "miner.h"
11 #include "kernel.h"
12 #include "bitcoinrpc.h"
13
14 #include <boost/format.hpp>
15
16 using namespace json_spirit;
17 using namespace std;
18
19 extern uint256 nPoWBase;
20 extern uint64_t nStakeInputsMapSize;
21
22 Value getsubsidy(const Array& params, bool fHelp)
23 {
24     if (fHelp || params.size() > 1)
25         throw runtime_error(
26             "getsubsidy [nTarget]\n"
27             "Returns proof-of-work subsidy value for the specified value of target.");
28
29     unsigned int nBits = 0;
30
31     if (params.size() != 0)
32     {
33         CBigNum bnTarget(uint256(params[0].get_str()));
34         nBits = bnTarget.GetCompact();
35     }
36     else
37     {
38         nBits = GetNextTargetRequired(pindexBest, false);
39     }
40
41     return (uint64_t)GetProofOfWorkReward(nBits);
42 }
43
44 Value getmininginfo(const Array& params, bool fHelp)
45 {
46     if (fHelp || params.size() != 0)
47         throw runtime_error(
48             "getmininginfo\n"
49             "Returns an object containing mining-related information.");
50
51     Object obj, diff;
52     obj.push_back(Pair("blocks",        (int)nBestHeight));
53     obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
54     obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
55
56     diff.push_back(Pair("proof-of-work",        GetDifficulty()));
57     diff.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
58     diff.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
59     obj.push_back(Pair("difficulty",    diff));
60
61     obj.push_back(Pair("blockvalue",    (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
62     obj.push_back(Pair("netmhashps",    GetPoWMHashPS()));
63     obj.push_back(Pair("netstakeweight",GetPoSKernelPS()));
64     obj.push_back(Pair("errors",        GetWarnings("statusbar")));
65     obj.push_back(Pair("pooledtx",      (uint64_t)mempool.size()));
66
67     obj.push_back(Pair("stakeinputs",   (uint64_t)nStakeInputsMapSize));
68     obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
69
70     obj.push_back(Pair("testnet",       fTestNet));
71     return obj;
72 }
73
74 // scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
75 Value scaninput(const Array& params, bool fHelp)
76 {
77     if (fHelp || params.size() != 1)
78         throw runtime_error(
79             "scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
80             "Scan specified transaction or input for suitable kernel solutions.\n"
81             "    difficulty - upper limit for difficulty, current difficulty by default;\n"
82             "    days - time window, 90 days by default.\n"
83         );
84
85     RPCTypeCheck(params, { obj_type });
86
87     auto scanParams = params[0].get_obj();
88
89     const Value& txid_v = find_value(scanParams, "txid");
90     if (txid_v.type() != str_type)
91         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
92
93     auto txid = txid_v.get_str();
94     if (!IsHex(txid))
95         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
96
97     uint256 hash(txid);
98     int32_t nDays = 90;
99     auto nBits = GetNextTargetRequired(pindexBest, true);
100
101     const Value& diff_v = find_value(scanParams, "difficulty");
102     if (diff_v.type() == real_type || diff_v.type() == int_type)
103     {
104         double dDiff = diff_v.get_real();
105         if (dDiff <= 0)
106             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
107
108         CBigNum bnTarget(nPoWBase);
109         bnTarget *= 1000;
110         bnTarget /= (int) (dDiff * 1000);
111         nBits = bnTarget.GetCompact();
112     }
113
114     const Value& days_v = find_value(scanParams, "days");
115     if (days_v.type() == int_type)
116     {
117         nDays = days_v.get_int();
118         if (nDays <= 0)
119             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
120     }
121
122
123     CTransaction tx;
124     uint256 hashBlock = 0;
125     if (GetTransaction(hash, tx, hashBlock))
126     {
127         if (hashBlock == 0)
128             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
129
130         vector<int> vInputs(0);
131         const Value& inputs_v = find_value(scanParams, "vout");
132         if (inputs_v.type() == array_type)
133         {
134             auto inputs = inputs_v.get_array();
135             for(const Value &v_out: inputs)
136             {
137                 int nOut = v_out.get_int();
138                 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
139                 {
140                     stringstream strErrorMsg;
141                     strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
142                     throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
143                 }
144
145                 vInputs.push_back(nOut);
146             }
147         }
148         else if(inputs_v.type() == int_type)
149         {
150             int nOut = inputs_v.get_int();
151             if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
152             {
153                 stringstream strErrorMsg;
154                 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
155                 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
156             }
157
158             vInputs.push_back(nOut);
159         }
160         else
161         {
162             for (size_t i = 0; i != tx.vout.size(); ++i) vInputs.push_back(i);
163         }
164
165         CTxDB txdb("r");
166
167         CBlock block;
168         CTxIndex txindex;
169
170         // Load transaction index item
171         if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
172             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
173
174         // Read block header
175         if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
176             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
177
178         uint64_t nStakeModifier = 0;
179         if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
180             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
181
182         pair<uint32_t, uint32_t> interval;
183         interval.first = GetTime();
184         // Only count coins meeting min age requirement
185         if (nStakeMinAge + block.nTime > interval.first)
186             interval.first += (nStakeMinAge + block.nTime - interval.first);
187         interval.second = interval.first + nDays * nOneDay;
188
189         Array results;
190         for(const int &nOut :  vInputs)
191         {
192             // Check for spent flag
193             // It doesn't make sense to scan spent inputs.
194             if (!txindex.vSpent[nOut].IsNull())
195                 continue;
196
197             // Skip zero value outputs
198             if (tx.vout[nOut].nValue == 0)
199                 continue;
200
201             // Build static part of kernel
202             CDataStream ssKernel(SER_GETHASH, 0);
203             ssKernel << nStakeModifier;
204             ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
205             auto itK = ssKernel.begin();
206
207             vector<pair<uint256, uint32_t> > result;
208             if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
209             {
210                 for(const auto& solution : result)
211                 {
212                     Object item;
213                     item.push_back(Pair("nout", nOut));
214                     item.push_back(Pair("hash", solution.first.GetHex()));
215                     item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
216
217                     results.push_back(item);
218                 }
219             }
220         }
221
222         if (results.size() == 0)
223             return false;
224
225         return results;
226     }
227     else
228         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
229 }
230
231 Value getworkex(const Array& params, bool fHelp)
232 {
233     if (fHelp || params.size() > 2)
234         throw runtime_error(
235             "getworkex [data, coinbase]\n"
236             "If [data, coinbase] is not specified, returns extended work data.\n"
237         );
238
239     if (vNodes.empty())
240         throw JSONRPCError(-9, "NovaCoin is not connected!");
241
242     if (IsInitialBlockDownload())
243         throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
244
245     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
246     static mapNewBlock_t mapNewBlock;
247     static vector<CBlock*> vNewBlock;
248     static CReserveKey reservekey(pwalletMain);
249
250     if (params.size() == 0)
251     {
252         // Update block
253         static unsigned int nTransactionsUpdatedLast;
254         static CBlockIndex* pindexPrev;
255         static int64_t nStart;
256         static CBlock* pblock;
257         if (pindexPrev != pindexBest ||
258             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
259         {
260             if (pindexPrev != pindexBest)
261             {
262                 // Deallocate old blocks since they're obsolete now
263                 mapNewBlock.clear();
264                 for(CBlock* pblock :  vNewBlock)
265                     delete pblock;
266                 vNewBlock.clear();
267             }
268             nTransactionsUpdatedLast = nTransactionsUpdated;
269             pindexPrev = pindexBest;
270             nStart = GetTime();
271
272             // Create new block
273             pblock = CreateNewBlock(pwalletMain);
274             if (!pblock)
275                 throw JSONRPCError(-7, "Out of memory");
276             vNewBlock.push_back(pblock);
277         }
278
279         // Update nTime
280         pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
281         pblock->nNonce = 0;
282
283         // Update nExtraNonce
284         static unsigned int nExtraNonce = 0;
285         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
286
287         // Save
288         mapNewBlock[pblock->hashMerkleRoot] = { pblock, pblock->vtx[0].vin[0].scriptSig };
289
290         // Prebuild hash buffers
291         char pmidstate[32];
292         char pdata[128];
293         char phash1[64];
294         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
295
296         auto hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
297
298         auto coinbaseTx = pblock->vtx[0];
299         auto merkle = pblock->GetMerkleBranch(0);
300
301         Object result;
302         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
303         result.push_back(Pair("target",   HexStr(hashTarget.begin(), hashTarget.end())));
304
305         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
306         ssTx << coinbaseTx;
307         result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
308
309         Array merkle_arr;
310
311         for(uint256 merkleh :  merkle) {
312             merkle_arr.push_back(HexStr(merkleh.begin(), merkleh.end()));
313         }
314
315         result.push_back(Pair("merkle", merkle_arr));
316
317
318         return result;
319     }
320     else
321     {
322         // Parse parameters
323         vector<unsigned char> vchData = ParseHex(params[0].get_str());
324         vector<unsigned char> coinbase;
325
326         if(params.size() == 2)
327             coinbase = ParseHex(params[1].get_str());
328
329         if (vchData.size() != 128)
330             throw JSONRPCError(-8, "Invalid parameter");
331
332         CBlock* pdata = (CBlock*)&vchData[0];
333
334         // Byte reverse
335         for (int i = 0; i < 128/4; i++)
336             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
337
338         // Get saved block
339         if (!mapNewBlock.count(pdata->hashMerkleRoot))
340             return false;
341         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
342
343         pblock->nTime = pdata->nTime;
344         pblock->nNonce = pdata->nNonce;
345
346         if(coinbase.size() == 0)
347             pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
348         else
349             CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
350
351         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
352
353         return CheckWork(pblock, *pwalletMain, reservekey);
354     }
355 }
356
357
358 Value getwork(const Array& params, bool fHelp)
359 {
360     if (fHelp || params.size() > 1)
361         throw runtime_error(
362             "getwork [data]\n"
363             "If [data] is not specified, returns formatted hash data to work on:\n"
364             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
365             "  \"data\" : block data\n"
366             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
367             "  \"target\" : little endian hash target\n"
368             "If [data] is specified, tries to solve the block and returns true if it was successful.");
369
370     if (vNodes.empty())
371         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
372
373     if (IsInitialBlockDownload())
374         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
375
376     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
377     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
378     static vector<CBlock*> vNewBlock;
379     static CReserveKey reservekey(pwalletMain);
380
381     if (params.size() == 0)
382     {
383         // Update block
384         static unsigned int nTransactionsUpdatedLast;
385         static CBlockIndex* pindexPrev;
386         static int64_t nStart;
387         static CBlock* pblock;
388         if (pindexPrev != pindexBest ||
389             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
390         {
391             if (pindexPrev != pindexBest)
392             {
393                 // Deallocate old blocks since they're obsolete now
394                 mapNewBlock.clear();
395                 for(CBlock* pblock : vNewBlock)
396                     delete pblock;
397                 vNewBlock.clear();
398             }
399
400             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
401             pindexPrev = NULL;
402
403             // Store the pindexBest used before CreateNewBlock, to avoid races
404             nTransactionsUpdatedLast = nTransactionsUpdated;
405             CBlockIndex* pindexPrevNew = pindexBest;
406             nStart = GetTime();
407
408             // Create new block
409             pblock = CreateNewBlock(pwalletMain);
410             if (!pblock)
411                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
412             vNewBlock.push_back(pblock);
413
414             // Need to update only after we know CreateNewBlock succeeded
415             pindexPrev = pindexPrevNew;
416         }
417
418         // Update nTime
419         pblock->UpdateTime(pindexPrev);
420         pblock->nNonce = 0;
421
422         // Update nExtraNonce
423         static unsigned int nExtraNonce = 0;
424         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
425
426         // Save
427         mapNewBlock[pblock->hashMerkleRoot] = { pblock, pblock->vtx[0].vin[0].scriptSig };
428
429         // Pre-build hash buffers
430         char pmidstate[32];
431         char pdata[128];
432         char phash1[64];
433         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
434
435         auto hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
436
437         Object result;
438         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
439         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
440         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
441         result.push_back(Pair("target",   HexStr(hashTarget.begin(), hashTarget.end())));
442         return result;
443     }
444     else
445     {
446         // Parse parameters
447         vector<unsigned char> vchData = ParseHex(params[0].get_str());
448         if (vchData.size() != 128)
449             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
450         CBlock* pdata = (CBlock*)&vchData[0];
451
452         // Byte reverse
453         for (int i = 0; i < 128/4; i++)
454             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
455
456         // Get saved block
457         if (!mapNewBlock.count(pdata->hashMerkleRoot))
458             return false;
459         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
460
461         pblock->nTime = pdata->nTime;
462         pblock->nNonce = pdata->nNonce;
463         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
464         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
465
466         return CheckWork(pblock, *pwalletMain, reservekey);
467     }
468 }
469
470
471 Value getblocktemplate(const Array& params, bool fHelp)
472 {
473     if (fHelp || params.size() > 1)
474         throw runtime_error(
475             "getblocktemplate [params]\n"
476             "Returns data needed to construct a block to work on:\n"
477             "  \"version\" : block version\n"
478             "  \"previousblockhash\" : hash of current highest block\n"
479             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
480             "  \"coinbaseaux\" : data that should be included in coinbase\n"
481             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
482             "  \"target\" : hash target\n"
483             "  \"mintime\" : minimum timestamp appropriate for next block\n"
484             "  \"curtime\" : current timestamp\n"
485             "  \"mutable\" : list of ways the block template may be changed\n"
486             "  \"noncerange\" : range of valid nonces\n"
487             "  \"sigoplimit\" : limit of sigops in blocks\n"
488             "  \"sizelimit\" : limit of block size\n"
489             "  \"bits\" : compressed target of next block\n"
490             "  \"height\" : height of the next block\n"
491             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
492
493     string strMode = "template";
494     if (params.size() > 0)
495     {
496         const Object& oparam = params[0].get_obj();
497         const Value& modeval = find_value(oparam, "mode");
498         if (modeval.type() == str_type)
499             strMode = modeval.get_str();
500         else if (modeval.type() == null_type)
501         {
502             /* Do nothing */
503         }
504         else
505             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
506     }
507
508     if (strMode != "template")
509         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
510
511     if (vNodes.empty())
512         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
513
514     if (IsInitialBlockDownload())
515         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
516
517     static CReserveKey reservekey(pwalletMain);
518
519     // Update block
520     static unsigned int nTransactionsUpdatedLast;
521     static CBlockIndex* pindexPrev;
522     static int64_t nStart;
523     static CBlock* pblock;
524     if (pindexPrev != pindexBest ||
525         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
526     {
527         // Clear pindexPrev so future calls make a new block, despite any failures from here on
528         pindexPrev = NULL;
529
530         // Store the pindexBest used before CreateNewBlock, to avoid races
531         nTransactionsUpdatedLast = nTransactionsUpdated;
532         CBlockIndex* pindexPrevNew = pindexBest;
533         nStart = GetTime();
534
535         // Create new block
536         if(pblock)
537         {
538             delete pblock;
539             pblock = NULL;
540         }
541         pblock = CreateNewBlock(pwalletMain);
542         if (!pblock)
543             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
544
545         // Need to update only after we know CreateNewBlock succeeded
546         pindexPrev = pindexPrevNew;
547     }
548
549     // Update nTime
550     pblock->UpdateTime(pindexPrev);
551     pblock->nNonce = 0;
552
553     Array transactions;
554     map<uint256, int64_t> setTxIndex;
555     int i = 0;
556     CTxDB txdb("r");
557     for(auto& tx : pblock->vtx)
558     {
559         auto txHash = tx.GetHash();
560         setTxIndex[txHash] = i++;
561
562         if (tx.IsCoinBase() || tx.IsCoinStake())
563             continue;
564
565         Object entry;
566
567         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
568         ssTx << tx;
569         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
570
571         entry.push_back(Pair("hash", txHash.GetHex()));
572
573         MapPrevTx mapInputs;
574         map<uint256, CTxIndex> mapUnused;
575         bool fInvalid = false;
576         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
577         {
578             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
579
580             Array deps;
581             for(auto& inp : mapInputs)
582             {
583                 if (setTxIndex.count(inp.first))
584                     deps.push_back(setTxIndex[inp.first]);
585             }
586             entry.push_back(Pair("depends", deps));
587
588             int64_t nSigOps = tx.GetLegacySigOpCount();
589             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
590             entry.push_back(Pair("sigops", nSigOps));
591         }
592
593         transactions.push_back(entry);
594     }
595
596     Object aux;
597     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
598
599     auto hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
600
601     static Array aMutable;
602     if (aMutable.empty())
603     {
604         aMutable.push_back("time");
605         aMutable.push_back("transactions");
606         aMutable.push_back("prevblock");
607     }
608
609     Object result;
610     result.push_back(Pair("version", pblock->nVersion));
611     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
612     result.push_back(Pair("transactions", transactions));
613     result.push_back(Pair("coinbaseaux", aux));
614     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
615     result.push_back(Pair("target", hashTarget.GetHex()));
616     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
617     result.push_back(Pair("mutable", aMutable));
618     result.push_back(Pair("noncerange", "00000000ffffffff"));
619     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
620     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
621     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
622     result.push_back(Pair("bits", HexBits(pblock->nBits)));
623     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
624
625     return result;
626 }
627
628 Value submitblock(const Array& params, bool fHelp)
629 {
630     if (fHelp || params.size() < 1 || params.size() > 2)
631         throw runtime_error(
632             "submitblock <hex data> [optional-params-obj]\n"
633             "[optional-params-obj] parameter is currently ignored.\n"
634             "Attempts to submit new block to network.\n"
635             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
636
637     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
638     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
639     CBlock block;
640     try {
641         ssBlock >> block;
642     }
643     catch (const exception&) {
644         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
645     }
646
647     bool fAccepted = ProcessBlock(NULL, &block);
648     if (!fAccepted)
649         return "rejected";
650
651     return Value::null;
652 }
653