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