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