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