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