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