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