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