]> Git Repo - VerusCoin.git/blob - src/miner.cpp
Add notary 3 to recent miners print
[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 #ifdef ENABLE_MINING
8 #include "pow/tromp/equi_miner.h"
9 #endif
10
11 #include "amount.h"
12 #include "base58.h"
13 #include "chainparams.h"
14 #include "consensus/consensus.h"
15 #include "consensus/upgrades.h"
16 #include "consensus/validation.h"
17 #ifdef ENABLE_MINING
18 #include "crypto/equihash.h"
19 #endif
20 #include "hash.h"
21 #include "main.h"
22 #include "metrics.h"
23 #include "net.h"
24 #include "pow.h"
25 #include "primitives/transaction.h"
26 #include "random.h"
27 #include "timedata.h"
28 #include "ui_interface.h"
29 #include "util.h"
30 #include "utilmoneystr.h"
31 #ifdef ENABLE_WALLET
32 #include "wallet/wallet.h"
33 #endif
34
35 #include "sodium.h"
36
37 #include <boost/thread.hpp>
38 #include <boost/tuple/tuple.hpp>
39 #ifdef ENABLE_MINING
40 #include <functional>
41 #endif
42 #include <mutex>
43
44 using namespace std;
45
46 //////////////////////////////////////////////////////////////////////////////
47 //
48 // BitcoinMiner
49 //
50
51 //
52 // Unconfirmed transactions in the memory pool often depend on other
53 // transactions in the memory pool. When we select transactions from the
54 // pool, we select by highest priority or fee rate, so we might consider
55 // transactions that depend on transactions that aren't yet in the block.
56 // The COrphan class keeps track of these 'temporary orphans' while
57 // CreateBlock is figuring out which transactions to include.
58 //
59 class COrphan
60 {
61 public:
62     const CTransaction* ptx;
63     set<uint256> setDependsOn;
64     CFeeRate feeRate;
65     double dPriority;
66     
67     COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
68     {
69     }
70 };
71
72 uint64_t nLastBlockTx = 0;
73 uint64_t nLastBlockSize = 0;
74
75 // We want to sort transactions by priority and fee rate, so:
76 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
77 class TxPriorityCompare
78 {
79     bool byFee;
80     
81 public:
82     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
83     
84     bool operator()(const TxPriority& a, const TxPriority& b)
85     {
86         if (byFee)
87         {
88             if (a.get<1>() == b.get<1>())
89                 return a.get<0>() < b.get<0>();
90             return a.get<1>() < b.get<1>();
91         }
92         else
93         {
94             if (a.get<0>() == b.get<0>())
95                 return a.get<1>() < b.get<1>();
96             return a.get<0>() < b.get<0>();
97         }
98     }
99 };
100
101 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
102 {
103     pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
104 }
105
106 #include "komodo_defs.h"
107
108 extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
109 extern uint64_t ASSETCHAINS_REWARD,ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED;
110 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
111 extern std::string NOTARY_PUBKEY;
112 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
113 uint32_t Mining_start,Mining_height;
114 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
115 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
116 //uint64_t komodo_paxtotal();
117 int32_t komodo_baseid(char *origbase);
118 //int32_t komodo_is_issuer();
119 //int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
120 //int32_t komodo_isrealtime(int32_t *kmdheightp);
121 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
122 uint64_t komodo_commission(const CBlock *block);
123 int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
124
125 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
126 {
127     uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
128     // Create new block
129     std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
130     if(!pblocktemplate.get())
131     {
132         fprintf(stderr,"pblocktemplate.get() failure\n");
133         return NULL;
134     }
135     CBlock *pblock = &pblocktemplate->block; // pointer for convenience
136     /*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
137     {
138         isrealtime = komodo_isrealtime(&kmdheight);
139         deposits = komodo_paxtotal();
140         while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
141         {
142             deposits = komodo_paxtotal();
143             if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
144             {
145                 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
146             }
147             else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
148             {
149                 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(),isrealtime,KOMODO_ON_DEMAND);
150                 break;
151             }
152             sleep(10);
153         }
154         KOMODO_ON_DEMAND = 0;
155         if ( 0 && deposits != 0 )
156             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());
157     }*/
158     // -regtest only: allow overriding block.nVersion with
159     // -blockversion=N to test forking scenarios
160     if (Params().MineBlocksOnDemand())
161         pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
162     
163     // Add dummy coinbase tx as first transaction
164     pblock->vtx.push_back(CTransaction());
165     pblocktemplate->vTxFees.push_back(-1); // updated at end
166     pblocktemplate->vTxSigOps.push_back(-1); // updated at end
167     
168     // Largest block you're willing to create:
169     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
170     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
171     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
172     
173     // How much of the block should be dedicated to high-priority transactions,
174     // included regardless of the fees they pay
175     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
176     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
177     
178     // Minimum block size you want to create; block will be filled with free transactions
179     // until there are no more or the block reaches this size:
180     unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
181     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
182     
183     // Collect memory pool transactions into the block
184     CAmount nFees = 0;
185     
186     {
187         LOCK2(cs_main, mempool.cs);
188         CBlockIndex* pindexPrev = chainActive.Tip();
189         const int nHeight = pindexPrev->nHeight + 1;
190         uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
191         pblock->nTime = GetAdjustedTime();
192         const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
193         CCoinsViewCache view(pcoinsTip);
194         uint32_t expired; uint64_t commission;
195         
196         // Priority order to process transactions
197         list<COrphan> vOrphan; // list memory doesn't move
198         map<uint256, vector<COrphan*> > mapDependers;
199         bool fPrintPriority = GetBoolArg("-printpriority", false);
200         
201         // This vector will be sorted into a priority queue:
202         vector<TxPriority> vecPriority;
203         vecPriority.reserve(mempool.mapTx.size());
204         for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
205              mi != mempool.mapTx.end(); ++mi)
206         {
207             const CTransaction& tx = mi->GetTx();
208             
209             int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
210             ? nMedianTimePast
211             : pblock->GetBlockTime();
212             
213             if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
214             {
215                 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
216                 continue;
217             }
218             if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
219             {
220                 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
221                 continue;
222             }
223             COrphan* porphan = NULL;
224             double dPriority = 0;
225             CAmount nTotalIn = 0;
226             bool fMissingInputs = false;
227             BOOST_FOREACH(const CTxIn& txin, tx.vin)
228             {
229                 // Read prev transaction
230                 if (!view.HaveCoins(txin.prevout.hash))
231                 {
232                     // This should never happen; all transactions in the memory
233                     // pool should connect to either transactions in the chain
234                     // or other transactions in the memory pool.
235                     if (!mempool.mapTx.count(txin.prevout.hash))
236                     {
237                         LogPrintf("ERROR: mempool transaction missing input\n");
238                         if (fDebug) assert("mempool transaction missing input" == 0);
239                         fMissingInputs = true;
240                         if (porphan)
241                             vOrphan.pop_back();
242                         break;
243                     }
244                     
245                     // Has to wait for dependencies
246                     if (!porphan)
247                     {
248                         // Use list for automatic deletion
249                         vOrphan.push_back(COrphan(&tx));
250                         porphan = &vOrphan.back();
251                     }
252                     mapDependers[txin.prevout.hash].push_back(porphan);
253                     porphan->setDependsOn.insert(txin.prevout.hash);
254                     nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
255                     continue;
256                 }
257                 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
258                 assert(coins);
259                 
260                 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
261                 nTotalIn += nValueIn;
262                 
263                 int nConf = nHeight - coins->nHeight;
264                 
265                 dPriority += (double)nValueIn * nConf;
266             }
267             nTotalIn += tx.GetJoinSplitValueIn();
268             
269             if (fMissingInputs) continue;
270             
271             // Priority is sum(valuein * age) / modified_txsize
272             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
273             dPriority = tx.ComputePriority(dPriority, nTxSize);
274             
275             uint256 hash = tx.GetHash();
276             mempool.ApplyDeltas(hash, dPriority, nTotalIn);
277             
278             CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
279             
280             if (porphan)
281             {
282                 porphan->dPriority = dPriority;
283                 porphan->feeRate = feeRate;
284             }
285             else
286                 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
287         }
288         
289         // Collect transactions into block
290         uint64_t nBlockSize = 1000;
291         uint64_t nBlockTx = 0;
292         int64_t interest;
293         int nBlockSigOps = 100;
294         bool fSortedByFee = (nBlockPrioritySize <= 0);
295         
296         TxPriorityCompare comparer(fSortedByFee);
297         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
298         
299         while (!vecPriority.empty())
300         {
301             // Take highest priority transaction off the priority queue:
302             double dPriority = vecPriority.front().get<0>();
303             CFeeRate feeRate = vecPriority.front().get<1>();
304             const CTransaction& tx = *(vecPriority.front().get<2>());
305             
306             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
307             vecPriority.pop_back();
308             
309             // Size limits
310             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
311             if (nBlockSize + nTxSize >= nBlockMaxSize)
312             {
313                 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
314                 continue;
315             }
316             
317             // Legacy limits on sigOps:
318             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
319             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
320             {
321                 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
322                 continue;
323             }
324             // Skip free transactions if we're past the minimum block size:
325             const uint256& hash = tx.GetHash();
326             double dPriorityDelta = 0;
327             CAmount nFeeDelta = 0;
328             mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
329             if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
330             {
331                 //fprintf(stderr,"fee rate skip\n");
332                 continue;
333             }
334             // Prioritise by fee once past the priority size or we run out of high-priority
335             // transactions:
336             if (!fSortedByFee &&
337                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
338             {
339                 fSortedByFee = true;
340                 comparer = TxPriorityCompare(fSortedByFee);
341                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
342             }
343             
344             if (!view.HaveInputs(tx))
345             {
346                 //fprintf(stderr,"dont have inputs\n");
347                 continue;
348             }
349             CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
350             
351             nTxSigOps += GetP2SHSigOpCount(tx, view);
352             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
353             {
354                 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
355                 continue;
356             }
357             // Note that flags: we don't want to set mempool/IsStandard()
358             // policy here, but we still have to ensure that the block we
359             // create only contains transactions that are valid in new blocks.
360             CValidationState state;
361             PrecomputedTransactionData txdata(tx);
362             if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
363             {
364                 //fprintf(stderr,"context failure\n");
365                 continue;
366             }
367             UpdateCoins(tx, view, nHeight);
368             
369             // Added
370             pblock->vtx.push_back(tx);
371             pblocktemplate->vTxFees.push_back(nTxFees);
372             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
373             nBlockSize += nTxSize;
374             ++nBlockTx;
375             nBlockSigOps += nTxSigOps;
376             nFees += nTxFees;
377             
378             if (fPrintPriority)
379             {
380                 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
381             }
382             
383             // Add transactions that depend on this one to the priority queue
384             if (mapDependers.count(hash))
385             {
386                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
387                 {
388                     if (!porphan->setDependsOn.empty())
389                     {
390                         porphan->setDependsOn.erase(hash);
391                         if (porphan->setDependsOn.empty())
392                         {
393                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
394                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
395                         }
396                     }
397                 }
398             }
399         }
400         
401         nLastBlockTx = nBlockTx;
402         nLastBlockSize = nBlockSize;
403         blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
404         //pblock->nTime = blocktime + 1;
405         pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
406         //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
407         if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
408         {
409             uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
410             CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
411             //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
412             //    blocktime = pindexPrev->GetMedianTimePast() + 60;
413             if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
414             {
415                 CAmount txfees = 0;
416                 pblock->vtx.push_back(txStaked);
417                 pblocktemplate->vTxFees.push_back(txfees);
418                 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
419                 nFees += txfees;
420                 pblock->nTime = blocktime;
421                 if ( GetAdjustedTime() < pblock->nTime )//|| pblock->GetBlockTime() > GetAdjustedTime() + 60)
422                 {
423                     fprintf(stderr,"need to wait %d seconds to mine:\n",(int32_t)(pblock->nTime - GetAdjustedTime()));
424                     while ( GetAdjustedTime()+30 < pblock->nTime )
425                     {
426                         sleep(30);
427                         fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime()));
428                     }
429                     fprintf(stderr,"finished waiting\n");
430                     //sleep(pblock->nTime - GetAdjustedTime());
431                 }
432             } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
433         }
434         
435         // Create coinbase tx
436         CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
437         txNew.vin.resize(1);
438         txNew.vin[0].prevout.SetNull();
439         txNew.vout.resize(1);
440         txNew.vout[0].scriptPubKey = scriptPubKeyIn;
441         txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
442         txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
443         txNew.nExpiryHeight = 0;
444         // Add fees
445         txNew.vout[0].nValue += nFees;
446         txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
447                 
448         pblock->vtx[0] = txNew;
449         if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
450         {
451             int32_t i; uint8_t *ptr;
452             txNew.vout.resize(2);
453             txNew.vout[1].nValue = commission;
454             txNew.vout[1].scriptPubKey.resize(35);
455             ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
456             ptr[0] = 33;
457             for (i=0; i<33; i++)
458                 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
459             ptr[34] = OP_CHECKSIG;
460             //printf("autocreate commision vout\n");
461             pblock->vtx[0] = txNew;
462         }
463         pblocktemplate->vTxFees[0] = -nFees;
464         // Randomise nonce
465         arith_uint256 nonce = UintToArith256(GetRandHash());
466         // Clear the top and bottom 16 bits (for local use as thread flags and counters)
467         nonce <<= 32;
468         nonce >>= 16;
469         pblock->nNonce = ArithToUint256(nonce);
470         
471         // Fill in header
472         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
473         pblock->hashReserved   = uint256();
474         if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
475         {
476             UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
477             pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
478         }
479         if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 )
480         {
481             pblock->nTime = pindexPrev->nTime + 60;
482             while ( pblock->GetBlockTime() > GetAdjustedTime() + 10 )
483                 sleep(1);
484             //fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60));
485         }
486         pblock->nSolution.clear();
487         pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
488         
489         CValidationState state;
490         if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
491         {
492             //static uint32_t counter;
493             //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
494             //    fprintf(stderr,"warning: miner testblockvalidity failed\n");
495             return(0);
496         }
497     }
498     
499     return pblocktemplate.release();
500 }
501  
502 /*
503  #ifdef ENABLE_WALLET
504  boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
505  #else
506  boost::optional<CScript> GetMinerScriptPubKey()
507  #endif
508  {
509  CKeyID keyID;
510  CBitcoinAddress addr;
511  if (addr.SetString(GetArg("-mineraddress", ""))) {
512  addr.GetKeyID(keyID);
513  } else {
514  #ifdef ENABLE_WALLET
515  CPubKey pubkey;
516  if (!reservekey.GetReservedKey(pubkey)) {
517  return boost::optional<CScript>();
518  }
519  keyID = pubkey.GetID();
520  #else
521  return boost::optional<CScript>();
522  #endif
523  }
524  
525  CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
526  return scriptPubKey;
527  }
528  
529  #ifdef ENABLE_WALLET
530  CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
531  {
532  boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
533  #else
534  CBlockTemplate* CreateNewBlockWithKey()
535  {
536  boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
537  #endif
538  
539  if (!scriptPubKey) {
540  return NULL;
541  }
542  return CreateNewBlock(*scriptPubKey);
543  }*/
544
545 //////////////////////////////////////////////////////////////////////////////
546 //
547 // Internal miner
548 //
549
550 #ifdef ENABLE_MINING
551
552 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
553 {
554     // Update nExtraNonce
555     static uint256 hashPrevBlock;
556     if (hashPrevBlock != pblock->hashPrevBlock)
557     {
558         nExtraNonce = 0;
559         hashPrevBlock = pblock->hashPrevBlock;
560     }
561     ++nExtraNonce;
562     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
563     CMutableTransaction txCoinbase(pblock->vtx[0]);
564     txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
565     assert(txCoinbase.vin[0].scriptSig.size() <= 100);
566     
567     pblock->vtx[0] = txCoinbase;
568     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
569 }
570
571 #ifdef ENABLE_WALLET
572 //////////////////////////////////////////////////////////////////////////////
573 //
574 // Internal miner
575 //
576
577 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
578 {
579     CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
580     if ( USE_EXTERNAL_PUBKEY != 0 )
581     {
582         //fprintf(stderr,"use notary pubkey\n");
583         scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
584     }
585     else
586     {
587         if (!reservekey.GetReservedKey(pubkey))
588         {
589             return NULL;
590         }
591         scriptPubKey.resize(35);
592         ptr = (uint8_t *)pubkey.begin();
593         script = (uint8_t *)scriptPubKey.data();
594         script[0] = 33;
595         for (i=0; i<33; i++)
596             script[i+1] = ptr[i];
597         script[34] = OP_CHECKSIG;
598         //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
599     }
600     return CreateNewBlock(scriptPubKey);
601 }
602
603 void komodo_broadcast(CBlock *pblock,int32_t limit)
604 {
605     int32_t n = 1;
606     //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
607     {
608         LOCK(cs_vNodes);
609         BOOST_FOREACH(CNode* pnode, vNodes)
610         {
611             if ( pnode->hSocket == INVALID_SOCKET )
612                 continue;
613             if ( (rand() % n) == 0 )
614             {
615                 pnode->PushMessage("block", *pblock);
616                 if ( n++ > limit )
617                     break;
618             }
619         }
620     }
621     //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
622 }
623
624 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
625 #else
626 static bool ProcessBlockFound(CBlock* pblock)
627 #endif // ENABLE_WALLET
628 {
629     LogPrintf("%s\n", pblock->ToString());
630     LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
631     
632     // Found a solution
633     {
634         LOCK(cs_main);
635         if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
636         {
637             uint256 hash; int32_t i;
638             hash = pblock->hashPrevBlock;
639             for (i=31; i>=0; i--)
640                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
641             fprintf(stderr," <- prev (stale)\n");
642             hash = chainActive.Tip()->GetBlockHash();
643             for (i=31; i>=0; i--)
644                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
645             fprintf(stderr," <- chainTip (stale)\n");
646             
647             return error("KomodoMiner: generated block is stale");
648         }
649     }
650     
651 #ifdef ENABLE_WALLET
652     // Remove key from key pool
653     if ( IS_KOMODO_NOTARY == 0 )
654     {
655         if (GetArg("-mineraddress", "").empty()) {
656             // Remove key from key pool
657             reservekey.KeepKey();
658         }
659     }
660     // Track how many getdata requests this block gets
661     //if ( 0 )
662     {
663         LOCK(wallet.cs_wallet);
664         wallet.mapRequestCount[pblock->GetHash()] = 0;
665     }
666 #endif
667     
668     // Process this block the same as if we had received it from another node
669     CValidationState state;
670     if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
671         return error("KomodoMiner: ProcessNewBlock, block not accepted");
672     
673     TrackMinedBlock(pblock->GetHash());
674     komodo_broadcast(pblock,16);
675     return true;
676 }
677
678 int32_t komodo_baseid(char *origbase);
679 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
680 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
681 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
682 extern int32_t KOMODO_LASTMINED;
683 int32_t roundrobin_delay;
684 arith_uint256 HASHTarget,HASHTarget_POW;
685
686 #ifdef ENABLE_WALLET
687 void static BitcoinMiner(CWallet *pwallet)
688 #else
689 void static BitcoinMiner()
690 #endif
691 {
692     LogPrintf("KomodoMiner started\n");
693     SetThreadPriority(THREAD_PRIORITY_LOWEST);
694     RenameThread("komodo-miner");
695     const CChainParams& chainparams = Params();
696     
697 #ifdef ENABLE_WALLET
698     // Each thread has its own key
699     CReserveKey reservekey(pwallet);
700 #endif
701     
702     // Each thread has its own counter
703     unsigned int nExtraNonce = 0;
704     
705     unsigned int n = chainparams.EquihashN();
706     unsigned int k = chainparams.EquihashK();
707     uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
708     while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
709     {
710         sleep(1);
711         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
712             break;
713     }
714     komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
715     
716     std::string solver;
717     //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
718     solver = "tromp";
719     //else solver = "default";
720     assert(solver == "tromp" || solver == "default");
721     LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
722     if ( ASSETCHAINS_SYMBOL[0] != 0 )
723         fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
724     std::mutex m_cs;
725     bool cancelSolver = false;
726     boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
727                                                                        [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
728                                                                            std::lock_guard<std::mutex> lock{m_cs};
729                                                                            cancelSolver = true;
730                                                                        }
731                                                                        );
732     miningTimer.start();
733     
734     try {
735         if ( ASSETCHAINS_SYMBOL[0] != 0 )
736             fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
737         while (true)
738         {
739             if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
740             {
741                 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
742                 //    break;
743                 // Busy-wait for the network to come online so we don't waste time mining
744                 // on an obsolete chain. In regtest mode we expect to fly solo.
745                 miningTimer.stop();
746                 do {
747                     bool fvNodesEmpty;
748                     {
749                         //LOCK(cs_vNodes);
750                         fvNodesEmpty = vNodes.empty();
751                     }
752                     if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
753                         break;
754                     MilliSleep(5000);
755                     //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
756                     
757                 } while (true);
758                 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
759                 miningTimer.start();
760             }
761             /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
762              {
763              fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
764              sleep(3);
765              }*/
766             //
767             // Create new block
768             //
769             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
770             CBlockIndex* pindexPrev = chainActive.Tip();
771             if ( Mining_height != pindexPrev->nHeight+1 )
772             {
773                 Mining_height = pindexPrev->nHeight+1;
774                 Mining_start = (uint32_t)time(NULL);
775             }
776             if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
777             {
778                 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
779                 sleep(3);
780             }
781 #ifdef ENABLE_WALLET
782             CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
783 #else
784             CBlockTemplate *ptr = CreateNewBlockWithKey();
785 #endif
786             if ( ptr == 0 )
787             {
788                 static uint32_t counter;
789                 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
790                     fprintf(stderr,"created illegal block, retry\n");
791                 sleep(3);
792                 continue;
793             }
794             unique_ptr<CBlockTemplate> pblocktemplate(ptr);
795             if (!pblocktemplate.get())
796             {
797                 if (GetArg("-mineraddress", "").empty()) {
798                     LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
799                 } else {
800                     // Should never reach here, because -mineraddress validity is checked in init.cpp
801                     LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
802                 }
803                 return;
804             }
805             CBlock *pblock = &pblocktemplate->block;
806             if ( ASSETCHAINS_SYMBOL[0] != 0 )
807             {
808                 if ( ASSETCHAINS_REWARD == 0 )
809                 {
810                     if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
811                     {
812                         static uint32_t counter;
813                         if ( counter++ < 10 )
814                             fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
815                         sleep(10);
816                         continue;
817                     } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
818                 }
819             }
820             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
821             LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
822             //
823             // Search
824             //
825             uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
826             savebits = pblock->nBits;
827             HASHTarget = arith_uint256().SetCompact(pblock->nBits);
828             roundrobin_delay = ROUNDROBIN_DELAY;
829             if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
830             {
831                 j = 65;
832                 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
833                 {
834                     komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
835                     if ( nonzpkeys > 0 )
836                     {
837                         for (i=0; i<33; i++)
838                             if( pubkeys[0][i] != 0 )
839                                 break;
840                         if ( i == 33 )
841                             externalflag = 1;
842                         else externalflag = 0;
843                         if ( NOTARY_PUBKEY33[0] != 0 )
844                         {
845                             for (i=1; i<66; i++)
846                                 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
847                                     break;
848                             if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
849                                 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
850                             for (j=gpucount=0; j<65; j++)
851                             {
852                                 if ( notaryid <= 3 || notaryid == 34 || notaryid == 51 || notaryid == 52 )
853                                 {
854                                     if ( mids[j] >= 0 )
855                                         fprintf(stderr,"%d ",mids[j]);
856                                     else fprintf(stderr,"GPU ");
857                                 }
858                                 if ( mids[j] == -1 )
859                                     gpucount++;
860                             }
861                             if ( gpucount > j/2 )
862                             {
863                                 double delta;
864                                 if ( notaryid < 0 )
865                                     i = (rand() % 64);
866                                 else i = ((Mining_height + notaryid) % 64);
867                                 delta = sqrt((double)gpucount - j/2) / 2.;
868                                 roundrobin_delay += ((delta * i) / 64) - delta;
869                                 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
870                             }
871                             fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay);
872                         }
873                         for (j=0; j<65; j++)
874                             if ( mids[j] == notaryid )
875                                 break;
876                         if ( j == 65 )
877                             KOMODO_LASTMINED = 0;
878                     } else fprintf(stderr,"no nonz pubkeys\n");
879                     if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
880                     {
881                         HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
882                         fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
883                     } //else fprintf(stderr,"duplicate at j.%d\n",j);
884                 } else Mining_start = 0;
885             } else Mining_start = 0;
886             if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
887             {
888                 int32_t percPoS,z;
889                 /*if ( Mining_height <= 100 )
890                 {
891                     sleep(60);
892                     continue;
893                 }*/
894                 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
895                 for (z=31; z>=0; z--)
896                     fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
897                 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
898             }
899             while (true)
900             {
901                 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
902                  {
903                  fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
904                  sleep(10);
905                  break;
906                  }*/
907                 // Hash state
908                 KOMODO_CHOSEN_ONE = 0;
909                 crypto_generichash_blake2b_state state;
910                 EhInitialiseState(n, k, state);
911                 // I = the block header minus nonce and solution.
912                 CEquihashInput I{*pblock};
913                 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
914                 ss << I;
915                 // H(I||...
916                 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
917                 // H(I||V||...
918                 crypto_generichash_blake2b_state curr_state;
919                 curr_state = state;
920                 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
921                 // (x_1, x_2, ...) = A(I, V, n, k)
922                 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
923                 arith_uint256 hashTarget;
924                 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 )
925                     hashTarget = HASHTarget_POW;
926                 else hashTarget = HASHTarget;
927                 std::function<bool(std::vector<unsigned char>)> validBlock =
928 #ifdef ENABLE_WALLET
929                 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
930 #else
931                 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
932 #endif
933                 (std::vector<unsigned char> soln) {
934                     int32_t z; arith_uint256 h; CBlock B;
935                     // Write the solution to the hash and compute the result.
936                     LogPrint("pow", "- Checking solution against target\n");
937                     pblock->nSolution = soln;
938                     solutionTargetChecks.increment();
939                     B = *pblock;
940                     h = UintToArith256(B.GetHash());
941                     if ( h > hashTarget )
942                         return false;
943                     /*for (z=31; z>=16; z--)
944                         fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
945                     fprintf(stderr," mined ");
946                     for (z=31; z>=16; z--)
947                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
948                     fprintf(stderr," hashTarget ");
949                     for (z=31; z>=16; z--)
950                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
951                     fprintf(stderr," POW\n");*/
952                     CValidationState state;
953                     if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
954                     {
955                         h = UintToArith256(B.GetHash());
956                         for (z=31; z>=0; z--)
957                             fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
958                         fprintf(stderr," Invalid block mined, try again\n");
959                         return(false);
960                     }
961                     if ( ASSETCHAINS_STAKED == 0 )
962                     {
963                         if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay )
964                         {
965                             //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL)));
966                             //int32_t nseconds = Mining_start+roundrobin_delay-time(NULL);
967                             //if ( nseconds > 0 )
968                             //    sleep(nseconds);
969                             MilliSleep((rand() % 1700) + 1);
970                         }
971                         else if ( ASSETCHAINS_SYMBOL[0] != 0 )
972                         {
973                             sleep(rand() % 30);
974                         }
975                     }
976                     else
977                     {
978                         if ( NOTARY_PUBKEY33[0] != 0 )
979                         {
980                             printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
981                             while ( GetAdjustedTime() < B.nTime )
982                                 sleep(1);
983                         }
984                         else
985                         {
986                             uint256 tmp = B.GetHash();
987                             int32_t z; for (z=31; z>=0; z--)
988                                 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
989                             fprintf(stderr," mined block!\n");
990                         }
991                     }
992                     KOMODO_CHOSEN_ONE = 1;
993                     // Found a solution
994                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
995                     LogPrintf("KomodoMiner:\n");
996                     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
997 #ifdef ENABLE_WALLET
998                     if (ProcessBlockFound(&B, *pwallet, reservekey)) {
999 #else
1000                         if (ProcessBlockFound(&B)) {
1001 #endif
1002                             // Ignore chain updates caused by us
1003                             std::lock_guard<std::mutex> lock{m_cs};
1004                             cancelSolver = false;
1005                         }
1006                         KOMODO_CHOSEN_ONE = 0;
1007                         SetThreadPriority(THREAD_PRIORITY_LOWEST);
1008                         // In regression test mode, stop mining after a block is found.
1009                         if (chainparams.MineBlocksOnDemand()) {
1010                             // Increment here because throwing skips the call below
1011                             ehSolverRuns.increment();
1012                             throw boost::thread_interrupted();
1013                         }
1014                         //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1015                         //    sleep(1800);
1016                         return true;
1017                     };
1018                     std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1019                         std::lock_guard<std::mutex> lock{m_cs};
1020                         return cancelSolver;
1021                     };
1022                     
1023                     // TODO: factor this out into a function with the same API for each solver.
1024                     if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1025                         // Create solver and initialize it.
1026                         equi eq(1);
1027                         eq.setstate(&curr_state);
1028                         
1029                         // Initialization done, start algo driver.
1030                         eq.digit0(0);
1031                         eq.xfull = eq.bfull = eq.hfull = 0;
1032                         eq.showbsizes(0);
1033                         for (u32 r = 1; r < WK; r++) {
1034                             (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1035                             eq.xfull = eq.bfull = eq.hfull = 0;
1036                             eq.showbsizes(r);
1037                         }
1038                         eq.digitK(0);
1039                         ehSolverRuns.increment();
1040                         
1041                         // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1042                         for (size_t s = 0; s < eq.nsols; s++) {
1043                             LogPrint("pow", "Checking solution %d\n", s+1);
1044                             std::vector<eh_index> index_vector(PROOFSIZE);
1045                             for (size_t i = 0; i < PROOFSIZE; i++) {
1046                                 index_vector[i] = eq.sols[s][i];
1047                             }
1048                             std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1049                             
1050                             if (validBlock(sol_char)) {
1051                                 // If we find a POW solution, do not try other solutions
1052                                 // because they become invalid as we created a new block in blockchain.
1053                                 break;
1054                             }
1055                         }
1056                     } else {
1057                         try {
1058                             // If we find a valid block, we rebuild
1059                             bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1060                             ehSolverRuns.increment();
1061                             if (found) {
1062                                 int32_t i; uint256 hash = pblock->GetHash();
1063                                 for (i=0; i<32; i++)
1064                                     fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1065                                 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1066                                 FOUND_BLOCK = 1;
1067                                 KOMODO_MAYBEMINED = Mining_height;
1068                                 break;
1069                             }
1070                         } catch (EhSolverCancelledException&) {
1071                             LogPrint("pow", "Equihash solver cancelled\n");
1072                             std::lock_guard<std::mutex> lock{m_cs};
1073                             cancelSolver = false;
1074                         }
1075                     }
1076                     
1077                     // Check for stop or if block needs to be rebuilt
1078                     boost::this_thread::interruption_point();
1079                     // Regtest mode doesn't require peers
1080                     if ( FOUND_BLOCK != 0 )
1081                     {
1082                         FOUND_BLOCK = 0;
1083                         fprintf(stderr,"FOUND_BLOCK!\n");
1084                         //sleep(2000);
1085                     }
1086                     if (vNodes.empty() && chainparams.MiningRequiresPeers())
1087                     {
1088                         if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1089                         {
1090                             fprintf(stderr,"no nodes, break\n");
1091                             break;
1092                         }
1093                     }
1094                     if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1095                     {
1096                         //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1097                         fprintf(stderr,"0xffff, break\n");
1098                         break;
1099                     }
1100                     if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1101                     {
1102                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1103                             fprintf(stderr,"timeout, break\n");
1104                         break;
1105                     }
1106                     if ( pindexPrev != chainActive.Tip() )
1107                     {
1108                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1109                             fprintf(stderr,"Tip advanced, break\n");
1110                         break;
1111                     }
1112                     // Update nNonce and nTime
1113                     pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1114                     pblock->nBits = savebits;
1115                     /*if ( NOTARY_PUBKEY33[0] == 0 )
1116                     {
1117                         int32_t percPoS;
1118                         UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1119                         if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1120                         {
1121                             // Changing pblock->nTime can change work required on testnet:
1122                             HASHTarget.SetCompact(pblock->nBits);
1123                             HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1124                         }
1125                     }*/
1126                 }
1127             }
1128         }
1129         catch (const boost::thread_interrupted&)
1130         {
1131             miningTimer.stop();
1132             c.disconnect();
1133             LogPrintf("KomodoMiner terminated\n");
1134             throw;
1135         }
1136         catch (const std::runtime_error &e)
1137         {
1138             miningTimer.stop();
1139             c.disconnect();
1140             LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1141             return;
1142         }
1143         miningTimer.stop();
1144         c.disconnect();
1145     }
1146     
1147 #ifdef ENABLE_WALLET
1148     void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1149 #else
1150     void GenerateBitcoins(bool fGenerate, int nThreads)
1151 #endif
1152     {
1153         static boost::thread_group* minerThreads = NULL;
1154         
1155         if (nThreads < 0)
1156             nThreads = GetNumCores();
1157         
1158         if (minerThreads != NULL)
1159         {
1160             minerThreads->interrupt_all();
1161             delete minerThreads;
1162             minerThreads = NULL;
1163         }
1164         
1165         if (nThreads == 0 || !fGenerate)
1166             return;
1167         
1168         minerThreads = new boost::thread_group();
1169         for (int i = 0; i < nThreads; i++) {
1170 #ifdef ENABLE_WALLET
1171             minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1172 #else
1173             minerThreads->create_thread(&BitcoinMiner);
1174 #endif
1175         }
1176     }
1177     
1178 #endif // ENABLE_MINING
This page took 0.094512 seconds and 4 git commands to generate.