]> Git Repo - VerusCoin.git/blob - src/miner.cpp
Improve and complete getinfo output, cleanup unused reference
[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 #include "crypto/verus_hash.h"
20 #endif
21 #include "hash.h"
22
23 #include "main.h"
24 #include "metrics.h"
25 #include "net.h"
26 #include "pow.h"
27 #include "primitives/transaction.h"
28 #include "random.h"
29 #include "timedata.h"
30 #include "ui_interface.h"
31 #include "util.h"
32 #include "utilmoneystr.h"
33 #ifdef ENABLE_WALLET
34 #include "wallet/wallet.h"
35 #endif
36
37 #include "sodium.h"
38
39 #include <boost/thread.hpp>
40 #include <boost/tuple/tuple.hpp>
41 #ifdef ENABLE_MINING
42 #include <functional>
43 #endif
44 #include <mutex>
45
46 using namespace std;
47
48 //////////////////////////////////////////////////////////////////////////////
49 //
50 // BitcoinMiner
51 //
52
53 //
54 // Unconfirmed transactions in the memory pool often depend on other
55 // transactions in the memory pool. When we select transactions from the
56 // pool, we select by highest priority or fee rate, so we might consider
57 // transactions that depend on transactions that aren't yet in the block.
58 // The COrphan class keeps track of these 'temporary orphans' while
59 // CreateBlock is figuring out which transactions to include.
60 //
61 class COrphan
62 {
63 public:
64     const CTransaction* ptx;
65     set<uint256> setDependsOn;
66     CFeeRate feeRate;
67     double dPriority;
68     
69     COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
70     {
71     }
72 };
73
74 uint64_t nLastBlockTx = 0;
75 uint64_t nLastBlockSize = 0;
76
77 // We want to sort transactions by priority and fee rate, so:
78 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
79 class TxPriorityCompare
80 {
81     bool byFee;
82     
83 public:
84     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
85     
86     bool operator()(const TxPriority& a, const TxPriority& b)
87     {
88         if (byFee)
89         {
90             if (a.get<1>() == b.get<1>())
91                 return a.get<0>() < b.get<0>();
92             return a.get<1>() < b.get<1>();
93         }
94         else
95         {
96             if (a.get<0>() == b.get<0>())
97                 return a.get<1>() < b.get<1>();
98             return a.get<0>() < b.get<0>();
99         }
100     }
101 };
102
103 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
104 {
105     pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
106 }
107
108 #include "komodo_defs.h"
109
110 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;
111 extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
112 extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
113 extern const char *ASSETCHAINS_ALGORITHMS[];
114 extern int32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
115 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
116 extern std::string NOTARY_PUBKEY;
117 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
118 uint32_t Mining_start,Mining_height;
119 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
120 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
121 //uint64_t komodo_paxtotal();
122 int32_t komodo_baseid(char *origbase);
123 //int32_t komodo_is_issuer();
124 //int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
125 //int32_t komodo_isrealtime(int32_t *kmdheightp);
126 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
127 int64_t komodo_block_unlocktime(uint32_t nHeight);
128 uint64_t komodo_commission(const CBlock *block);
129 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);
130 int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
131
132 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
133 {
134     uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
135     // Create new block
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
199         const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
200         uint32_t proposedTime = GetAdjustedTime();
201         if (proposedTime == nMedianTimePast)
202         {
203             // too fast or stuck, this addresses the too fast issue, while moving
204             // forward as quickly as possible
205             for (int i; i < 100; i++)
206             {
207                 proposedTime = GetAdjustedTime();
208                 if (proposedTime == nMedianTimePast)
209                     MilliSleep(10);
210             }
211         }
212         pblock->nTime = GetAdjustedTime();
213
214         CCoinsViewCache view(pcoinsTip);
215         uint32_t expired; uint64_t commission;
216         
217         // Priority order to process transactions
218         list<COrphan> vOrphan; // list memory doesn't move
219         map<uint256, vector<COrphan*> > mapDependers;
220         bool fPrintPriority = GetBoolArg("-printpriority", false);
221         
222         // This vector will be sorted into a priority queue:
223         vector<TxPriority> vecPriority;
224         vecPriority.reserve(mempool.mapTx.size());
225         for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
226              mi != mempool.mapTx.end(); ++mi)
227         {
228             const CTransaction& tx = mi->GetTx();
229             
230             int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
231             ? nMedianTimePast
232             : pblock->GetBlockTime();
233             
234             if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
235             {
236                 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
237                 continue;
238             }
239             if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
240             {
241                 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
242                 continue;
243             }
244             COrphan* porphan = NULL;
245             double dPriority = 0;
246             CAmount nTotalIn = 0;
247             bool fMissingInputs = false;
248             BOOST_FOREACH(const CTxIn& txin, tx.vin)
249             {
250                 // Read prev transaction
251                 if (!view.HaveCoins(txin.prevout.hash))
252                 {
253                     // This should never happen; all transactions in the memory
254                     // pool should connect to either transactions in the chain
255                     // or other transactions in the memory pool.
256                     if (!mempool.mapTx.count(txin.prevout.hash))
257                     {
258                         LogPrintf("ERROR: mempool transaction missing input\n");
259                         if (fDebug) assert("mempool transaction missing input" == 0);
260                         fMissingInputs = true;
261                         if (porphan)
262                             vOrphan.pop_back();
263                         break;
264                     }
265                     
266                     // Has to wait for dependencies
267                     if (!porphan)
268                     {
269                         // Use list for automatic deletion
270                         vOrphan.push_back(COrphan(&tx));
271                         porphan = &vOrphan.back();
272                     }
273                     mapDependers[txin.prevout.hash].push_back(porphan);
274                     porphan->setDependsOn.insert(txin.prevout.hash);
275                     nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
276                     continue;
277                 }
278                 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
279                 assert(coins);
280                 
281                 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
282                 nTotalIn += nValueIn;
283                 
284                 int nConf = nHeight - coins->nHeight;
285                 
286                 dPriority += (double)nValueIn * nConf;
287             }
288             nTotalIn += tx.GetJoinSplitValueIn();
289             
290             if (fMissingInputs) continue;
291             
292             // Priority is sum(valuein * age) / modified_txsize
293             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
294             dPriority = tx.ComputePriority(dPriority, nTxSize);
295             
296             uint256 hash = tx.GetHash();
297             mempool.ApplyDeltas(hash, dPriority, nTotalIn);
298             
299             CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
300             
301             if (porphan)
302             {
303                 porphan->dPriority = dPriority;
304                 porphan->feeRate = feeRate;
305             }
306             else
307                 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
308         }
309         
310         // Collect transactions into block
311         uint64_t nBlockSize = 1000;
312         uint64_t nBlockTx = 0;
313         int64_t interest;
314         int nBlockSigOps = 100;
315         bool fSortedByFee = (nBlockPrioritySize <= 0);
316         
317         TxPriorityCompare comparer(fSortedByFee);
318         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
319         
320         while (!vecPriority.empty())
321         {
322             // Take highest priority transaction off the priority queue:
323             double dPriority = vecPriority.front().get<0>();
324             CFeeRate feeRate = vecPriority.front().get<1>();
325             const CTransaction& tx = *(vecPriority.front().get<2>());
326             
327             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
328             vecPriority.pop_back();
329             
330             // Size limits
331             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
332             if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
333             {
334                 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
335                 continue;
336             }
337             
338             // Legacy limits on sigOps:
339             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
340             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
341             {
342                 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
343                 continue;
344             }
345             // Skip free transactions if we're past the minimum block size:
346             const uint256& hash = tx.GetHash();
347             double dPriorityDelta = 0;
348             CAmount nFeeDelta = 0;
349             mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
350             if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
351             {
352                 //fprintf(stderr,"fee rate skip\n");
353                 continue;
354             }
355             // Prioritise by fee once past the priority size or we run out of high-priority
356             // transactions:
357             if (!fSortedByFee &&
358                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
359             {
360                 fSortedByFee = true;
361                 comparer = TxPriorityCompare(fSortedByFee);
362                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
363             }
364             
365             if (!view.HaveInputs(tx))
366             {
367                 //fprintf(stderr,"dont have inputs\n");
368                 continue;
369             }
370             CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
371             
372             nTxSigOps += GetP2SHSigOpCount(tx, view);
373             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
374             {
375                 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
376                 continue;
377             }
378             // Note that flags: we don't want to set mempool/IsStandard()
379             // policy here, but we still have to ensure that the block we
380             // create only contains transactions that are valid in new blocks.
381             CValidationState state;
382             PrecomputedTransactionData txdata(tx);
383             if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
384             {
385                 //fprintf(stderr,"context failure\n");
386                 continue;
387             }
388             UpdateCoins(tx, view, nHeight);
389             
390             // Added
391             pblock->vtx.push_back(tx);
392             pblocktemplate->vTxFees.push_back(nTxFees);
393             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
394             nBlockSize += nTxSize;
395             ++nBlockTx;
396             nBlockSigOps += nTxSigOps;
397             nFees += nTxFees;
398             
399             if (fPrintPriority)
400             {
401                 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
402             }
403             
404             // Add transactions that depend on this one to the priority queue
405             if (mapDependers.count(hash))
406             {
407                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
408                 {
409                     if (!porphan->setDependsOn.empty())
410                     {
411                         porphan->setDependsOn.erase(hash);
412                         if (porphan->setDependsOn.empty())
413                         {
414                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
415                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
416                         }
417                     }
418                 }
419             }
420         }
421         
422         nLastBlockTx = nBlockTx;
423         nLastBlockSize = nBlockSize;
424         blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
425         //pblock->nTime = blocktime + 1;
426         pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
427         //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
428         if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
429         {
430             uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
431             CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
432             //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
433             //    blocktime = pindexPrev->GetMedianTimePast() + 60;
434             if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
435             {
436                 CAmount txfees = 0;
437                 if ( GetAdjustedTime() < blocktime-13 )
438                     return(0);
439                 pblock->vtx.push_back(txStaked);
440                 pblocktemplate->vTxFees.push_back(txfees);
441                 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
442                 nFees += txfees;
443                 pblock->nTime = blocktime;
444                 //printf("PoS ht.%d t%u\n",(int32_t)chainActive.Tip()->nHeight+1,blocktime);
445             } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
446         }
447         
448         // Create coinbase tx
449         CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
450         txNew.vin.resize(1);
451         txNew.vin[0].prevout.SetNull();
452         txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
453
454         txNew.vout.resize(1);
455         txNew.vout[0].scriptPubKey = scriptPubKeyIn;
456         txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()) + nFees;
457         txNew.nExpiryHeight = 0;
458         txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
459
460         // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
461         // to transaction if so, cast for GTE operator
462         if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
463         {
464             int32_t opretlen, p2shlen, scriptlen;
465             CScriptExt opretScript = CScriptExt();
466
467             txNew.vout.resize(2);
468
469             // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
470             // protected only by the time lock rather than 100% inaccessible
471             opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
472             if (!scriptPubKeyIn.IsPayToScriptHash())
473                 opretScript += scriptPubKeyIn;
474
475             txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
476             txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
477             txNew.vout[1].nValue = 0;
478         } // timelocks and commissions are currently incompatible due to validation complexity of the combination
479         else if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
480         {
481             int32_t i; uint8_t *ptr;
482             txNew.vout.resize(2);
483             txNew.vout[1].nValue = commission;
484             txNew.vout[1].scriptPubKey.resize(35);
485             ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
486             ptr[0] = 33;
487             for (i=0; i<33; i++)
488                 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
489             ptr[34] = OP_CHECKSIG;
490             //printf("autocreate commision vout\n");
491         }
492
493         pblock->vtx[0] = txNew;
494         pblocktemplate->vTxFees[0] = -nFees;
495
496         // Randomise nonce
497         arith_uint256 nonce = UintToArith256(GetRandHash());
498
499         // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
500         nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
501         nonce >>= 16;
502         pblock->nNonce = ArithToUint256(nonce);
503         
504         // Fill in header
505         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
506         pblock->hashReserved   = uint256();
507         if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
508         {
509             UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
510             pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
511         }
512         pblock->nSolution.clear();
513         pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
514         if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
515         {
516             CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
517             if ( pblock->nTime < pindexPrev->nTime+65 )
518                 pblock->nTime = pindexPrev->nTime + 65;
519             if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
520             {
521                 CAmount txfees = 0;
522                 pblock->vtx.push_back(txNotary);
523                 pblocktemplate->vTxFees.push_back(txfees);
524                 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
525                 nFees += txfees;
526                 //fprintf(stderr,"added notaryvin\n");
527             }
528             else
529             {
530                 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
531                 return(0);
532             }
533         }
534         else
535         {
536             CValidationState state;
537             if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
538             {
539                 //static uint32_t counter;
540                 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
541                 //    fprintf(stderr,"warning: miner testblockvalidity failed\n");
542                 return(0);
543             }
544         }
545     }
546     
547     return pblocktemplate.release();
548 }
549  
550 /*
551  #ifdef ENABLE_WALLET
552  boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
553  #else
554  boost::optional<CScript> GetMinerScriptPubKey()
555  #endif
556  {
557  CKeyID keyID;
558  CBitcoinAddress addr;
559  if (addr.SetString(GetArg("-mineraddress", ""))) {
560  addr.GetKeyID(keyID);
561  } else {
562  #ifdef ENABLE_WALLET
563  CPubKey pubkey;
564  if (!reservekey.GetReservedKey(pubkey)) {
565  return boost::optional<CScript>();
566  }
567  keyID = pubkey.GetID();
568  #else
569  return boost::optional<CScript>();
570  #endif
571  }
572  
573  CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
574  return scriptPubKey;
575  }
576  
577  #ifdef ENABLE_WALLET
578  CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
579  {
580  boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
581  #else
582  CBlockTemplate* CreateNewBlockWithKey()
583  {
584  boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
585  #endif
586  
587  if (!scriptPubKey) {
588  return NULL;
589  }
590  return CreateNewBlock(*scriptPubKey);
591  }*/
592
593 //////////////////////////////////////////////////////////////////////////////
594 //
595 // Internal miner
596 //
597
598 #ifdef ENABLE_MINING
599
600 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
601 {
602     // Update nExtraNonce
603     static uint256 hashPrevBlock;
604     if (hashPrevBlock != pblock->hashPrevBlock)
605     {
606         nExtraNonce = 0;
607         hashPrevBlock = pblock->hashPrevBlock;
608     }
609     ++nExtraNonce;
610     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
611     CMutableTransaction txCoinbase(pblock->vtx[0]);
612     txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
613     assert(txCoinbase.vin[0].scriptSig.size() <= 100);
614     
615     pblock->vtx[0] = txCoinbase;
616     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
617 }
618
619 #ifdef ENABLE_WALLET
620 //////////////////////////////////////////////////////////////////////////////
621 //
622 // Internal miner
623 //
624
625 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
626 {
627     CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
628     if ( USE_EXTERNAL_PUBKEY != 0 )
629     {
630         //fprintf(stderr,"use notary pubkey\n");
631         scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
632     }
633     else
634     {
635         if (!reservekey.GetReservedKey(pubkey))
636         {
637             return NULL;
638         }
639         scriptPubKey.resize(35);
640         ptr = (uint8_t *)pubkey.begin();
641         script = (uint8_t *)scriptPubKey.data();
642         script[0] = 33;
643         for (i=0; i<33; i++)
644             script[i+1] = ptr[i];
645         script[34] = OP_CHECKSIG;
646         //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
647     }
648     return CreateNewBlock(scriptPubKey);
649 }
650
651 void komodo_broadcast(CBlock *pblock,int32_t limit)
652 {
653     int32_t n = 1;
654     //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
655     {
656         LOCK(cs_vNodes);
657         BOOST_FOREACH(CNode* pnode, vNodes)
658         {
659             if ( pnode->hSocket == INVALID_SOCKET )
660                 continue;
661             if ( (rand() % n) == 0 )
662             {
663                 pnode->PushMessage("block", *pblock);
664                 if ( n++ > limit )
665                     break;
666             }
667         }
668     }
669     //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
670 }
671
672 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
673 #else
674 static bool ProcessBlockFound(CBlock* pblock)
675 #endif // ENABLE_WALLET
676 {
677     LogPrintf("%s\n", pblock->ToString());
678     LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
679     
680     // Found a solution
681     {
682         LOCK(cs_main);
683         if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
684         {
685             uint256 hash; int32_t i;
686             hash = pblock->hashPrevBlock;
687             for (i=31; i>=0; i--)
688                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
689             fprintf(stderr," <- prev (stale)\n");
690             hash = chainActive.Tip()->GetBlockHash();
691             for (i=31; i>=0; i--)
692                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
693             fprintf(stderr," <- chainTip (stale)\n");
694             
695             return error("KomodoMiner: generated block is stale");
696         }
697     }
698     
699 #ifdef ENABLE_WALLET
700     // Remove key from key pool
701     if ( IS_KOMODO_NOTARY == 0 )
702     {
703         if (GetArg("-mineraddress", "").empty()) {
704             // Remove key from key pool
705             reservekey.KeepKey();
706         }
707     }
708     // Track how many getdata requests this block gets
709     //if ( 0 )
710     {
711         LOCK(wallet.cs_wallet);
712         wallet.mapRequestCount[pblock->GetHash()] = 0;
713     }
714 #endif
715     
716     // Process this block the same as if we had received it from another node
717     CValidationState state;
718     if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
719         return error("KomodoMiner: ProcessNewBlock, block not accepted");
720     
721     TrackMinedBlock(pblock->GetHash());
722     komodo_broadcast(pblock,16);
723     return true;
724 }
725
726 int32_t komodo_baseid(char *origbase);
727 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
728 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
729 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
730 extern int32_t KOMODO_LASTMINED;
731 int32_t roundrobin_delay;
732 arith_uint256 HASHTarget,HASHTarget_POW;
733
734 // wait for peers to connect
735 int32_t waitForPeers(const CChainParams &chainparams)
736 {
737     if (chainparams.MiningRequiresPeers())
738     {
739         do {
740             bool fvNodesEmpty;
741             {
742                 LOCK(cs_vNodes);
743                 fvNodesEmpty = vNodes.empty();
744             }
745             if (!fvNodesEmpty )
746                 break;
747             MilliSleep(1000);
748         } while (true);
749     }
750 }
751
752 #ifdef ENABLE_WALLET
753 void static BitcoinMiner_noeq(CWallet *pwallet)
754 #else
755 void static BitcoinMiner_noeq()
756 #endif
757 {
758     LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
759     RenameThread("verushash-miner");
760
761 #ifdef ENABLE_WALLET
762     // Each thread has its own key
763     CReserveKey reservekey(pwallet);
764 #endif
765
766     const CChainParams& chainparams = Params();
767     // Each thread has its own counter
768     unsigned int nExtraNonce = 0;
769     std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
770     solnPlaceholder.resize(Eh200_9.SolutionWidth);
771     uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
772
773     while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
774     {
775         sleep(1);
776         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
777             break;
778     }
779
780     // try a nice clean peer connection to start
781     waitForPeers(chainparams);
782     sleep(5);
783     CBlockIndex* curTip;
784     do {
785         curTip = chainActive.Tip();
786         printf("Verifying block height %d         \n", chainActive.Tip()->nHeight);
787         MilliSleep(1000 + rand() % 1900);
788     } while (curTip != chainActive.Tip());
789
790     SetThreadPriority(THREAD_PRIORITY_LOWEST);
791
792     sleep(5);
793     printf("Mining height %d\n", chainActive.Tip()->nHeight + 1);
794
795     miningTimer.start();
796
797     try {
798         fprintf(stderr,"Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
799         while (true)
800         {
801             miningTimer.stop();
802             waitForPeers(chainparams);
803             miningTimer.start();
804
805             // Create new block
806             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
807             CBlockIndex* pindexPrev = chainActive.Tip();
808             if ( Mining_height != pindexPrev->nHeight+1 )
809             {
810                 Mining_height = pindexPrev->nHeight+1;
811                 Mining_start = (uint32_t)time(NULL);
812             }
813
814             //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
815
816 #ifdef ENABLE_WALLET
817             CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
818 #else
819             CBlockTemplate *ptr = CreateNewBlockWithKey();
820 #endif
821             if ( ptr == 0 )
822             {
823                 static uint32_t counter;
824                 if ( counter++ < 100 )
825                     fprintf(stderr,"created illegal block, retry\n");
826                 continue;
827             }
828             unique_ptr<CBlockTemplate> pblocktemplate(ptr);
829             if (!pblocktemplate.get())
830             {
831                 if (GetArg("-mineraddress", "").empty()) {
832                     LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
833                               ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
834                 } else {
835                     // Should never reach here, because -mineraddress validity is checked in init.cpp
836                     LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
837                 }
838                 return;
839             }
840             CBlock *pblock = &pblocktemplate->block;
841             if ( ASSETCHAINS_SYMBOL[0] != 0 )
842             {
843                 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
844                 {
845                     if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
846                     {
847                         static uint32_t counter;
848                         if ( counter++ < 10 )
849                             fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
850                         sleep(10);
851                         continue;
852                     } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
853                 }
854             }
855             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
856             LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
857                        pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
858             //
859             // Search
860             //
861             uint32_t savebits; int64_t nStart = GetTime();
862
863             pblock->nSolution = solnPlaceholder;
864             savebits = pblock->nBits;
865             arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
866             arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
867
868             Mining_start = 0;
869
870             if ( pindexPrev != chainActive.Tip() )
871             {
872                 printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
873                 MilliSleep(250);
874                 continue;
875             }
876
877             while (true)
878             {
879                 // for speed check multiples at a time
880                 for (int i = 0; i < ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; i++)
881                 {
882                     solutionTargetChecks.increment();
883
884                     // Update nNonce and nTime
885                     pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
886
887                     if ( UintToArith256(pblock->GetHash()) <= hashTarget )
888                     {
889                         SetThreadPriority(THREAD_PRIORITY_NORMAL);
890
891                         int32_t unlockTime = komodo_block_unlocktime(Mining_height);
892                         int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
893
894                         LogPrintf("KomodoMiner using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
895                         LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
896                         printf("Found block %d \n", Mining_height );
897                         printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
898                         printf("  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
899                         if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
900                             printf("- timelocked until block %i\n", unlockTime);
901                         else
902                             printf("\n");
903
904 #ifdef ENABLE_WALLET
905                         ProcessBlockFound(pblock, *pwallet, reservekey);
906 #else
907                         ProcessBlockFound(pblock));
908 #endif
909                         SetThreadPriority(THREAD_PRIORITY_LOWEST);
910
911                         // In regression test mode, stop mining after a block is found.
912                         if (chainparams.MineBlocksOnDemand()) {
913                             throw boost::thread_interrupted();
914                         }
915                         break;
916                     }
917                     else
918                     {
919                         if ((UintToArith256(pblock->nNonce) & mask) == mask)
920                         {
921                             break;
922                         }
923                     }
924                 }
925
926                 // Check for stop or if block needs to be rebuilt
927                 boost::this_thread::interruption_point();
928
929                 if (vNodes.empty() && chainparams.MiningRequiresPeers())
930                 {
931                     if ( Mining_height > ASSETCHAINS_MINHEIGHT )
932                     {
933                         fprintf(stderr,"no nodes, attempting reconnect\n");
934                         break;
935                     }
936                 }
937
938                 if ((UintToArith256(pblock->nNonce) & mask) == mask)
939                 {
940                     fprintf(stderr,"%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
941                     break;
942                 }
943
944                 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
945                 {
946                     fprintf(stderr,"timeout, retrying\n");
947                     break;
948                 }
949
950                 if ( pindexPrev != chainActive.Tip() )
951                 {
952                     printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
953                     break;
954                 }
955
956                 pblock->nBits = savebits;
957                 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
958                 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
959                 {
960                     // Changing pblock->nTime can change work required on testnet:
961                     hashTarget.SetCompact(pblock->nBits);
962                 }
963             }
964         }
965     }
966     catch (const boost::thread_interrupted&)
967     {
968         miningTimer.stop();
969         LogPrintf("KomodoMiner terminated\n");
970         throw;
971     }
972     catch (const std::runtime_error &e)
973     {
974         miningTimer.stop();
975         LogPrintf("KomodoMiner runtime error: %s\n", e.what());
976         return;
977     }
978     miningTimer.stop();
979 }
980
981 #ifdef ENABLE_WALLET
982 void static BitcoinMiner(CWallet *pwallet)
983 #else
984 void static BitcoinMiner()
985 #endif
986 {
987     LogPrintf("KomodoMiner started\n");
988     SetThreadPriority(THREAD_PRIORITY_LOWEST);
989     RenameThread("komodo-miner");
990     const CChainParams& chainparams = Params();
991     
992 #ifdef ENABLE_WALLET
993     // Each thread has its own key
994     CReserveKey reservekey(pwallet);
995 #endif
996     
997     // Each thread has its own counter
998     unsigned int nExtraNonce = 0;
999     
1000     unsigned int n = chainparams.EquihashN();
1001     unsigned int k = chainparams.EquihashK();
1002     uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
1003     while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
1004     {
1005         sleep(1);
1006         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1007             break;
1008     }
1009     komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
1010     
1011     std::string solver;
1012     //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
1013     solver = "tromp";
1014     //else solver = "default";
1015     assert(solver == "tromp" || solver == "default");
1016     LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
1017     if ( ASSETCHAINS_SYMBOL[0] != 0 )
1018         fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
1019     std::mutex m_cs;
1020     bool cancelSolver = false;
1021     boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
1022                                                                        [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1023                                                                            std::lock_guard<std::mutex> lock{m_cs};
1024                                                                            cancelSolver = true;
1025                                                                        }
1026                                                                        );
1027     miningTimer.start();
1028     
1029     try {
1030         if ( ASSETCHAINS_SYMBOL[0] != 0 )
1031             fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
1032         while (true)
1033         {
1034             if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
1035             {
1036                 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
1037                 //    break;
1038                 // Busy-wait for the network to come online so we don't waste time mining
1039                 // on an obsolete chain. In regtest mode we expect to fly solo.
1040                 miningTimer.stop();
1041                 do {
1042                     bool fvNodesEmpty;
1043                     {
1044                         //LOCK(cs_vNodes);
1045                         fvNodesEmpty = vNodes.empty();
1046                     }
1047                     if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
1048                         break;
1049                     MilliSleep(5000);
1050                     //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
1051                     
1052                 } while (true);
1053                 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
1054                 miningTimer.start();
1055             }
1056             /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
1057              {
1058              fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
1059              sleep(3);
1060              }*/
1061             //
1062             // Create new block
1063             //
1064             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1065             CBlockIndex* pindexPrev = chainActive.Tip();
1066             if ( Mining_height != pindexPrev->nHeight+1 )
1067             {
1068                 Mining_height = pindexPrev->nHeight+1;
1069                 Mining_start = (uint32_t)time(NULL);
1070             }
1071             if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
1072             {
1073                 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
1074                 sleep(3);
1075             }
1076 #ifdef ENABLE_WALLET
1077             CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
1078 #else
1079             CBlockTemplate *ptr = CreateNewBlockWithKey();
1080 #endif
1081             if ( ptr == 0 )
1082             {
1083                 static uint32_t counter;
1084                 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1085                     fprintf(stderr,"created illegal block, retry\n");
1086                 sleep(1);
1087                 continue;
1088             }
1089             unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1090             if (!pblocktemplate.get())
1091             {
1092                 if (GetArg("-mineraddress", "").empty()) {
1093                     LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
1094                 } else {
1095                     // Should never reach here, because -mineraddress validity is checked in init.cpp
1096                     LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
1097                 }
1098                 return;
1099             }
1100             CBlock *pblock = &pblocktemplate->block;
1101             if ( ASSETCHAINS_SYMBOL[0] != 0 )
1102             {
1103                 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1104                 {
1105                     if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1106                     {
1107                         static uint32_t counter;
1108                         if ( counter++ < 10 )
1109                             fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1110                         sleep(10);
1111                         continue;
1112                     } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1113                 }
1114             }
1115             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1116             LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1117             //
1118             // Search
1119             //
1120             uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
1121             savebits = pblock->nBits;
1122             HASHTarget = arith_uint256().SetCompact(pblock->nBits);
1123             roundrobin_delay = ROUNDROBIN_DELAY;
1124             if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
1125             {
1126                 j = 65;
1127                 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
1128                 {
1129                     int32_t dispflag = 0;
1130                     if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
1131                         dispflag = 1;
1132                     komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
1133                     if ( nonzpkeys > 0 )
1134                     {
1135                         for (i=0; i<33; i++)
1136                             if( pubkeys[0][i] != 0 )
1137                                 break;
1138                         if ( i == 33 )
1139                             externalflag = 1;
1140                         else externalflag = 0;
1141                         if ( NOTARY_PUBKEY33[0] != 0 )
1142                         {
1143                             for (i=1; i<66; i++)
1144                                 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1145                                     break;
1146                             if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1147                                 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
1148                             for (j=gpucount=0; j<65; j++)
1149                             {
1150                                 if ( dispflag != 0 )
1151                                 {
1152                                     if ( mids[j] >= 0 )
1153                                         fprintf(stderr,"%d ",mids[j]);
1154                                     else fprintf(stderr,"GPU ");
1155                                 }
1156                                 if ( mids[j] == -1 )
1157                                     gpucount++;
1158                             }
1159                             if ( gpucount > j/2 )
1160                             {
1161                                 double delta;
1162                                 if ( notaryid < 0 )
1163                                     i = (rand() % 64);
1164                                 else i = ((Mining_height + notaryid) % 64);
1165                                 delta = sqrt((double)gpucount - j/2) / 2.;
1166                                 roundrobin_delay += ((delta * i) / 64) - delta;
1167                                 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
1168                             }
1169                             if ( dispflag != 0 )
1170                                 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);
1171                         }
1172                         for (j=0; j<65; j++)
1173                             if ( mids[j] == notaryid )
1174                                 break;
1175                         if ( j == 65 )
1176                             KOMODO_LASTMINED = 0;
1177                     } else fprintf(stderr,"no nonz pubkeys\n");
1178                     if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
1179                     {
1180                         HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
1181                         fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
1182                     } //else fprintf(stderr,"duplicate at j.%d\n",j);
1183                 } else Mining_start = 0;
1184             } else Mining_start = 0;
1185             if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
1186             {
1187                 int32_t percPoS,z;
1188                 /*if ( Mining_height <= 100 )
1189                 {
1190                     sleep(60);
1191                     continue;
1192                 }*/
1193                 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1194                 for (z=31; z>=0; z--)
1195                     fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1196                 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1197             }
1198             while (true)
1199             {
1200                 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
1201                  {
1202                  fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1203                  sleep(10);
1204                  break;
1205                  }*/
1206                 // Hash state
1207                 KOMODO_CHOSEN_ONE = 0;
1208                 
1209                 crypto_generichash_blake2b_state state;
1210                 EhInitialiseState(n, k, state);
1211                 // I = the block header minus nonce and solution.
1212                 CEquihashInput I{*pblock};
1213                 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1214                 ss << I;
1215                 // H(I||...
1216                 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
1217                 // H(I||V||...
1218                 crypto_generichash_blake2b_state curr_state;
1219                 curr_state = state;
1220                 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
1221                 // (x_1, x_2, ...) = A(I, V, n, k)
1222                 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
1223                 arith_uint256 hashTarget;
1224                 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 )
1225                     hashTarget = HASHTarget_POW;
1226                 else hashTarget = HASHTarget;
1227                 std::function<bool(std::vector<unsigned char>)> validBlock =
1228 #ifdef ENABLE_WALLET
1229                 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
1230 #else
1231                 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
1232 #endif
1233                 (std::vector<unsigned char> soln) {
1234                     int32_t z; arith_uint256 h; CBlock B;
1235                     // Write the solution to the hash and compute the result.
1236                     LogPrint("pow", "- Checking solution against target\n");
1237                     pblock->nSolution = soln;
1238                     solutionTargetChecks.increment();
1239                     B = *pblock;
1240                     h = UintToArith256(B.GetHash());
1241                     if ( h > hashTarget )
1242                         return false;
1243                     /*for (z=31; z>=16; z--)
1244                         fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1245                     fprintf(stderr," mined ");
1246                     for (z=31; z>=16; z--)
1247                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
1248                     fprintf(stderr," hashTarget ");
1249                     for (z=31; z>=16; z--)
1250                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1251                     fprintf(stderr," POW\n");*/
1252                     if ( NOTARY_PUBKEY33[0] != 0 && B.nTime > GetAdjustedTime() )
1253                     {
1254                         fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1255                         while ( GetAdjustedTime() < B.nTime-2 )
1256                         {
1257                             sleep(1);
1258                             if ( chainActive.Tip()->nHeight >= Mining_height )
1259                             {
1260                                 fprintf(stderr,"new block arrived\n");
1261                                 return(false);
1262                             }
1263                         }
1264                     }
1265                     if ( ASSETCHAINS_STAKED == 0 )
1266                     {
1267                         if ( NOTARY_PUBKEY33[0] != 0 )
1268                         {
1269                             int32_t r;
1270                             if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
1271                                 MilliSleep((rand() % (r * 1000)) + 1000);
1272                         }
1273                     }
1274                     else
1275                     {
1276                         if ( NOTARY_PUBKEY33[0] != 0 )
1277                         {
1278                             printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1279                             while ( GetAdjustedTime() < B.nTime )
1280                                 sleep(1);
1281                         }
1282                         else
1283                         {
1284                             uint256 tmp = B.GetHash();
1285                             int32_t z; for (z=31; z>=0; z--)
1286                                 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1287                             fprintf(stderr," mined block!\n");
1288                         }
1289                     }
1290                     CValidationState state;
1291                     if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
1292                     {
1293                         h = UintToArith256(B.GetHash());
1294                         for (z=31; z>=0; z--)
1295                             fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1296                         fprintf(stderr," Invalid block mined, try again\n");
1297                         return(false);
1298                     }
1299                     KOMODO_CHOSEN_ONE = 1;
1300                     // Found a solution
1301                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
1302                     LogPrintf("KomodoMiner:\n");
1303                     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
1304 #ifdef ENABLE_WALLET
1305                     if (ProcessBlockFound(&B, *pwallet, reservekey)) {
1306 #else
1307                         if (ProcessBlockFound(&B)) {
1308 #endif
1309                             // Ignore chain updates caused by us
1310                             std::lock_guard<std::mutex> lock{m_cs};
1311                             cancelSolver = false;
1312                         }
1313                         KOMODO_CHOSEN_ONE = 0;
1314                         SetThreadPriority(THREAD_PRIORITY_LOWEST);
1315                         // In regression test mode, stop mining after a block is found.
1316                         if (chainparams.MineBlocksOnDemand()) {
1317                             // Increment here because throwing skips the call below
1318                             ehSolverRuns.increment();
1319                             throw boost::thread_interrupted();
1320                         }
1321                         //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1322                         //    sleep(1800);
1323                         return true;
1324                     };
1325                     std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1326                         std::lock_guard<std::mutex> lock{m_cs};
1327                         return cancelSolver;
1328                     };
1329                     
1330                     // TODO: factor this out into a function with the same API for each solver.
1331                     if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1332                         // Create solver and initialize it.
1333                         equi eq(1);
1334                         eq.setstate(&curr_state);
1335                         
1336                         // Initialization done, start algo driver.
1337                         eq.digit0(0);
1338                         eq.xfull = eq.bfull = eq.hfull = 0;
1339                         eq.showbsizes(0);
1340                         for (u32 r = 1; r < WK; r++) {
1341                             (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1342                             eq.xfull = eq.bfull = eq.hfull = 0;
1343                             eq.showbsizes(r);
1344                         }
1345                         eq.digitK(0);
1346                         ehSolverRuns.increment();
1347                         
1348                         // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1349                         for (size_t s = 0; s < eq.nsols; s++) {
1350                             LogPrint("pow", "Checking solution %d\n", s+1);
1351                             std::vector<eh_index> index_vector(PROOFSIZE);
1352                             for (size_t i = 0; i < PROOFSIZE; i++) {
1353                                 index_vector[i] = eq.sols[s][i];
1354                             }
1355                             std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1356                             
1357                             if (validBlock(sol_char)) {
1358                                 // If we find a POW solution, do not try other solutions
1359                                 // because they become invalid as we created a new block in blockchain.
1360                                 break;
1361                             }
1362                         }
1363                     } else {
1364                         try {
1365                             // If we find a valid block, we rebuild
1366                             bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1367                             ehSolverRuns.increment();
1368                             if (found) {
1369                                 int32_t i; uint256 hash = pblock->GetHash();
1370                                 for (i=0; i<32; i++)
1371                                     fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1372                                 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1373                                 FOUND_BLOCK = 1;
1374                                 KOMODO_MAYBEMINED = Mining_height;
1375                                 break;
1376                             }
1377                         } catch (EhSolverCancelledException&) {
1378                             LogPrint("pow", "Equihash solver cancelled\n");
1379                             std::lock_guard<std::mutex> lock{m_cs};
1380                             cancelSolver = false;
1381                         }
1382                     }
1383                     
1384                     // Check for stop or if block needs to be rebuilt
1385                     boost::this_thread::interruption_point();
1386                     // Regtest mode doesn't require peers
1387                     if ( FOUND_BLOCK != 0 )
1388                     {
1389                         FOUND_BLOCK = 0;
1390                         fprintf(stderr,"FOUND_BLOCK!\n");
1391                         //sleep(2000);
1392                     }
1393                     if (vNodes.empty() && chainparams.MiningRequiresPeers())
1394                     {
1395                         if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1396                         {
1397                             fprintf(stderr,"no nodes, break\n");
1398                             break;
1399                         }
1400                     }
1401                     if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1402                     {
1403                         //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1404                         fprintf(stderr,"0xffff, break\n");
1405                         break;
1406                     }
1407                     if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1408                     {
1409                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1410                             fprintf(stderr,"timeout, break\n");
1411                         break;
1412                     }
1413                     if ( pindexPrev != chainActive.Tip() )
1414                     {
1415                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1416                             fprintf(stderr,"Tip advanced, break\n");
1417                         break;
1418                     }
1419                     // Update nNonce and nTime
1420                     pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1421                     pblock->nBits = savebits;
1422                     /*if ( NOTARY_PUBKEY33[0] == 0 )
1423                     {
1424                         int32_t percPoS;
1425                         UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1426                         if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1427                         {
1428                             // Changing pblock->nTime can change work required on testnet:
1429                             HASHTarget.SetCompact(pblock->nBits);
1430                             HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1431                         }
1432                     }*/
1433                 }
1434             }
1435         }
1436         catch (const boost::thread_interrupted&)
1437         {
1438             miningTimer.stop();
1439             c.disconnect();
1440             LogPrintf("KomodoMiner terminated\n");
1441             throw;
1442         }
1443         catch (const std::runtime_error &e)
1444         {
1445             miningTimer.stop();
1446             c.disconnect();
1447             LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1448             return;
1449         }
1450         miningTimer.stop();
1451         c.disconnect();
1452     }
1453     
1454 #ifdef ENABLE_WALLET
1455     void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1456 #else
1457     void GenerateBitcoins(bool fGenerate, int nThreads)
1458 #endif
1459     {
1460         static boost::thread_group* minerThreads = NULL;
1461         
1462         if (nThreads < 0)
1463             nThreads = GetNumCores();
1464         
1465         if (minerThreads != NULL)
1466         {
1467             minerThreads->interrupt_all();
1468             delete minerThreads;
1469             minerThreads = NULL;
1470         }
1471         
1472         if (nThreads == 0 || !fGenerate)
1473             return;
1474         
1475         minerThreads = new boost::thread_group();
1476         for (int i = 0; i < nThreads; i++) {
1477 #ifdef ENABLE_WALLET
1478         if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1479             minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1480         else
1481             minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
1482 #else
1483         if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1484             minerThreads->create_thread(&BitcoinMiner);
1485         else
1486             minerThreads->create_thread(&BitcoinMiner_noeq);
1487 #endif
1488         }
1489     }
1490     
1491 #endif // ENABLE_MINING
This page took 0.109515 seconds and 4 git commands to generate.