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