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