ca569688bd32c68060c4ed5f82d6b5fb7a1d3dd5
[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-leveldb.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             for (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         for (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                 for (const auto &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<shared_ptr<CBlock>, CScript> > mapNewBlock_t;
247     static mapNewBlock_t mapNewBlock;
248     static vector<std::shared_ptr<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 shared_ptr<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                 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] = make_pair(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         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
296
297         CTransaction coinbaseTx = pblock->vtx[0];
298         std::vector<uint256> 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(BEGIN(hashTarget), END(hashTarget))));
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(BEGIN(merkleh), END(merkleh)));
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         std::shared_ptr<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<shared_ptr<CBlock>, CScript> > mapNewBlock_t;
376     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
377     static vector<shared_ptr<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 shared_ptr<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                 vNewBlock.clear();
395             }
396
397             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
398             pindexPrev = NULL;
399
400             // Store the pindexBest used before CreateNewBlock, to avoid races
401             nTransactionsUpdatedLast = nTransactionsUpdated;
402             CBlockIndex* pindexPrevNew = pindexBest;
403             nStart = GetTime();
404
405             // Create new block
406             pblock = CreateNewBlock(pwalletMain);
407             if (!pblock)
408                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
409             vNewBlock.push_back(pblock);
410
411             // Need to update only after we know CreateNewBlock succeeded
412             pindexPrev = pindexPrevNew;
413         }
414
415         // Update nTime
416         pblock->UpdateTime(pindexPrev);
417         pblock->nNonce = 0;
418
419         // Update nExtraNonce
420         static unsigned int nExtraNonce = 0;
421         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
422
423         // Save
424         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
425
426         // Pre-build hash buffers
427         char pmidstate[32];
428         char pdata[128];
429         char phash1[64];
430         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
431
432         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
433
434         Object result;
435         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
436         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
437         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
438         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
439         return result;
440     }
441     else
442     {
443         // Parse parameters
444         vector<unsigned char> vchData = ParseHex(params[0].get_str());
445         if (vchData.size() != 128)
446             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
447         CBlock* pdata = (CBlock*)&vchData[0];
448
449         // Byte reverse
450         for (int i = 0; i < 128/4; i++)
451             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
452
453         // Get saved block
454         if (!mapNewBlock.count(pdata->hashMerkleRoot))
455             return false;
456         std::shared_ptr<CBlock> pblock = mapNewBlock[pdata->hashMerkleRoot].first;
457
458         pblock->nTime = pdata->nTime;
459         pblock->nNonce = pdata->nNonce;
460         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
461         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
462
463         return CheckWork(pblock, *pwalletMain, reservekey);
464     }
465 }
466
467
468 Value getblocktemplate(const Array& params, bool fHelp)
469 {
470     if (fHelp || params.size() > 1)
471         throw runtime_error(
472             "getblocktemplate [params]\n"
473             "Returns data needed to construct a block to work on:\n"
474             "  \"version\" : block version\n"
475             "  \"previousblockhash\" : hash of current highest block\n"
476             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
477             "  \"coinbaseaux\" : data that should be included in coinbase\n"
478             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
479             "  \"target\" : hash target\n"
480             "  \"mintime\" : minimum timestamp appropriate for next block\n"
481             "  \"curtime\" : current timestamp\n"
482             "  \"mutable\" : list of ways the block template may be changed\n"
483             "  \"noncerange\" : range of valid nonces\n"
484             "  \"sigoplimit\" : limit of sigops in blocks\n"
485             "  \"sizelimit\" : limit of block size\n"
486             "  \"bits\" : compressed target of next block\n"
487             "  \"height\" : height of the next block\n"
488             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
489
490     std::string strMode = "template";
491     if (params.size() > 0)
492     {
493         const Object& oparam = params[0].get_obj();
494         const Value& modeval = find_value(oparam, "mode");
495         if (modeval.type() == str_type)
496             strMode = modeval.get_str();
497         else if (modeval.type() == null_type)
498         {
499             /* Do nothing */
500         }
501         else
502             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
503     }
504
505     if (strMode != "template")
506         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
507
508     if (vNodes.empty())
509         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
510
511     if (IsInitialBlockDownload())
512         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
513
514     static CReserveKey reservekey(pwalletMain);
515
516     // Update block
517     static unsigned int nTransactionsUpdatedLast;
518     static CBlockIndex* pindexPrev;
519     static int64_t nStart;
520     static std::shared_ptr<CBlock> pblock;
521     if (pindexPrev != pindexBest ||
522         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
523     {
524         // Clear pindexPrev so future calls make a new block, despite any failures from here on
525         pindexPrev = NULL;
526
527         // Store the pindexBest used before CreateNewBlock, to avoid races
528         nTransactionsUpdatedLast = nTransactionsUpdated;
529         CBlockIndex* pindexPrevNew = pindexBest;
530         nStart = GetTime();
531
532         // Create new block
533         if(pblock)
534         {
535             pblock.reset();
536         }
537         pblock = CreateNewBlock(pwalletMain);
538         if (!pblock)
539             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
540
541         // Need to update only after we know CreateNewBlock succeeded
542         pindexPrev = pindexPrevNew;
543     }
544
545     // Update nTime
546     pblock->UpdateTime(pindexPrev);
547     pblock->nNonce = 0;
548
549     Array transactions;
550     map<uint256, int64_t> setTxIndex;
551     int i = 0;
552     CTxDB txdb("r");
553     for (CTransaction& tx : pblock->vtx)
554     {
555         uint256 txHash = tx.GetHash();
556         setTxIndex[txHash] = i++;
557
558         if (tx.IsCoinBase() || tx.IsCoinStake())
559             continue;
560
561         Object entry;
562
563         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
564         ssTx << tx;
565         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
566
567         entry.push_back(Pair("hash", txHash.GetHex()));
568
569         MapPrevTx mapInputs;
570         map<uint256, CTxIndex> mapUnused;
571         bool fInvalid = false;
572         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
573         {
574             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
575
576             Array deps;
577             for (MapPrevTx::value_type& inp : mapInputs)
578             {
579                 if (setTxIndex.count(inp.first))
580                     deps.push_back(setTxIndex[inp.first]);
581             }
582             entry.push_back(Pair("depends", deps));
583
584             int64_t nSigOps = tx.GetLegacySigOpCount();
585             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
586             entry.push_back(Pair("sigops", nSigOps));
587         }
588
589         transactions.push_back(entry);
590     }
591
592     Object aux;
593     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
594
595     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
596
597     static Array aMutable;
598     if (aMutable.empty())
599     {
600         aMutable.push_back("time");
601         aMutable.push_back("transactions");
602         aMutable.push_back("prevblock");
603     }
604
605     Object result;
606     result.push_back(Pair("version", pblock->nVersion));
607     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
608     result.push_back(Pair("transactions", transactions));
609     result.push_back(Pair("coinbaseaux", aux));
610     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
611     result.push_back(Pair("target", hashTarget.GetHex()));
612     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
613     result.push_back(Pair("mutable", aMutable));
614     result.push_back(Pair("noncerange", "00000000ffffffff"));
615     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
616     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
617     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
618     result.push_back(Pair("bits", HexBits(pblock->nBits)));
619     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
620
621     return result;
622 }
623
624 Value submitblock(const Array& params, bool fHelp)
625 {
626     if (fHelp || params.size() < 1 || params.size() > 2)
627         throw runtime_error(
628             "submitblock <hex data> [optional-params-obj]\n"
629             "[optional-params-obj] parameter is currently ignored.\n"
630             "Attempts to submit new block to network.\n"
631             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
632
633     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
634     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
635     CBlock block;
636     try {
637         ssBlock >> block;
638     }
639     catch (const std::exception&) {
640         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
641     }
642
643     bool fAccepted = ProcessBlock(NULL, &block);
644     if (!fAccepted)
645         return "rejected";
646
647     return Value::null;
648 }
649