rpcmining.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. // ECOin - Copyright (c) - 2014/2021 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #include "main.h"
  3. #include "db.h"
  4. #include "txdb.h"
  5. #include "init.h"
  6. #include "miner.h"
  7. #include "ecoinrpc.h"
  8. using namespace json_spirit;
  9. using namespace std;
  10. extern unsigned int nStakeTargetSpacing;
  11. extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex);
  12. Value getsubsidy(const Array& params, bool fHelp)
  13. {
  14. if (fHelp || params.size() > 1)
  15. throw runtime_error(
  16. "getsubsidy [nTarget]\n"
  17. "Returns proof-of-work subsidy value for the specified value of target.");
  18. unsigned int nBits = 0;
  19. if (params.size() != 0)
  20. {
  21. //CBigNum bnTarget(uint256(params[0].get_str()));
  22. //nBits = bnTarget.GetCompact();
  23. }
  24. else
  25. {
  26. //nBits = GetNextTargetRequired(pindexBest, false);
  27. }
  28. return 0;
  29. }
  30. Value getmininginfo(const Array& params, bool fHelp)
  31. {
  32. if (fHelp || params.size() != 0)
  33. throw runtime_error(
  34. "getmininginfo\n"
  35. "Returns an object containing mining-related information.");
  36. uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
  37. pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
  38. Object obj, diff, weight;
  39. obj.push_back(Pair("blocks", (int)nBestHeight));
  40. obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
  41. obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
  42. diff.push_back(Pair("proof-of-work", GetDifficulty()));
  43. diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
  44. diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
  45. obj.push_back(Pair("difficulty", diff));
  46. obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nHeight+1, GetLastBlockIndex(pindexBest, false)->GetBlockHash())));
  47. obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
  48. obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
  49. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  50. obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
  51. weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
  52. weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
  53. weight.push_back(Pair("combined", (uint64_t)nWeight));
  54. obj.push_back(Pair("stakeweight", weight));
  55. obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
  56. obj.push_back(Pair("testnet", fTestNet));
  57. return obj;
  58. }
  59. Value getstakinginfo(const Array& params, bool fHelp)
  60. {
  61. if (fHelp || params.size() != 0)
  62. throw runtime_error(
  63. "getstakinginfo\n"
  64. "Returns an object containing staking-related information.");
  65. uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
  66. pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
  67. uint64_t nNetworkWeight = GetPoSKernelPS();
  68. bool staking = nLastCoinStakeSearchInterval && nWeight;
  69. int nExpectedTime = staking ? (nStakeTargetSpacing * nNetworkWeight / nWeight) : -1;
  70. Object obj;
  71. obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
  72. obj.push_back(Pair("staking", staking));
  73. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  74. obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
  75. obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
  76. obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
  77. obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
  78. obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
  79. obj.push_back(Pair("weight", (uint64_t)nWeight));
  80. obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
  81. obj.push_back(Pair("expectedtime", nExpectedTime));
  82. return obj;
  83. }
  84. Value getworkex(const Array& params, bool fHelp)
  85. {
  86. if (fHelp || params.size() > 2)
  87. throw runtime_error(
  88. "getworkex [data, coinbase]\n"
  89. "If [data, coinbase] is not specified, returns extended work data.\n"
  90. );
  91. if (vNodes.empty())
  92. throw JSONRPCError(-9, "Ecoin is not connected!");
  93. if (IsInitialBlockDownload())
  94. throw JSONRPCError(-10, "Ecoin is downloading blocks...");
  95. typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
  96. static mapNewBlock_t mapNewBlock;
  97. static vector<CBlock*> vNewBlock;
  98. static CReserveKey reservekey(pwalletMain);
  99. if (params.size() == 0)
  100. {
  101. // Update block
  102. static unsigned int nTransactionsUpdatedLast;
  103. static CBlockIndex* pindexPrev;
  104. static int64 nStart;
  105. static CBlock* pblock;
  106. if (pindexPrev != pindexBest ||
  107. (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
  108. {
  109. if (pindexPrev != pindexBest)
  110. {
  111. // Deallocate old blocks since they're obsolete now
  112. mapNewBlock.clear();
  113. BOOST_FOREACH(CBlock* pblock, vNewBlock)
  114. delete pblock;
  115. vNewBlock.clear();
  116. }
  117. nTransactionsUpdatedLast = nTransactionsUpdated;
  118. pindexPrev = pindexBest;
  119. nStart = GetTime();
  120. // Create new block
  121. pblock = CreateNewBlock(pwalletMain);
  122. if (!pblock)
  123. throw JSONRPCError(-7, "Out of memory");
  124. vNewBlock.push_back(pblock);
  125. }
  126. // Update nTime
  127. pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  128. pblock->nNonce = 0;
  129. // Update nExtraNonce
  130. static unsigned int nExtraNonce = 0;
  131. IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
  132. // Save
  133. mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
  134. // Prebuild hash buffers
  135. char pmidstate[32];
  136. char pdata[128];
  137. char phash1[64];
  138. FormatHashBuffers(pblock, pmidstate, pdata, phash1);
  139. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  140. CTransaction coinbaseTx = pblock->vtx[0];
  141. std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
  142. Object result;
  143. result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
  144. result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
  145. CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
  146. ssTx << coinbaseTx;
  147. result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
  148. Array merkle_arr;
  149. BOOST_FOREACH(uint256 merkleh, merkle) {
  150. merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
  151. }
  152. result.push_back(Pair("merkle", merkle_arr));
  153. return result;
  154. }
  155. else
  156. {
  157. // Parse parameters
  158. vector<unsigned char> vchData = ParseHex(params[0].get_str());
  159. vector<unsigned char> coinbase;
  160. if(params.size() == 2)
  161. coinbase = ParseHex(params[1].get_str());
  162. if (vchData.size() != 128)
  163. throw JSONRPCError(-8, "Invalid parameter");
  164. CBlock* pdata = (CBlock*)&vchData[0];
  165. // Byte reverse
  166. for (int i = 0; i < 128/4; i++)
  167. ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
  168. // Get saved block
  169. if (!mapNewBlock.count(pdata->hashMerkleRoot))
  170. return false;
  171. CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
  172. pblock->nTime = pdata->nTime;
  173. pblock->nNonce = pdata->nNonce;
  174. if(coinbase.size() == 0)
  175. pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
  176. else
  177. CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
  178. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  179. return CheckWork(pblock, *pwalletMain, reservekey);
  180. }
  181. }
  182. Value getwork(const Array& params, bool fHelp)
  183. {
  184. if (fHelp || params.size() > 1)
  185. throw runtime_error(
  186. "getwork [data]\n"
  187. "If [data] is not specified, returns formatted hash data to work on:\n"
  188. " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
  189. " \"data\" : block data\n"
  190. " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
  191. " \"target\" : little endian hash target\n"
  192. "If [data] is specified, tries to solve the block and returns true if it was successful.");
  193. if (vNodes.empty())
  194. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Ecoin is not connected!");
  195. if (IsInitialBlockDownload())
  196. throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Ecoin is downloading blocks...");
  197. typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
  198. static mapNewBlock_t mapNewBlock; // FIXME: thread safety
  199. static vector<CBlock*> vNewBlock;
  200. static CReserveKey reservekey(pwalletMain);
  201. if (params.size() == 0)
  202. {
  203. // Update block
  204. static unsigned int nTransactionsUpdatedLast;
  205. static CBlockIndex* pindexPrev;
  206. static int64 nStart;
  207. static CBlock* pblock;
  208. if (pindexPrev != pindexBest ||
  209. (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
  210. {
  211. if (pindexPrev != pindexBest)
  212. {
  213. // Deallocate old blocks since they're obsolete now
  214. mapNewBlock.clear();
  215. BOOST_FOREACH(CBlock* pblock, vNewBlock)
  216. delete pblock;
  217. vNewBlock.clear();
  218. }
  219. // Clear pindexPrev so future getworks make a new block, despite any failures from here on
  220. pindexPrev = NULL;
  221. // Store the pindexBest used before CreateNewBlock, to avoid races
  222. nTransactionsUpdatedLast = nTransactionsUpdated;
  223. CBlockIndex* pindexPrevNew = pindexBest;
  224. nStart = GetTime();
  225. // Create new block
  226. pblock = CreateNewBlock(pwalletMain);
  227. if (!pblock)
  228. throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
  229. vNewBlock.push_back(pblock);
  230. // Need to update only after we know CreateNewBlock succeeded
  231. pindexPrev = pindexPrevNew;
  232. }
  233. // Update nTime
  234. pblock->UpdateTime(pindexPrev);
  235. pblock->nNonce = 0;
  236. // Update nExtraNonce
  237. static unsigned int nExtraNonce = 0;
  238. IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
  239. // Save
  240. mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
  241. // Pre-build hash buffers
  242. char pmidstate[32];
  243. char pdata[128];
  244. char phash1[64];
  245. FormatHashBuffers(pblock, pmidstate, pdata, phash1);
  246. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  247. Object result;
  248. result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
  249. result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
  250. result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
  251. result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
  252. return result;
  253. }
  254. else
  255. {
  256. // Parse parameters
  257. vector<unsigned char> vchData = ParseHex(params[0].get_str());
  258. if (vchData.size() != 128)
  259. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
  260. CBlock* pdata = (CBlock*)&vchData[0];
  261. // Byte reverse
  262. for (int i = 0; i < 128/4; i++)
  263. ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
  264. // Get saved block
  265. if (!mapNewBlock.count(pdata->hashMerkleRoot))
  266. return false;
  267. CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
  268. pblock->nTime = pdata->nTime;
  269. pblock->nNonce = pdata->nNonce;
  270. pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
  271. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  272. return CheckWork(pblock, *pwalletMain, reservekey);
  273. }
  274. }
  275. Value getblocktemplate(const Array& params, bool fHelp)
  276. {
  277. if (fHelp || params.size() > 1)
  278. throw runtime_error(
  279. "getblocktemplate [params]\n"
  280. "Returns data needed to construct a block to work on:\n"
  281. " \"version\" : block version\n"
  282. " \"previousblockhash\" : hash of current highest block\n"
  283. " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
  284. " \"coinbaseaux\" : data that should be included in coinbase\n"
  285. " \"proofoftx\" : proof-of-transaction value"
  286. " \"proofoftxwinner\" : proof-of-transaction winner"
  287. " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
  288. " \"target\" : hash target\n"
  289. " \"mintime\" : minimum timestamp appropriate for next block\n"
  290. " \"curtime\" : current timestamp\n"
  291. " \"mutable\" : list of ways the block template may be changed\n"
  292. " \"noncerange\" : range of valid nonces\n"
  293. " \"sigoplimit\" : limit of sigops in blocks\n"
  294. " \"sizelimit\" : limit of block size\n"
  295. " \"bits\" : compressed target of next block\n"
  296. " \"height\" : height of the next block\n"
  297. "See https://en.ecoin.it/wiki/BIP_0022 for full specification.");
  298. std::string strMode = "template";
  299. if (params.size() > 0)
  300. {
  301. const Object& oparam = params[0].get_obj();
  302. const Value& modeval = find_value(oparam, "mode");
  303. if (modeval.type() == str_type)
  304. strMode = modeval.get_str();
  305. else if (modeval.type() == null_type)
  306. {
  307. /* Do nothing */
  308. }
  309. else
  310. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  311. }
  312. if (strMode != "template")
  313. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  314. if (vNodes.empty())
  315. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Ecoin is not connected!");
  316. if (IsInitialBlockDownload())
  317. throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Ecoin is downloading blocks...");
  318. static CReserveKey reservekey(pwalletMain);
  319. // Update block
  320. static unsigned int nTransactionsUpdatedLast;
  321. static CBlockIndex* pindexPrev;
  322. static int64 nStart;
  323. static CBlock* pblock;
  324. if (pindexPrev != pindexBest ||
  325. (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
  326. {
  327. // Clear pindexPrev so future calls make a new block, despite any failures from here on
  328. pindexPrev = NULL;
  329. // Store the pindexBest used before CreateNewBlock, to avoid races
  330. nTransactionsUpdatedLast = nTransactionsUpdated;
  331. CBlockIndex* pindexPrevNew = pindexBest;
  332. nStart = GetTime();
  333. // Create new block
  334. if(pblock)
  335. {
  336. delete pblock;
  337. pblock = NULL;
  338. }
  339. pblock = CreateNewBlock(pwalletMain);
  340. if (!pblock)
  341. throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
  342. // Need to update only after we know CreateNewBlock succeeded
  343. pindexPrev = pindexPrevNew;
  344. }
  345. // Update nTime
  346. pblock->UpdateTime(pindexPrev);
  347. pblock->nNonce = 0;
  348. Array transactions;
  349. map<uint256, int64_t> setTxIndex;
  350. int i = 0;
  351. CTxDB txdb("r");
  352. BOOST_FOREACH (CTransaction& tx, pblock->vtx)
  353. {
  354. uint256 txHash = tx.GetHash();
  355. setTxIndex[txHash] = i++;
  356. if (tx.IsCoinBase() || tx.IsCoinStake())
  357. continue;
  358. Object entry;
  359. CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
  360. ssTx << tx;
  361. entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
  362. entry.push_back(Pair("hash", txHash.GetHex()));
  363. MapPrevTx mapInputs;
  364. map<uint256, CTxIndex> mapUnused;
  365. bool fInvalid = false;
  366. if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
  367. {
  368. entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
  369. Array deps;
  370. BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
  371. {
  372. if (setTxIndex.count(inp.first))
  373. deps.push_back(setTxIndex[inp.first]);
  374. }
  375. entry.push_back(Pair("depends", deps));
  376. int64_t nSigOps = tx.GetLegacySigOpCount();
  377. nSigOps += tx.GetP2SHSigOpCount(mapInputs);
  378. entry.push_back(Pair("sigops", nSigOps));
  379. }
  380. transactions.push_back(entry);
  381. }
  382. Object aux;
  383. aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
  384. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  385. static Array aMutable;
  386. if (aMutable.empty())
  387. {
  388. aMutable.push_back("time");
  389. aMutable.push_back("transactions");
  390. aMutable.push_back("prevblock");
  391. }
  392. Object result;
  393. result.push_back(Pair("version", pblock->nVersion));
  394. result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
  395. result.push_back(Pair("transactions", transactions));
  396. result.push_back(Pair("coinbaseaux", aux));
  397. if (pblock->vtx[0].vout.size() > 1)
  398. {
  399. const CTxOut& txout = pblock->vtx[0].vout[1];
  400. Object script;
  401. ScriptPubKeyToJSON(txout.scriptPubKey, script, true);
  402. result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue + (int64_t)pblock->vtx[0].vout[1].nValue));
  403. result.push_back(Pair("proofoftx", (int64_t)pblock->vtx[0].vout[1].nValue));
  404. result.push_back(Pair("proofoftxwinner", script));
  405. }
  406. else
  407. {
  408. result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
  409. result.push_back(Pair("proofoftx", (int64_t)0));
  410. result.push_back(Pair("proofoftxwinner", 0));
  411. }
  412. result.push_back(Pair("target", hashTarget.GetHex()));
  413. result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
  414. result.push_back(Pair("mutable", aMutable));
  415. result.push_back(Pair("noncerange", "00000000ffffffff"));
  416. result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
  417. result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
  418. result.push_back(Pair("curtime", (int64_t)pblock->nTime));
  419. result.push_back(Pair("bits", HexBits(pblock->nBits)));
  420. result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
  421. return result;
  422. }
  423. Value submitblock(const Array& params, bool fHelp)
  424. {
  425. if (fHelp || params.size() < 1 || params.size() > 2)
  426. throw runtime_error(
  427. "submitblock <hex data> [optional-params-obj]\n"
  428. "[optional-params-obj] parameter is currently ignored.\n"
  429. "Attempts to submit new block to network.\n");
  430. vector<unsigned char> blockData(ParseHex(params[0].get_str()));
  431. CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
  432. CBlock block;
  433. try {
  434. ssBlock >> block;
  435. }
  436. catch (std::exception &e) {
  437. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
  438. }
  439. bool fAccepted = ProcessBlock(NULL, &block);
  440. if (!fAccepted)
  441. return "rejected";
  442. return Value::null;
  443. }