miner.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #include "txdb.h"
  3. #include "miner.h"
  4. #include "kernel.h"
  5. #include <iostream>
  6. using namespace std;
  7. string strMintWarning;
  8. extern unsigned int nMinerSleep;
  9. int static FormatHashBlocks(void* pbuffer, unsigned int len)
  10. {
  11. unsigned char* pdata = (unsigned char*)pbuffer;
  12. unsigned int blocks = 1 + ((len + 8) / 64);
  13. unsigned char* pend = pdata + 64 * blocks;
  14. memset(pdata + len, 0, 64 * blocks - len);
  15. pdata[len] = 0x80;
  16. unsigned int bits = len * 8;
  17. pend[-1] = (bits >> 0) & 0xff;
  18. pend[-2] = (bits >> 8) & 0xff;
  19. pend[-3] = (bits >> 16) & 0xff;
  20. pend[-4] = (bits >> 24) & 0xff;
  21. return blocks;
  22. }
  23. static const unsigned int pSHA256InitState[8] =
  24. {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
  25. void SHA256Transform(void* pstate, void* pinput, const void* pinit)
  26. {
  27. SHA256_CTX ctx;
  28. unsigned char data[64];
  29. SHA256_Init(&ctx);
  30. for (int i = 0; i < 16; i++)
  31. ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
  32. for (int i = 0; i < 8; i++)
  33. ctx.h[i] = ((uint32_t*)pinit)[i];
  34. SHA256_Update(&ctx, data, sizeof(data));
  35. for (int i = 0; i < 8; i++)
  36. ((uint32_t*)pstate)[i] = ctx.h[i];
  37. }
  38. class COrphan
  39. {
  40. public:
  41. CTransaction* ptx;
  42. set<uint256> setDependsOn;
  43. double dPriority;
  44. double dFeePerKb;
  45. COrphan(CTransaction* ptxIn)
  46. {
  47. ptx = ptxIn;
  48. dPriority = dFeePerKb = 0;
  49. }
  50. void print() const
  51. {
  52. printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
  53. ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
  54. BOOST_FOREACH(uint256 hash, setDependsOn)
  55. printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
  56. }
  57. };
  58. uint64 nLastBlockTx = 0;
  59. uint64 nLastBlockSize = 0;
  60. int64 nLastCoinStakeSearchInterval = 0;
  61. typedef boost::tuple<double, double, CTransaction*> TxPriority;
  62. class TxPriorityCompare
  63. {
  64. bool byFee;
  65. public:
  66. TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
  67. bool operator()(const TxPriority& a, const TxPriority& b)
  68. {
  69. if (byFee)
  70. {
  71. if (a.get<1>() == b.get<1>())
  72. return a.get<0>() < b.get<0>();
  73. return a.get<1>() < b.get<1>();
  74. }
  75. else
  76. {
  77. if (a.get<0>() == b.get<0>())
  78. return a.get<1>() < b.get<1>();
  79. return a.get<0>() < b.get<0>();
  80. }
  81. }
  82. };
  83. typedef boost::tuple<bool, CEcoinAddress> ProofOfTx;
  84. ProofOfTx ProofOfTxSearch(unsigned int nBlockHeight, CReserveKey pubKey)
  85. {
  86. bool fMatch = false;
  87. CEcoinAddress addrMiner;
  88. CBlock block;
  89. CBlockIndex* pblockindex = FindBlockByHeight(nBlockHeight);
  90. uint256 hashLastBlock = pblockindex->GetBlockHash();
  91. pblockindex = mapBlockIndex[hashLastBlock];
  92. block.ReadFromDisk(pblockindex, true);
  93. CMerkleTx txGen(block.vtx[0]);
  94. txGen.SetMerkleBranch(&block);
  95. if (!fMatch && nBlockHeight+1 > 57000 && block.vtx.size() <= 20)
  96. {
  97. BOOST_FOREACH (const CTransaction& tx, block.vtx)
  98. {
  99. if (tx.vout.size() <= 3)
  100. {
  101. for (unsigned int i = 0; i < tx.vout.size(); i++)
  102. {
  103. const CTxOut& txout = tx.vout[i];
  104. if (txout.nValue / 1000000.00 > 1)
  105. {
  106. txnouttype type;
  107. vector<CTxDestination> vAddresses;
  108. int nRequired;
  109. ExtractDestinations(txout.scriptPubKey, type, vAddresses, nRequired);
  110. BOOST_FOREACH(const CTxDestination& addr, vAddresses)
  111. {
  112. const char* pszAddress = CEcoinAddress(addr).ToString().c_str();
  113. CScript addrHex = CScript() << vector<unsigned char>((const unsigned char*)pszAddress, (const unsigned char*)pszAddress + strlen(pszAddress));
  114. string strSearch = SearchTermV2(addrHex.ToString().c_str());
  115. if (fAddrMiner(hashLastBlock.GetHex().c_str(), strSearch.c_str()))
  116. {
  117. addrMiner = CEcoinAddress(addr);
  118. fMatch = true;
  119. }
  120. else
  121. {
  122. fMatch = false;
  123. CKeyID keyID = pubKey.GetReservedKey().GetID();
  124. addrMiner.Set(keyID);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. else
  131. {
  132. unsigned int iv = 0;
  133. if (tx.vout.size() > 10)
  134. iv = 10;
  135. else
  136. iv = tx.vout.size();
  137. for (unsigned int i = 0; i < iv; i++)
  138. {
  139. const CTxOut& txout = tx.vout[i];
  140. if (txout.nValue / 1000000.00 > 1)
  141. {
  142. txnouttype type;
  143. vector<CTxDestination> vAddresses;
  144. int nRequired;
  145. ExtractDestinations(txout.scriptPubKey, type, vAddresses, nRequired);
  146. BOOST_FOREACH(const CTxDestination& addr, vAddresses)
  147. {
  148. const char* pszAddress = CEcoinAddress(addr).ToString().c_str();
  149. CScript addrHex = CScript() << vector<unsigned char>((const unsigned char*)pszAddress, (const unsigned char*)pszAddress + strlen(pszAddress));
  150. string strSearch = SearchTerm(addrHex.ToString().c_str());
  151. if (fAddrMiner(hashLastBlock.GetHex().c_str(), strSearch.c_str()))
  152. {
  153. addrMiner = CEcoinAddress(addr);
  154. fMatch = true;
  155. }
  156. else
  157. {
  158. fMatch = false;
  159. CKeyID keyID = pubKey.GetReservedKey().GetID();
  160. addrMiner.Set(keyID);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. else if (!fMatch && nBlockHeight+1 > 57000 && block.vtx.size() > 20)
  169. {
  170. CKeyID keyID = pubKey.GetReservedKey().GetID();
  171. addrMiner.Set(keyID);
  172. return boost::make_tuple(false, addrMiner);
  173. }
  174. else if (!fMatch && nBlockHeight+1 > 22000 && nBlockHeight+1 <= 57000 && block.vtx.size() < 11)
  175. {
  176. BOOST_FOREACH (const CTransaction& tx, block.vtx)
  177. {
  178. if (tx.vout.size() < 11)
  179. {
  180. for (unsigned int i = 0; i < tx.vout.size(); i++)
  181. {
  182. const CTxOut& txout = tx.vout[i];
  183. if (txout.nValue / 1000000.00 > 500)
  184. {
  185. txnouttype type;
  186. vector<CTxDestination> vAddresses;
  187. int nRequired;
  188. ExtractDestinations(txout.scriptPubKey, type, vAddresses, nRequired);
  189. BOOST_FOREACH(const CTxDestination& addr, vAddresses)
  190. {
  191. const char* pszAddress = CEcoinAddress(addr).ToString().c_str();
  192. CScript addrHex = CScript() << vector<unsigned char>((const unsigned char*)pszAddress, (const unsigned char*)pszAddress + strlen(pszAddress));
  193. string strSearch = SearchTerm(addrHex.ToString().c_str());
  194. if (fAddrMiner(hashLastBlock.GetHex().c_str(), strSearch.c_str()))
  195. {
  196. addrMiner = CEcoinAddress(addr);
  197. fMatch = true;
  198. }
  199. else
  200. {
  201. fMatch = false;
  202. CKeyID keyID = pubKey.GetReservedKey().GetID();
  203. addrMiner.Set(keyID);
  204. }
  205. }
  206. }
  207. }
  208. }
  209. else
  210. {
  211. for (unsigned int i = 0; i < 5; i++)
  212. {
  213. const CTxOut& txout = tx.vout[i];
  214. if (txout.nValue / 1000000.00 > 500)
  215. {
  216. txnouttype type;
  217. vector<CTxDestination> vAddresses;
  218. int nRequired;
  219. ExtractDestinations(txout.scriptPubKey, type, vAddresses, nRequired);
  220. BOOST_FOREACH(const CTxDestination& addr, vAddresses)
  221. {
  222. const char* pszAddress = CEcoinAddress(addr).ToString().c_str();
  223. CScript addrHex = CScript() << vector<unsigned char>((const unsigned char*)pszAddress, (const unsigned char*)pszAddress + strlen(pszAddress));
  224. string strSearch = SearchTerm(addrHex.ToString().c_str());
  225. if (fAddrMiner(hashLastBlock.GetHex().c_str(), strSearch.c_str()))
  226. {
  227. addrMiner = CEcoinAddress(addr);
  228. fMatch = true;
  229. }
  230. else
  231. {
  232. fMatch = false;
  233. CKeyID keyID = pubKey.GetReservedKey().GetID();
  234. addrMiner.Set(keyID);
  235. }
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. else if (!fMatch && nBlockHeight+1 > 22000 && nBlockHeight+1 <= 57000 && block.vtx.size() > 10)
  243. {
  244. CKeyID keyID = pubKey.GetReservedKey().GetID();
  245. addrMiner.Set(keyID);
  246. return boost::make_tuple(false, addrMiner);
  247. }
  248. else if (nBlockHeight+1 > 12400 && nBlockHeight+1 < 22001 && block.vtx.size() > 5)
  249. {
  250. CKeyID keyID = pubKey.GetReservedKey().GetID();
  251. addrMiner.Set(keyID);
  252. return boost::make_tuple(false, addrMiner);
  253. }
  254. else if (!fMatch && nBlockHeight+1 > 12400 && nBlockHeight+1 < 22001 && block.vtx.size() < 6)
  255. {
  256. BOOST_FOREACH (const CTransaction& tx, block.vtx)
  257. {
  258. for (unsigned int i = 0; i < tx.vout.size(); i++)
  259. {
  260. const CTxOut& txout = tx.vout[i];
  261. if (txout.nValue / 1000000.00 > 500)
  262. {
  263. txnouttype type;
  264. vector<CTxDestination> vAddresses;
  265. int nRequired;
  266. ExtractDestinations(txout.scriptPubKey, type, vAddresses, nRequired);
  267. BOOST_FOREACH(const CTxDestination& addr, vAddresses)
  268. {
  269. const char* pszAddress = CEcoinAddress(addr).ToString().c_str();
  270. CScript addrHex = CScript() << vector<unsigned char>((const unsigned char*)pszAddress, (const unsigned char*)pszAddress + strlen(pszAddress));
  271. string strSearch = SearchTerm(addrHex.ToString().c_str());
  272. if (fAddrMiner(hashLastBlock.GetHex().c_str(), strSearch.c_str()))
  273. {
  274. addrMiner = CEcoinAddress(addr);
  275. fMatch = true;
  276. }
  277. else
  278. {
  279. fMatch = false;
  280. CKeyID keyID = pubKey.GetReservedKey().GetID();
  281. addrMiner.Set(keyID);
  282. }
  283. }
  284. }
  285. }
  286. }
  287. }
  288. else if (!fMatch && nBlockHeight > 0 && nBlockHeight+1 <= 12400)
  289. {
  290. BOOST_FOREACH (const CTransaction& tx, block.vtx)
  291. {
  292. for (unsigned int i = 0; i < tx.vout.size(); i++)
  293. {
  294. const CTxOut& txout = tx.vout[i];
  295. if (txout.nValue / 1000000.00 > 500)
  296. {
  297. txnouttype type;
  298. vector<CTxDestination> vAddresses;
  299. int nRequired;
  300. ExtractDestinations(txout.scriptPubKey, type, vAddresses, nRequired);
  301. BOOST_FOREACH(const CTxDestination& addr, vAddresses)
  302. {
  303. const char* pszAddress = CEcoinAddress(addr).ToString().c_str();
  304. CScript addrHex = CScript() << vector<unsigned char>((const unsigned char*)pszAddress, (const unsigned char*)pszAddress + strlen(pszAddress));
  305. string strSearch = SearchTerm(addrHex.ToString().c_str());
  306. if (fAddrMiner(hashLastBlock.GetHex().c_str(), strSearch.c_str()))
  307. {
  308. addrMiner = CEcoinAddress(addr);
  309. fMatch = true;
  310. }
  311. else
  312. {
  313. fMatch = false;
  314. CKeyID keyID = pubKey.GetReservedKey().GetID();
  315. addrMiner.Set(keyID);
  316. }
  317. }
  318. }
  319. }
  320. }
  321. }
  322. return boost::make_tuple(fMatch, addrMiner);
  323. }
  324. // CreateNewBlock: create new block (without proof-of-work/proof-of-stake)
  325. CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
  326. {
  327. bool fMatch = false;
  328. CBlockIndex* pindexPrev = pindexBest;
  329. CEcoinAddress addrMiner;
  330. CReserveKey reservekey(pwallet);
  331. // Create new block
  332. auto_ptr<CBlock> pblock(new CBlock());
  333. if (!pblock.get())
  334. return NULL;
  335. unsigned int nBlockHeight = pindexPrev->nHeight;
  336. ProofOfTx hashAddr = ProofOfTxSearch(nBlockHeight, reservekey);
  337. fMatch = hashAddr.get<0>();
  338. // Create coinbase tx
  339. CTransaction txNew;
  340. txNew.vin.resize(1);
  341. txNew.vin[0].prevout.SetNull();
  342. if (!fProofOfStake && !fMatch)
  343. {
  344. txNew.vout.resize(1);
  345. txNew.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
  346. }
  347. else if (!fProofOfStake && fMatch)
  348. {
  349. txNew.vout.resize(2);
  350. txNew.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
  351. addrMiner = hashAddr.get<1>();
  352. CScript txPubKey;
  353. CTxDestination txDestination = addrMiner.Get();
  354. txPubKey.SetDestination(txDestination);
  355. txNew.vout[1].scriptPubKey = txPubKey;
  356. }
  357. else if (fProofOfStake)
  358. {
  359. txNew.vout.resize(1);
  360. txNew.vout[0].SetEmpty();
  361. }
  362. pblock->vtx.push_back(txNew);
  363. unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
  364. nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
  365. unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
  366. nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
  367. unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
  368. nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
  369. int64 nMinTxFee = MIN_TX_FEE;
  370. if (mapArgs.count("-mintxfee"))
  371. ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
  372. pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
  373. int64 nFees = 0;
  374. {
  375. LOCK2(cs_main, mempool.cs);
  376. CBlockIndex* pindexPrev = pindexBest;
  377. CTxDB txdb("r");
  378. // Priority order to process transactions
  379. list<COrphan> vOrphan; // list memory doesn't move
  380. map<uint256, vector<COrphan*> > mapDependers;
  381. // This vector will be sorted into a priority queue:
  382. vector<TxPriority> vecPriority;
  383. vecPriority.reserve(mempool.mapTx.size());
  384. for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
  385. {
  386. CTransaction& tx = (*mi).second;
  387. if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
  388. continue;
  389. COrphan* porphan = NULL;
  390. double dPriority = 0;
  391. int64 nTotalIn = 0;
  392. bool fMissingInputs = false;
  393. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  394. {
  395. // Read prev transaction
  396. CTransaction txPrev;
  397. CTxIndex txindex;
  398. if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
  399. {
  400. // This should never happen; all transactions in the memory
  401. // pool should connect to either transactions in the chain
  402. // or other transactions in the memory pool.
  403. if (!mempool.mapTx.count(txin.prevout.hash))
  404. {
  405. printf("ERROR: mempool transaction missing input\n");
  406. if (fDebug) assert("mempool transaction missing input" == 0);
  407. fMissingInputs = true;
  408. if (porphan)
  409. vOrphan.pop_back();
  410. break;
  411. }
  412. // Has to wait for dependencies
  413. if (!porphan)
  414. {
  415. // Use list for automatic deletion
  416. vOrphan.push_back(COrphan(&tx));
  417. porphan = &vOrphan.back();
  418. }
  419. mapDependers[txin.prevout.hash].push_back(porphan);
  420. porphan->setDependsOn.insert(txin.prevout.hash);
  421. nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
  422. continue;
  423. }
  424. int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
  425. nTotalIn += nValueIn;
  426. int nConf = txindex.GetDepthInMainChain();
  427. dPriority += (double)nValueIn * nConf;
  428. }
  429. if (fMissingInputs) continue;
  430. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  431. dPriority /= nTxSize;
  432. double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
  433. if (porphan)
  434. {
  435. porphan->dPriority = dPriority;
  436. porphan->dFeePerKb = dFeePerKb;
  437. }
  438. else
  439. vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
  440. }
  441. // Collect transactions into block
  442. map<uint256, CTxIndex> mapTestPool;
  443. uint64 nBlockSize = 1000;
  444. uint64 nBlockTx = 0;
  445. int nBlockSigOps = 100;
  446. bool fSortedByFee = (nBlockPrioritySize <= 0);
  447. TxPriorityCompare comparer(fSortedByFee);
  448. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  449. while (!vecPriority.empty())
  450. {
  451. // Take highest priority transaction off the priority queue:
  452. double dPriority = vecPriority.front().get<0>();
  453. double dFeePerKb = vecPriority.front().get<1>();
  454. CTransaction& tx = *(vecPriority.front().get<2>());
  455. std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
  456. vecPriority.pop_back();
  457. // Size limits
  458. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  459. if (nBlockSize + nTxSize >= nBlockMaxSize)
  460. continue;
  461. // Legacy limits on sigOps:
  462. unsigned int nTxSigOps = tx.GetLegacySigOpCount();
  463. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  464. continue;
  465. // Timestamp limit
  466. if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
  467. continue;
  468. // Simplify transaction fee - allow free = false
  469. int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
  470. // Skip free transactions if we're past the minimum block size:
  471. if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
  472. continue;
  473. if (!fSortedByFee &&
  474. ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
  475. {
  476. fSortedByFee = true;
  477. comparer = TxPriorityCompare(fSortedByFee);
  478. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  479. }
  480. map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
  481. MapPrevTx mapInputs;
  482. bool fInvalid;
  483. if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
  484. continue;
  485. int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
  486. if (nTxFees < nMinFee)
  487. continue;
  488. nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
  489. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  490. continue;
  491. if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
  492. continue;
  493. mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
  494. swap(mapTestPool, mapTestPoolTmp);
  495. pblock->vtx.push_back(tx);
  496. nBlockSize += nTxSize;
  497. ++nBlockTx;
  498. nBlockSigOps += nTxSigOps;
  499. nFees += nTxFees;
  500. if (fDebug && GetBoolArg("-printpriority"))
  501. {
  502. printf("priority %.1f feeperkb %.1f txid %s\n",
  503. dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
  504. }
  505. uint256 hash = tx.GetHash();
  506. if (mapDependers.count(hash))
  507. {
  508. BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
  509. {
  510. if (!porphan->setDependsOn.empty())
  511. {
  512. porphan->setDependsOn.erase(hash);
  513. if (porphan->setDependsOn.empty())
  514. {
  515. vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
  516. std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
  517. }
  518. }
  519. }
  520. }
  521. }
  522. nLastBlockTx = nBlockTx;
  523. nLastBlockSize = nBlockSize;
  524. if (fDebug && GetBoolArg("-printpriority"))
  525. printf("CreateNewBlock(): total size %" PRI64u"\n", nBlockSize);
  526. if (!fProofOfStake && nBlockHeight+1 <= 57000)
  527. {
  528. if (!fMatch)
  529. pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, pindexPrev->GetBlockHash());
  530. else
  531. {
  532. pblock->vtx[0].vout[0].nValue = (GetProofOfWorkReward(pindexPrev->nHeight+1, pindexPrev->GetBlockHash())/2);
  533. pblock->vtx[0].vout[1].nValue = (GetProofOfWorkReward(pindexPrev->nHeight+1, pindexPrev->GetBlockHash())/2);
  534. }
  535. }
  536. else if (!fProofOfStake && nBlockHeight+1 > 57000)
  537. {
  538. if (!fMatch)
  539. pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, pindexPrev->GetBlockHash());
  540. else
  541. {
  542. pblock->vtx[0].vout[0].nValue = (GetProofOfWorkReward(pindexPrev->nHeight+1, pindexPrev->GetBlockHash())*0.95);
  543. pblock->vtx[0].vout[1].nValue = (GetProofOfWorkReward(pindexPrev->nHeight+1, pindexPrev->GetBlockHash())*0.05);
  544. }
  545. }
  546. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  547. pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
  548. pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
  549. if (!fProofOfStake)
  550. pblock->UpdateTime(pindexPrev);
  551. pblock->nNonce = 0;
  552. }
  553. return pblock.release();
  554. }
  555. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  556. {
  557. static uint256 hashPrevBlock;
  558. if (hashPrevBlock != pblock->hashPrevBlock)
  559. {
  560. nExtraNonce = 0;
  561. hashPrevBlock = pblock->hashPrevBlock;
  562. }
  563. ++nExtraNonce;
  564. unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
  565. pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
  566. assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
  567. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  568. }
  569. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
  570. {
  571. struct
  572. {
  573. struct unnamed2
  574. {
  575. int nVersion;
  576. uint256 hashPrevBlock;
  577. uint256 hashMerkleRoot;
  578. unsigned int nTime;
  579. unsigned int nBits;
  580. unsigned int nNonce;
  581. }
  582. block;
  583. unsigned char pchPadding0[64];
  584. uint256 hash1;
  585. unsigned char pchPadding1[64];
  586. }
  587. tmp;
  588. memset(&tmp, 0, sizeof(tmp));
  589. tmp.block.nVersion = pblock->nVersion;
  590. tmp.block.hashPrevBlock = pblock->hashPrevBlock;
  591. tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
  592. tmp.block.nTime = pblock->nTime;
  593. tmp.block.nBits = pblock->nBits;
  594. tmp.block.nNonce = pblock->nNonce;
  595. FormatHashBlocks(&tmp.block, sizeof(tmp.block));
  596. FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
  597. // Byte swap all the input buffer
  598. for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
  599. ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
  600. // Precalc the first half of the first hash, which stays constant
  601. SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
  602. memcpy(pdata, &tmp.block, 128);
  603. memcpy(phash1, &tmp.hash1, 64);
  604. }
  605. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
  606. {
  607. uint256 hashBlock = pblock->GetHash();
  608. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  609. if(!pblock->IsProofOfWork())
  610. return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
  611. if (hashBlock > hashTarget)
  612. return error("CheckWork() : proof-of-work not meeting target");
  613. printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
  614. pblock->print();
  615. printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
  616. {
  617. LOCK(cs_main);
  618. if (pblock->hashPrevBlock != hashBestChain)
  619. return error("CheckWork() : generated block is stale");
  620. reservekey.KeepKey();
  621. {
  622. LOCK(wallet.cs_wallet);
  623. wallet.mapRequestCount[hashBlock] = 0;
  624. }
  625. if (!ProcessBlock(NULL, pblock))
  626. return error("CheckWork() : ProcessBlock, block not accepted");
  627. }
  628. return true;
  629. }
  630. bool CheckStake(CBlock* pblock, CWallet& wallet)
  631. {
  632. uint256 proofHash = 0, hashTarget = 0;
  633. uint256 hashBlock = pblock->GetHash();
  634. if(!pblock->IsProofOfStake())
  635. return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
  636. // verify hash target and signature of coinstake tx
  637. if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
  638. return error("CheckStake() : proof-of-stake checking failed");
  639. printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str());
  640. pblock->print();
  641. printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
  642. {
  643. LOCK(cs_main);
  644. if (pblock->hashPrevBlock != hashBestChain)
  645. return error("CheckStake() : generated block is stale");
  646. {
  647. LOCK(wallet.cs_wallet);
  648. wallet.mapRequestCount[hashBlock] = 0;
  649. }
  650. if (!ProcessBlock(NULL, pblock))
  651. return error("CheckStake() : ProcessBlock, block not accepted");
  652. }
  653. return true;
  654. }
  655. void StakeMiner(CWallet *pwallet)
  656. {
  657. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  658. // Make this thread recognisable as the mining thread
  659. RenameThread("ecoin-miner");
  660. // Each thread has its own counter
  661. unsigned int nExtraNonce = 0;
  662. while (true)
  663. {
  664. if (fShutdown)
  665. return;
  666. while (pwallet->IsLocked())
  667. {
  668. //strMintWarning = strMintMessage;
  669. Sleep(1000);
  670. if (fShutdown)
  671. return;
  672. }
  673. while (vNodes.empty() || IsInitialBlockDownload())
  674. {
  675. Sleep(1000);
  676. if (fShutdown)
  677. return;
  678. }
  679. CBlockIndex* pindexPrev = pindexBest;
  680. auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true));
  681. if (!pblock.get())
  682. return;
  683. IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
  684. // Trying to sign a block
  685. if (pblock->SignBlock(*pwallet))
  686. {
  687. strMintWarning = _("Stake generation: new block found!");
  688. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  689. CheckStake(pblock.get(), *pwallet);
  690. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  691. Sleep(500);
  692. }
  693. else
  694. Sleep(nMinerSleep);
  695. continue;
  696. }
  697. }