Merge branch 'master' of github.com:novacoin-project/novacoin
[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;
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 || diff_v.type() == int_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 if(inputs_v.type() == int_type)
151         {
152             int nOut = inputs_v.get_int();
153             if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
154             {
155                 stringstream strErrorMsg;
156                 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
157                 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
158             }
159
160             vInputs.push_back(nOut);
161         }
162         else
163         {
164             vInputs = vector<int>(boost::counting_iterator<int>( 0 ), boost::counting_iterator<int>( tx.vout.size() ));
165         }
166
167         CTxDB txdb("r");
168
169         CBlock block;
170         CTxIndex txindex;
171
172         // Load transaction index item
173         if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
174             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
175
176         // Read block header
177         if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
178             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
179
180         uint64_t nStakeModifier = 0;
181         if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
182             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
183
184         std::pair<uint32_t, uint32_t> interval;
185         interval.first = GetTime();
186         // Only count coins meeting min age requirement
187         if (nStakeMinAge + block.nTime > interval.first)
188             interval.first += (nStakeMinAge + block.nTime - interval.first);
189         interval.second = interval.first + nDays * nOneDay;
190
191         Array results;
192         BOOST_FOREACH(const int &nOut, vInputs)
193         {
194             // Check for spent flag
195             // It doesn't make sense to scan spent inputs.
196             if (!txindex.vSpent[nOut].IsNull())
197                 continue;
198
199             // Skip zero value outputs
200             if (tx.vout[nOut].nValue == 0)
201                 continue;
202
203             // Build static part of kernel
204             CDataStream ssKernel(SER_GETHASH, 0);
205             ssKernel << nStakeModifier;
206             ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
207             CDataStream::const_iterator itK = ssKernel.begin();
208
209             std::vector<std::pair<uint256, uint32_t> > result;
210             if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
211             {
212                 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, result)
213                 {
214                     Object item;
215                     item.push_back(Pair("nout", nOut));
216                     item.push_back(Pair("hash", solution.first.GetHex()));
217                     item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
218
219                     results.push_back(item);
220                 }
221             }
222         }
223
224         if (results.size() == 0)
225             return false;
226
227         return results;
228     }
229     else
230         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
231 }
232
233 Value getworkex(const Array& params, bool fHelp)
234 {
235     if (fHelp || params.size() > 2)
236         throw runtime_error(
237             "getworkex [data, coinbase]\n"
238             "If [data, coinbase] is not specified, returns extended work data.\n"
239         );
240
241     if (vNodes.empty())
242         throw JSONRPCError(-9, "NovaCoin is not connected!");
243
244     if (IsInitialBlockDownload())
245         throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
246
247     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
248     static mapNewBlock_t mapNewBlock;
249     static vector<CBlock*> vNewBlock;
250     static CReserveKey reservekey(pwalletMain);
251
252     if (params.size() == 0)
253     {
254         // Update block
255         static unsigned int nTransactionsUpdatedLast;
256         static CBlockIndex* pindexPrev;
257         static int64_t nStart;
258         static CBlock* pblock;
259         if (pindexPrev != pindexBest ||
260             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
261         {
262             if (pindexPrev != pindexBest)
263             {
264                 // Deallocate old blocks since they're obsolete now
265                 mapNewBlock.clear();
266                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
267                     delete pblock;
268                 vNewBlock.clear();
269             }
270             nTransactionsUpdatedLast = nTransactionsUpdated;
271             pindexPrev = pindexBest;
272             nStart = GetTime();
273
274             // Create new block
275             pblock = CreateNewBlock(pwalletMain);
276             if (!pblock)
277                 throw JSONRPCError(-7, "Out of memory");
278             vNewBlock.push_back(pblock);
279         }
280
281         // Update nTime
282         pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
283         pblock->nNonce = 0;
284
285         // Update nExtraNonce
286         static unsigned int nExtraNonce = 0;
287         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
288
289         // Save
290         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
291
292         // Prebuild hash buffers
293         char pmidstate[32];
294         char pdata[128];
295         char phash1[64];
296         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
297
298         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
299
300         CTransaction coinbaseTx = pblock->vtx[0];
301         std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
302
303         Object result;
304         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
305         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
306
307         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
308         ssTx << coinbaseTx;
309         result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
310
311         Array merkle_arr;
312
313         BOOST_FOREACH(uint256 merkleh, merkle) {
314             merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
315         }
316
317         result.push_back(Pair("merkle", merkle_arr));
318
319
320         return result;
321     }
322     else
323     {
324         // Parse parameters
325         vector<unsigned char> vchData = ParseHex(params[0].get_str());
326         vector<unsigned char> coinbase;
327
328         if(params.size() == 2)
329             coinbase = ParseHex(params[1].get_str());
330
331         if (vchData.size() != 128)
332             throw JSONRPCError(-8, "Invalid parameter");
333
334         CBlock* pdata = (CBlock*)&vchData[0];
335
336         // Byte reverse
337         for (int i = 0; i < 128/4; i++)
338             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
339
340         // Get saved block
341         if (!mapNewBlock.count(pdata->hashMerkleRoot))
342             return false;
343         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
344
345         pblock->nTime = pdata->nTime;
346         pblock->nNonce = pdata->nNonce;
347
348         if(coinbase.size() == 0)
349             pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
350         else
351             CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
352
353         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
354
355         return CheckWork(pblock, *pwalletMain, reservekey);
356     }
357 }
358
359
360 Value getwork(const Array& params, bool fHelp)
361 {
362     if (fHelp || params.size() > 1)
363         throw runtime_error(
364             "getwork [data]\n"
365             "If [data] is not specified, returns formatted hash data to work on:\n"
366             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
367             "  \"data\" : block data\n"
368             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
369             "  \"target\" : little endian hash target\n"
370             "If [data] is specified, tries to solve the block and returns true if it was successful.");
371
372     if (vNodes.empty())
373         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
374
375     if (IsInitialBlockDownload())
376         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
377
378     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
379     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
380     static vector<CBlock*> vNewBlock;
381     static CReserveKey reservekey(pwalletMain);
382
383     if (params.size() == 0)
384     {
385         // Update block
386         static unsigned int nTransactionsUpdatedLast;
387         static CBlockIndex* pindexPrev;
388         static int64_t nStart;
389         static CBlock* pblock;
390         if (pindexPrev != pindexBest ||
391             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
392         {
393             if (pindexPrev != pindexBest)
394             {
395                 // Deallocate old blocks since they're obsolete now
396                 mapNewBlock.clear();
397                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
398                     delete pblock;
399                 vNewBlock.clear();
400             }
401
402             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
403             pindexPrev = NULL;
404
405             // Store the pindexBest used before CreateNewBlock, to avoid races
406             nTransactionsUpdatedLast = nTransactionsUpdated;
407             CBlockIndex* pindexPrevNew = pindexBest;
408             nStart = GetTime();
409
410             // Create new block
411             pblock = CreateNewBlock(pwalletMain);
412             if (!pblock)
413                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
414             vNewBlock.push_back(pblock);
415
416             // Need to update only after we know CreateNewBlock succeeded
417             pindexPrev = pindexPrevNew;
418         }
419
420         // Update nTime
421         pblock->UpdateTime(pindexPrev);
422         pblock->nNonce = 0;
423
424         // Update nExtraNonce
425         static unsigned int nExtraNonce = 0;
426         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
427
428         // Save
429         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
430
431         // Pre-build hash buffers
432         char pmidstate[32];
433         char pdata[128];
434         char phash1[64];
435         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
436
437         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
438
439         Object result;
440         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
441         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
442         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
443         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
444         return result;
445     }
446     else
447     {
448         // Parse parameters
449         vector<unsigned char> vchData = ParseHex(params[0].get_str());
450         if (vchData.size() != 128)
451             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
452         CBlock* pdata = (CBlock*)&vchData[0];
453
454         // Byte reverse
455         for (int i = 0; i < 128/4; i++)
456             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
457
458         // Get saved block
459         if (!mapNewBlock.count(pdata->hashMerkleRoot))
460             return false;
461         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
462
463         pblock->nTime = pdata->nTime;
464         pblock->nNonce = pdata->nNonce;
465         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
466         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
467
468         return CheckWork(pblock, *pwalletMain, reservekey);
469     }
470 }
471
472
473 Value getblocktemplate(const Array& params, bool fHelp)
474 {
475     if (fHelp || params.size() > 1)
476         throw runtime_error(
477             "getblocktemplate [params]\n"
478             "Returns data needed to construct a block to work on:\n"
479             "  \"version\" : block version\n"
480             "  \"previousblockhash\" : hash of current highest block\n"
481             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
482             "  \"coinbaseaux\" : data that should be included in coinbase\n"
483             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
484             "  \"target\" : hash target\n"
485             "  \"mintime\" : minimum timestamp appropriate for next block\n"
486             "  \"curtime\" : current timestamp\n"
487             "  \"mutable\" : list of ways the block template may be changed\n"
488             "  \"noncerange\" : range of valid nonces\n"
489             "  \"sigoplimit\" : limit of sigops in blocks\n"
490             "  \"sizelimit\" : limit of block size\n"
491             "  \"bits\" : compressed target of next block\n"
492             "  \"height\" : height of the next block\n"
493             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
494
495     std::string strMode = "template";
496     if (params.size() > 0)
497     {
498         const Object& oparam = params[0].get_obj();
499         const Value& modeval = find_value(oparam, "mode");
500         if (modeval.type() == str_type)
501             strMode = modeval.get_str();
502         else if (modeval.type() == null_type)
503         {
504             /* Do nothing */
505         }
506         else
507             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
508     }
509
510     if (strMode != "template")
511         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
512
513     if (vNodes.empty())
514         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
515
516     if (IsInitialBlockDownload())
517         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
518
519     static CReserveKey reservekey(pwalletMain);
520
521     // Update block
522     static unsigned int nTransactionsUpdatedLast;
523     static CBlockIndex* pindexPrev;
524     static int64_t nStart;
525     static CBlock* pblock;
526     if (pindexPrev != pindexBest ||
527         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
528     {
529         // Clear pindexPrev so future calls make a new block, despite any failures from here on
530         pindexPrev = NULL;
531
532         // Store the pindexBest used before CreateNewBlock, to avoid races
533         nTransactionsUpdatedLast = nTransactionsUpdated;
534         CBlockIndex* pindexPrevNew = pindexBest;
535         nStart = GetTime();
536
537         // Create new block
538         if(pblock)
539         {
540             delete pblock;
541             pblock = NULL;
542         }
543         pblock = CreateNewBlock(pwalletMain);
544         if (!pblock)
545             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
546
547         // Need to update only after we know CreateNewBlock succeeded
548         pindexPrev = pindexPrevNew;
549     }
550
551     // Update nTime
552     pblock->UpdateTime(pindexPrev);
553     pblock->nNonce = 0;
554
555     Array transactions;
556     map<uint256, int64_t> setTxIndex;
557     int i = 0;
558     CTxDB txdb("r");
559     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
560     {
561         uint256 txHash = tx.GetHash();
562         setTxIndex[txHash] = i++;
563
564         if (tx.IsCoinBase() || tx.IsCoinStake())
565             continue;
566
567         Object entry;
568
569         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
570         ssTx << tx;
571         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
572
573         entry.push_back(Pair("hash", txHash.GetHex()));
574
575         MapPrevTx mapInputs;
576         map<uint256, CTxIndex> mapUnused;
577         bool fInvalid = false;
578         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
579         {
580             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
581
582             Array deps;
583             BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
584             {
585                 if (setTxIndex.count(inp.first))
586                     deps.push_back(setTxIndex[inp.first]);
587             }
588             entry.push_back(Pair("depends", deps));
589
590             int64_t nSigOps = tx.GetLegacySigOpCount();
591             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
592             entry.push_back(Pair("sigops", nSigOps));
593         }
594
595         transactions.push_back(entry);
596     }
597
598     Object aux;
599     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
600
601     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
602
603     static Array aMutable;
604     if (aMutable.empty())
605     {
606         aMutable.push_back("time");
607         aMutable.push_back("transactions");
608         aMutable.push_back("prevblock");
609     }
610
611     Object result;
612     result.push_back(Pair("version", pblock->nVersion));
613     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
614     result.push_back(Pair("transactions", transactions));
615     result.push_back(Pair("coinbaseaux", aux));
616     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
617     result.push_back(Pair("target", hashTarget.GetHex()));
618     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
619     result.push_back(Pair("mutable", aMutable));
620     result.push_back(Pair("noncerange", "00000000ffffffff"));
621     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
622     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
623     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
624     result.push_back(Pair("bits", HexBits(pblock->nBits)));
625     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
626
627     return result;
628 }
629
630 Value submitblock(const Array& params, bool fHelp)
631 {
632     if (fHelp || params.size() < 1 || params.size() > 2)
633         throw runtime_error(
634             "submitblock <hex data> [optional-params-obj]\n"
635             "[optional-params-obj] parameter is currently ignored.\n"
636             "Attempts to submit new block to network.\n"
637             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
638
639     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
640     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
641     CBlock block;
642     try {
643         ssBlock >> block;
644     }
645     catch (const std::exception&) {
646         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
647     }
648
649     bool fAccepted = ProcessBlock(NULL, &block);
650     if (!fAccepted)
651         return "rejected";
652
653     return Value::null;
654 }
655