]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Auto merge of #1311 - ebfull:cleanup-pp, r=ebfull
[VerusCoin.git] / src / miner.cpp
CommitLineData
d247a5d1 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
78253fcb 3// Distributed under the MIT software license, see the accompanying
d247a5d1
JG
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
d247a5d1 6#include "miner.h"
51ed9ec9 7
eda37330 8#include "amount.h"
bebe7282 9#include "chainparams.h"
691161d4 10#include "consensus/consensus.h"
da29ecbc 11#include "consensus/validation.h"
85aab2a0 12#include "hash.h"
d247a5d1 13#include "main.h"
51ed9ec9 14#include "net.h"
df852d2b 15#include "pow.h"
bebe7282 16#include "primitives/transaction.h"
8e165d57 17#include "random.h"
22c4272b 18#include "timedata.h"
ad49c256
WL
19#include "util.h"
20#include "utilmoneystr.h"
df840de5 21#ifdef ENABLE_WALLET
fdda3c50 22#include "crypto/equihash.h"
50c72f23 23#include "wallet/wallet.h"
2dbabb11 24#include <functional>
df840de5 25#endif
09eb201b 26
fdda3c50
JG
27#include "sodium.h"
28
ad49c256 29#include <boost/thread.hpp>
a3c26c2e 30#include <boost/tuple/tuple.hpp>
5a360a5c 31#include <mutex>
ad49c256 32
09eb201b 33using namespace std;
7b4737c8 34
d247a5d1
JG
35//////////////////////////////////////////////////////////////////////////////
36//
37// BitcoinMiner
38//
39
c6cb21d1
GA
40//
41// Unconfirmed transactions in the memory pool often depend on other
42// transactions in the memory pool. When we select transactions from the
43// pool, we select by highest priority or fee rate, so we might consider
44// transactions that depend on transactions that aren't yet in the block.
45// The COrphan class keeps track of these 'temporary orphans' while
46// CreateBlock is figuring out which transactions to include.
47//
d247a5d1
JG
48class COrphan
49{
50public:
4d707d51 51 const CTransaction* ptx;
d247a5d1 52 set<uint256> setDependsOn;
c6cb21d1 53 CFeeRate feeRate;
02bec4b2 54 double dPriority;
d247a5d1 55
c6cb21d1 56 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 57 {
d247a5d1 58 }
d247a5d1
JG
59};
60
51ed9ec9
BD
61uint64_t nLastBlockTx = 0;
62uint64_t nLastBlockSize = 0;
d247a5d1 63
c6cb21d1
GA
64// We want to sort transactions by priority and fee rate, so:
65typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
66class TxPriorityCompare
67{
68 bool byFee;
0655fac0 69
d247a5d1
JG
70public:
71 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
0655fac0 72
d247a5d1
JG
73 bool operator()(const TxPriority& a, const TxPriority& b)
74 {
75 if (byFee)
76 {
77 if (a.get<1>() == b.get<1>())
78 return a.get<0>() < b.get<0>();
79 return a.get<1>() < b.get<1>();
80 }
81 else
82 {
83 if (a.get<0>() == b.get<0>())
84 return a.get<1>() < b.get<1>();
85 return a.get<0>() < b.get<0>();
86 }
87 }
88};
89
bebe7282 90void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 91{
92 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
93
94 // Updating time can change work required on testnet:
bebe7282
JT
95 if (consensusParams.fPowAllowMinDifficultyBlocks)
96 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
22c4272b 97}
98
48265f3c 99CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
d247a5d1 100{
935bd0a4 101 const CChainParams& chainparams = Params();
d247a5d1
JG
102 // Create new block
103 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
104 if(!pblocktemplate.get())
105 return NULL;
106 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
107
dbca89b7
GA
108 // -regtest only: allow overriding block.nVersion with
109 // -blockversion=N to test forking scenarios
110 if (Params().MineBlocksOnDemand())
111 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
112
4949004d
PW
113 // Add dummy coinbase tx as first transaction
114 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
115 pblocktemplate->vTxFees.push_back(-1); // updated at end
116 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
117
118 // Largest block you're willing to create:
ad898b40 119 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
120 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
121 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
122
123 // How much of the block should be dedicated to high-priority transactions,
124 // included regardless of the fees they pay
125 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
126 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
127
128 // Minimum block size you want to create; block will be filled with free transactions
129 // until there are no more or the block reaches this size:
037b4f14 130 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1
JG
131 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
132
133 // Collect memory pool transactions into the block
a372168e 134 CAmount nFees = 0;
0655fac0 135
d247a5d1
JG
136 {
137 LOCK2(cs_main, mempool.cs);
48265f3c 138 CBlockIndex* pindexPrev = chainActive.Tip();
b867e409 139 const int nHeight = pindexPrev->nHeight + 1;
75a4d512 140 pblock->nTime = GetAdjustedTime();
a1d3c6fb 141 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
7c70438d 142 CCoinsViewCache view(pcoinsTip);
d247a5d1
JG
143
144 // Priority order to process transactions
145 list<COrphan> vOrphan; // list memory doesn't move
146 map<uint256, vector<COrphan*> > mapDependers;
147 bool fPrintPriority = GetBoolArg("-printpriority", false);
148
149 // This vector will be sorted into a priority queue:
150 vector<TxPriority> vecPriority;
151 vecPriority.reserve(mempool.mapTx.size());
4d707d51
GA
152 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
153 mi != mempool.mapTx.end(); ++mi)
d247a5d1 154 {
4d707d51 155 const CTransaction& tx = mi->second.GetTx();
a1d3c6fb
MF
156
157 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
158 ? nMedianTimePast
159 : pblock->GetBlockTime();
160
161 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
d247a5d1
JG
162 continue;
163
164 COrphan* porphan = NULL;
165 double dPriority = 0;
a372168e 166 CAmount nTotalIn = 0;
d247a5d1
JG
167 bool fMissingInputs = false;
168 BOOST_FOREACH(const CTxIn& txin, tx.vin)
169 {
170 // Read prev transaction
171 if (!view.HaveCoins(txin.prevout.hash))
172 {
173 // This should never happen; all transactions in the memory
174 // pool should connect to either transactions in the chain
175 // or other transactions in the memory pool.
176 if (!mempool.mapTx.count(txin.prevout.hash))
177 {
881a85a2 178 LogPrintf("ERROR: mempool transaction missing input\n");
d247a5d1
JG
179 if (fDebug) assert("mempool transaction missing input" == 0);
180 fMissingInputs = true;
181 if (porphan)
182 vOrphan.pop_back();
183 break;
184 }
185
186 // Has to wait for dependencies
187 if (!porphan)
188 {
189 // Use list for automatic deletion
190 vOrphan.push_back(COrphan(&tx));
191 porphan = &vOrphan.back();
192 }
193 mapDependers[txin.prevout.hash].push_back(porphan);
194 porphan->setDependsOn.insert(txin.prevout.hash);
4d707d51 195 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
d247a5d1
JG
196 continue;
197 }
629d75fa
PW
198 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
199 assert(coins);
d247a5d1 200
a372168e 201 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
d247a5d1
JG
202 nTotalIn += nValueIn;
203
b867e409 204 int nConf = nHeight - coins->nHeight;
d247a5d1
JG
205
206 dPriority += (double)nValueIn * nConf;
207 }
208 if (fMissingInputs) continue;
209
d6eb2599 210 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 211 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 212 dPriority = tx.ComputePriority(dPriority, nTxSize);
d247a5d1 213
10d2c57c 214 uint256 hash = tx.GetTxid();
2a72d459
LD
215 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
216
c6cb21d1 217 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
d247a5d1
JG
218
219 if (porphan)
220 {
221 porphan->dPriority = dPriority;
c6cb21d1 222 porphan->feeRate = feeRate;
d247a5d1
JG
223 }
224 else
c6cb21d1 225 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
d247a5d1
JG
226 }
227
228 // Collect transactions into block
51ed9ec9
BD
229 uint64_t nBlockSize = 1000;
230 uint64_t nBlockTx = 0;
d247a5d1
JG
231 int nBlockSigOps = 100;
232 bool fSortedByFee = (nBlockPrioritySize <= 0);
233
234 TxPriorityCompare comparer(fSortedByFee);
235 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
236
237 while (!vecPriority.empty())
238 {
239 // Take highest priority transaction off the priority queue:
240 double dPriority = vecPriority.front().get<0>();
c6cb21d1 241 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 242 const CTransaction& tx = *(vecPriority.front().get<2>());
d247a5d1
JG
243
244 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
245 vecPriority.pop_back();
246
247 // Size limits
248 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
249 if (nBlockSize + nTxSize >= nBlockMaxSize)
250 continue;
251
252 // Legacy limits on sigOps:
253 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
254 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
255 continue;
256
257 // Skip free transactions if we're past the minimum block size:
10d2c57c 258 const uint256& hash = tx.GetTxid();
2a72d459 259 double dPriorityDelta = 0;
a372168e 260 CAmount nFeeDelta = 0;
2a72d459 261 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 262 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
d247a5d1
JG
263 continue;
264
2a72d459 265 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
266 // transactions:
267 if (!fSortedByFee &&
268 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
269 {
270 fSortedByFee = true;
271 comparer = TxPriorityCompare(fSortedByFee);
272 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
273 }
274
275 if (!view.HaveInputs(tx))
276 continue;
277
a372168e 278 CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
d247a5d1
JG
279
280 nTxSigOps += GetP2SHSigOpCount(tx, view);
281 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
282 continue;
283
68f7d1d7
PT
284 // Note that flags: we don't want to set mempool/IsStandard()
285 // policy here, but we still have to ensure that the block we
286 // create only contains transactions that are valid in new blocks.
d247a5d1 287 CValidationState state;
c0dde76d 288 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
d247a5d1
JG
289 continue;
290
d7621ccf 291 UpdateCoins(tx, state, view, nHeight);
d247a5d1
JG
292
293 // Added
294 pblock->vtx.push_back(tx);
295 pblocktemplate->vTxFees.push_back(nTxFees);
296 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
297 nBlockSize += nTxSize;
298 ++nBlockTx;
299 nBlockSigOps += nTxSigOps;
300 nFees += nTxFees;
301
302 if (fPrintPriority)
303 {
c6cb21d1 304 LogPrintf("priority %.1f fee %s txid %s\n",
10d2c57c 305 dPriority, feeRate.ToString(), tx.GetTxid().ToString());
d247a5d1
JG
306 }
307
308 // Add transactions that depend on this one to the priority queue
309 if (mapDependers.count(hash))
310 {
311 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
312 {
313 if (!porphan->setDependsOn.empty())
314 {
315 porphan->setDependsOn.erase(hash);
316 if (porphan->setDependsOn.empty())
317 {
c6cb21d1 318 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
319 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
320 }
321 }
322 }
323 }
324 }
325
326 nLastBlockTx = nBlockTx;
327 nLastBlockSize = nBlockSize;
f48742c2 328 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
d247a5d1 329
f3ffa3d2
SB
330 // Create coinbase tx
331 CMutableTransaction txNew;
332 txNew.vin.resize(1);
333 txNew.vin[0].prevout.SetNull();
334 txNew.vout.resize(1);
335 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
336 txNew.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
337
338 if ((nHeight > 0) && (nHeight < chainparams.GetConsensus().nSubsidyHalvingInterval)) {
339 // Founders reward is 20% of the block subsidy
340 auto vFoundersReward = txNew.vout[0].nValue / 5;
341 // Take some reward away from us
342 txNew.vout[0].nValue -= vFoundersReward;
343
344 auto rewardScript = ParseHex(FOUNDERS_REWARD_SCRIPT);
345
346 // And give it to the founders
347 txNew.vout.push_back(CTxOut(vFoundersReward, CScript(rewardScript.begin(),
348 rewardScript.end())));
349 }
350
351 // Add fees
352 txNew.vout[0].nValue += nFees;
b867e409 353 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
f3ffa3d2 354
4949004d 355 pblock->vtx[0] = txNew;
d247a5d1
JG
356 pblocktemplate->vTxFees[0] = -nFees;
357
8e165d57
JG
358 // Randomise nonce
359 arith_uint256 nonce = UintToArith256(GetRandHash());
360 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
361 nonce <<= 32;
362 nonce >>= 16;
363 pblock->nNonce = ArithToUint256(nonce);
364
d247a5d1
JG
365 // Fill in header
366 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 367 pblock->hashReserved = uint256();
bebe7282 368 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
d698ef69 369 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
fdda3c50 370 pblock->nSolution.clear();
d247a5d1
JG
371 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
372
d247a5d1 373 CValidationState state;
df08a626 374 if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
5262fde0 375 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
d247a5d1
JG
376 }
377
378 return pblocktemplate.release();
379}
380
d247a5d1
JG
381void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
382{
383 // Update nExtraNonce
384 static uint256 hashPrevBlock;
385 if (hashPrevBlock != pblock->hashPrevBlock)
386 {
387 nExtraNonce = 0;
388 hashPrevBlock = pblock->hashPrevBlock;
389 }
390 ++nExtraNonce;
391 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
392 CMutableTransaction txCoinbase(pblock->vtx[0]);
393 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
394 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
d247a5d1 395
4949004d 396 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
397 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
398}
399
4a85e067 400#ifdef ENABLE_WALLET
acfa0333
WL
401//////////////////////////////////////////////////////////////////////////////
402//
403// Internal miner
404//
acfa0333 405
48265f3c 406CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333
WL
407{
408 CPubKey pubkey;
409 if (!reservekey.GetReservedKey(pubkey))
410 return NULL;
411
e9ca4280 412 CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
48265f3c 413 return CreateNewBlock(scriptPubKey);
acfa0333
WL
414}
415
269d8ba0 416static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
d247a5d1 417{
81212588 418 LogPrintf("%s\n", pblock->ToString());
7d9d134b 419 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
d247a5d1
JG
420
421 // Found a solution
422 {
423 LOCK(cs_main);
4c6d41b8 424 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
fdda3c50 425 return error("ZcashMiner: generated block is stale");
18e72167 426 }
d247a5d1 427
18e72167
PW
428 // Remove key from key pool
429 reservekey.KeepKey();
d247a5d1 430
18e72167
PW
431 // Track how many getdata requests this block gets
432 {
433 LOCK(wallet.cs_wallet);
434 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1
JG
435 }
436
18e72167
PW
437 // Process this block the same as if we had received it from another node
438 CValidationState state;
304892fc 439 if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
fdda3c50 440 return error("ZcashMiner: ProcessNewBlock, block not accepted");
18e72167 441
d247a5d1
JG
442 return true;
443}
444
445void static BitcoinMiner(CWallet *pwallet)
446{
fdda3c50 447 LogPrintf("ZcashMiner started\n");
d247a5d1 448 SetThreadPriority(THREAD_PRIORITY_LOWEST);
fdda3c50 449 RenameThread("zcash-miner");
bebe7282 450 const CChainParams& chainparams = Params();
d247a5d1
JG
451
452 // Each thread has its own key and counter
453 CReserveKey reservekey(pwallet);
454 unsigned int nExtraNonce = 0;
455
e9574728
JG
456 unsigned int n = chainparams.EquihashN();
457 unsigned int k = chainparams.EquihashK();
fdda3c50 458
5a360a5c
JG
459 std::mutex m_cs;
460 bool cancelSolver = false;
461 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
462 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
463 std::lock_guard<std::mutex> lock{m_cs};
464 cancelSolver = true;
465 }
466 );
467
0655fac0
PK
468 try {
469 while (true) {
bebe7282 470 if (chainparams.MiningRequiresPeers()) {
0655fac0
PK
471 // Busy-wait for the network to come online so we don't waste time mining
472 // on an obsolete chain. In regtest mode we expect to fly solo.
bba7c249
GM
473 do {
474 bool fvNodesEmpty;
475 {
476 LOCK(cs_vNodes);
477 fvNodesEmpty = vNodes.empty();
478 }
479 if (!fvNodesEmpty && !IsInitialBlockDownload())
480 break;
0655fac0 481 MilliSleep(1000);
bba7c249 482 } while (true);
0655fac0 483 }
d247a5d1 484
0655fac0
PK
485 //
486 // Create new block
487 //
488 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 489 CBlockIndex* pindexPrev = chainActive.Tip();
0655fac0 490
48265f3c 491 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
0655fac0 492 if (!pblocktemplate.get())
6c37f7fd 493 {
fdda3c50 494 LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
0655fac0 495 return;
6c37f7fd 496 }
0655fac0
PK
497 CBlock *pblock = &pblocktemplate->block;
498 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
499
fdda3c50 500 LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
0655fac0
PK
501 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
502
503 //
504 // Search
505 //
506 int64_t nStart = GetTime();
48265f3c 507 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
fdda3c50 508
7213c0b1
JG
509 while (true) {
510 // Hash state
511 crypto_generichash_blake2b_state state;
e9574728 512 EhInitialiseState(n, k, state);
fdda3c50 513
7213c0b1
JG
514 // I = the block header minus nonce and solution.
515 CEquihashInput I{*pblock};
516 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
517 ss << I;
fdda3c50 518
7213c0b1
JG
519 // H(I||...
520 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
fdda3c50 521
8e165d57
JG
522 // H(I||V||...
523 crypto_generichash_blake2b_state curr_state;
524 curr_state = state;
525 crypto_generichash_blake2b_update(&curr_state,
526 pblock->nNonce.begin(),
527 pblock->nNonce.size());
528
529 // (x_1, x_2, ...) = A(I, V, n, k)
530 LogPrint("pow", "Running Equihash solver with nNonce = %s\n",
531 pblock->nNonce.ToString());
8e165d57 532
5be6abbf 533 std::function<bool(std::vector<unsigned char>)> validBlock =
51eb5273 534 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
5be6abbf 535 (std::vector<unsigned char> soln) {
51eb5273
JG
536 // Write the solution to the hash and compute the result.
537 LogPrint("pow", "- Checking solution against target\n");
8e165d57
JG
538 pblock->nSolution = soln;
539
540 if (UintToArith256(pblock->GetHash()) > hashTarget) {
51eb5273 541 return false;
8e165d57 542 }
48265f3c 543
8e165d57
JG
544 // Found a solution
545 SetThreadPriority(THREAD_PRIORITY_NORMAL);
546 LogPrintf("ZcashMiner:\n");
547 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
5a360a5c
JG
548 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
549 // Ignore chain updates caused by us
550 std::lock_guard<std::mutex> lock{m_cs};
551 cancelSolver = false;
552 }
8e165d57 553 SetThreadPriority(THREAD_PRIORITY_LOWEST);
48265f3c 554
8e165d57
JG
555 // In regression test mode, stop mining after a block is found.
556 if (chainparams.MineBlocksOnDemand())
557 throw boost::thread_interrupted();
48265f3c 558
51eb5273
JG
559 return true;
560 };
561 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
562 std::lock_guard<std::mutex> lock{m_cs};
563 return cancelSolver;
564 };
565 try {
566 // If we find a valid block, we rebuild
567 if (EhOptimisedSolve(n, k, curr_state, validBlock, cancelled))
568 break;
569 } catch (EhSolverCancelledException&) {
570 LogPrint("pow", "Equihash solver cancelled\n");
571 std::lock_guard<std::mutex> lock{m_cs};
572 cancelSolver = false;
48265f3c 573 }
d247a5d1 574
0655fac0
PK
575 // Check for stop or if block needs to be rebuilt
576 boost::this_thread::interruption_point();
577 // Regtest mode doesn't require peers
bebe7282 578 if (vNodes.empty() && chainparams.MiningRequiresPeers())
0655fac0 579 break;
8e165d57 580 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
0655fac0
PK
581 break;
582 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
583 break;
584 if (pindexPrev != chainActive.Tip())
585 break;
586
8e165d57
JG
587 // Update nNonce and nTime
588 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
bebe7282
JT
589 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
590 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
48265f3c
WL
591 {
592 // Changing pblock->nTime can change work required on testnet:
593 hashTarget.SetCompact(pblock->nBits);
594 }
d247a5d1
JG
595 }
596 }
0655fac0 597 }
27df4123 598 catch (const boost::thread_interrupted&)
d247a5d1 599 {
fdda3c50 600 LogPrintf("ZcashMiner terminated\n");
d247a5d1
JG
601 throw;
602 }
bba7c249
GM
603 catch (const std::runtime_error &e)
604 {
fdda3c50 605 LogPrintf("ZcashMiner runtime error: %s\n", e.what());
bba7c249
GM
606 return;
607 }
5a360a5c 608 c.disconnect();
d247a5d1
JG
609}
610
c8b74258 611void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
d247a5d1
JG
612{
613 static boost::thread_group* minerThreads = NULL;
614
d247a5d1 615 if (nThreads < 0) {
2595b9ac 616 // In regtest threads defaults to 1
617 if (Params().DefaultMinerThreads())
618 nThreads = Params().DefaultMinerThreads();
d247a5d1
JG
619 else
620 nThreads = boost::thread::hardware_concurrency();
621 }
622
623 if (minerThreads != NULL)
624 {
625 minerThreads->interrupt_all();
626 delete minerThreads;
627 minerThreads = NULL;
628 }
629
630 if (nThreads == 0 || !fGenerate)
631 return;
632
633 minerThreads = new boost::thread_group();
634 for (int i = 0; i < nThreads; i++)
635 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
636}
637
0655fac0 638#endif // ENABLE_WALLET
This page took 0.186059 seconds and 4 git commands to generate.