]> Git Repo - VerusCoin.git/blob - src/miner.cpp
Integrate latest Zcash fixes and update for non-latin user names
[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 "chainparams.h"
13 #include "cc/StakeGuard.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 #include "crypto/verus_hash.h"
21 #endif
22 #include "hash.h"
23 #include "key_io.h"
24 #include "main.h"
25 #include "metrics.h"
26 #include "net.h"
27 #include "pow.h"
28 #include "primitives/transaction.h"
29 #include "random.h"
30 #include "timedata.h"
31 #include "ui_interface.h"
32 #include "util.h"
33 #include "utilmoneystr.h"
34 #ifdef ENABLE_WALLET
35 #include "wallet/wallet.h"
36 #endif
37
38 #include "zcash/Address.hpp"
39 #include "transaction_builder.h"
40
41 #include "sodium.h"
42
43 #include <boost/thread.hpp>
44 #include <boost/tuple/tuple.hpp>
45 #ifdef ENABLE_MINING
46 #include <functional>
47 #endif
48 #include <mutex>
49
50 using namespace std;
51
52 //////////////////////////////////////////////////////////////////////////////
53 //
54 // BitcoinMiner
55 //
56
57 //
58 // Unconfirmed transactions in the memory pool often depend on other
59 // transactions in the memory pool. When we select transactions from the
60 // pool, we select by highest priority or fee rate, so we might consider
61 // transactions that depend on transactions that aren't yet in the block.
62 // The COrphan class keeps track of these 'temporary orphans' while
63 // CreateBlock is figuring out which transactions to include.
64 //
65 class COrphan
66 {
67 public:
68     const CTransaction* ptx;
69     set<uint256> setDependsOn;
70     CFeeRate feeRate;
71     double dPriority;
72     
73     COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
74     {
75     }
76 };
77
78 uint64_t nLastBlockTx = 0;
79 uint64_t nLastBlockSize = 0;
80
81 // We want to sort transactions by priority and fee rate, so:
82 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
83 class TxPriorityCompare
84 {
85     bool byFee;
86     
87 public:
88     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
89     
90     bool operator()(const TxPriority& a, const TxPriority& b)
91     {
92         if (byFee)
93         {
94             if (a.get<1>() == b.get<1>())
95                 return a.get<0>() < b.get<0>();
96             return a.get<1>() < b.get<1>();
97         }
98         else
99         {
100             if (a.get<0>() == b.get<0>())
101                 return a.get<1>() < b.get<1>();
102             return a.get<0>() < b.get<0>();
103         }
104     }
105 };
106
107 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
108 {
109     pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
110
111     // Updating time can change work required on testnet:
112     if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {
113         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
114     }
115 }
116
117 #include "komodo_defs.h"
118
119 extern CCriticalSection cs_metrics;
120 extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
121 extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
122 extern bool VERUS_MINTBLOCKS;
123 extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
124 extern const char *ASSETCHAINS_ALGORITHMS[];
125 extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
126 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
127 extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
128 void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
129
130 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
131 uint32_t Mining_start,Mining_height;
132 int32_t My_notaryid = -1;
133 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
134 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
135 int32_t komodo_baseid(char *origbase);
136 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
137 int64_t komodo_block_unlocktime(uint32_t nHeight);
138 uint64_t komodo_commission(const CBlock *block);
139 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);
140 int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk);
141 int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
142
143 CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
144 {
145     CScript scriptPubKeyIn(_scriptPubKeyIn);
146
147     CPubKey pk = CPubKey();
148     std::vector<std::vector<unsigned char>> vAddrs;
149     txnouttype txT;
150     if (Solver(scriptPubKeyIn, txT, vAddrs))
151     {
152         if (txT == TX_PUBKEY)
153             pk = CPubKey(vAddrs[0]);
154     }
155
156     uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
157     //fprintf(stderr,"create new block\n");
158     // Create new block
159     if ( gpucount < 0 )
160         gpucount = KOMODO_MAXGPUCOUNT;
161     std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
162     if(!pblocktemplate.get())
163     {
164         fprintf(stderr,"pblocktemplate.get() failure\n");
165         return NULL;
166     }
167     CBlock *pblock = &pblocktemplate->block; // pointer for convenience
168      // -regtest only: allow overriding block.nVersion with
169     // -blockversion=N to test forking scenarios
170     if (Params().MineBlocksOnDemand())
171         pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
172     
173     // Add dummy coinbase tx as first transaction
174     pblock->vtx.push_back(CTransaction());
175     pblocktemplate->vTxFees.push_back(-1); // updated at end
176     pblocktemplate->vTxSigOps.push_back(-1); // updated at end
177     
178     // Largest block you're willing to create:
179     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
180     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
181     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
182     
183     // How much of the block should be dedicated to high-priority transactions,
184     // included regardless of the fees they pay
185     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
186     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
187     
188     // Minimum block size you want to create; block will be filled with free transactions
189     // until there are no more or the block reaches this size:
190     unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
191     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
192     
193     // Collect memory pool transactions into the block
194     CAmount nFees = 0;
195
196     // we will attempt to spend any cheats we see
197     CTransaction cheatTx;
198     boost::optional<CTransaction> cheatSpend;
199     uint256 cbHash;
200
201     CBlockIndex* pindexPrev = 0;
202     {
203         LOCK2(cs_main, mempool.cs);
204         pindexPrev = chainActive.LastTip();
205         const int nHeight = pindexPrev->GetHeight() + 1;
206         const Consensus::Params &consensusParams = chainparams.GetConsensus();
207         uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams);
208         bool sapling = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING);
209
210         const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
211         uint32_t proposedTime = GetAdjustedTime();
212         if (proposedTime == nMedianTimePast)
213         {
214             // too fast or stuck, this addresses the too fast issue, while moving
215             // forward as quickly as possible
216             for (int i; i < 100; i++)
217             {
218                 proposedTime = GetAdjustedTime();
219                 if (proposedTime == nMedianTimePast)
220                     MilliSleep(10);
221             }
222         }
223         pblock->nTime = GetAdjustedTime();
224
225         CCoinsViewCache view(pcoinsTip);
226         uint32_t expired; uint64_t commission;
227         
228         SaplingMerkleTree sapling_tree;
229         assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
230
231         // Priority order to process transactions
232         list<COrphan> vOrphan; // list memory doesn't move
233         map<uint256, vector<COrphan*> > mapDependers;
234         bool fPrintPriority = GetBoolArg("-printpriority", false);
235         
236         // This vector will be sorted into a priority queue:
237         vector<TxPriority> vecPriority;
238         vecPriority.reserve(mempool.mapTx.size() + 1);
239
240         // check if we should add cheat transaction
241         CBlockIndex *ppast;
242         CTransaction cb;
243         int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;
244         if (cheatCatcher &&
245             sapling && chainActive.Height() > 100 && 
246             (ppast = chainActive[cheatHeight]) && 
247             ppast->IsVerusPOSBlock() && 
248             cheatList.IsHeightOrGreaterInList(cheatHeight))
249         {
250             // get the block and see if there is a cheat candidate for the stake tx
251             CBlock b;
252             if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, 1))
253             {
254                 CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];
255
256                 if (cheatList.IsCheatInList(stakeTx, &cheatTx))
257                 {
258                     // make and sign the cheat transaction to spend the coinbase to our address
259                     CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
260
261                     uint32_t voutNum;
262                     // get the first vout with value
263                     for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)
264                     {
265                         if (b.vtx[0].vout[voutNum].nValue > 0)
266                             break;
267                     }
268
269                     // send to the same pub key as the destination of this block reward
270                     if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))
271                     {
272                         extern CWallet *pwalletMain;
273                         LOCK(pwalletMain->cs_wallet);
274                         TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);
275                         cb = b.vtx[0];
276                         cbHash = cb.GetHash();
277
278                         bool hasInput = false;
279                         for (uint32_t i = 0; i < cb.vout.size(); i++)
280                         {
281                             // add the spends with the cheat
282                             if (cb.vout[i].nValue > 0)
283                             {
284                                 tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);
285                                 hasInput = true;
286                             }
287                         }
288
289                         if (hasInput)
290                         {
291                             // this is a send from a t-address to a sapling address, which we don't have an ovk for. 
292                             // Instead, generate a common one from the HD seed. This ensures the data is
293                             // recoverable, at least for us, while keeping it logically separate from the ZIP 32
294                             // Sapling key hierarchy, which the user might not be using.
295                             uint256 ovk;
296                             HDSeed seed;
297                             if (pwalletMain->GetHDSeed(seed)) {
298                                 ovk = ovkForShieldingFromTaddr(seed);
299
300                                 // send everything to Sapling address
301                                 tb.SendChangeTo(cheatCatcher.value(), ovk);
302
303                                 tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);
304
305                                 cheatSpend = tb.Build();
306                             }
307                         }
308                     }
309                 }
310             }
311         }
312
313         if (cheatSpend)
314         {
315             std::list<CTransaction> removed;
316             mempool.removeConflicts(cheatTx, removed);
317             printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n",
318                 (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str());
319
320             // add to mem pool and relay
321             if (myAddtomempool(cheatTx))
322             {
323                 RelayTransaction(cheatTx);
324             }
325         }
326
327         // now add transactions from the mem pool
328         for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
329              mi != mempool.mapTx.end(); ++mi)
330         {
331             const CTransaction& tx = mi->GetTx();
332             
333             int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
334             ? nMedianTimePast
335             : pblock->GetBlockTime();
336
337             if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
338             {
339                 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
340                 continue;
341             }
342
343             if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
344             {
345                 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
346                 continue;
347             }
348
349             COrphan* porphan = NULL;
350             double dPriority = 0;
351             CAmount nTotalIn = 0;
352             bool fMissingInputs = false;
353             if (tx.IsCoinImport())
354             {
355                 CAmount nValueIn = GetCoinImportValue(tx);
356                 nTotalIn += nValueIn;
357                 dPriority += (double)nValueIn * 1000;  // flat multiplier
358             } else {
359                 BOOST_FOREACH(const CTxIn& txin, tx.vin)
360                 {
361                     // Read prev transaction
362                     if (!view.HaveCoins(txin.prevout.hash))
363                     {
364                         // This should never happen; all transactions in the memory
365                         // pool should connect to either transactions in the chain
366                         // or other transactions in the memory pool.
367                         if (!mempool.mapTx.count(txin.prevout.hash))
368                         {
369                             LogPrintf("ERROR: mempool transaction missing input\n");
370                             if (fDebug) assert("mempool transaction missing input" == 0);
371                             fMissingInputs = true;
372                             if (porphan)
373                                 vOrphan.pop_back();
374                             break;
375                         }
376
377                         // Has to wait for dependencies
378                         if (!porphan)
379                         {
380                             // Use list for automatic deletion
381                             vOrphan.push_back(COrphan(&tx));
382                             porphan = &vOrphan.back();
383                         }
384                         mapDependers[txin.prevout.hash].push_back(porphan);
385                         porphan->setDependsOn.insert(txin.prevout.hash);
386                         nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
387                         continue;
388                     }
389                     const CCoins* coins = view.AccessCoins(txin.prevout.hash);
390                     assert(coins);
391
392                     CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
393                     nTotalIn += nValueIn;
394
395                     int nConf = nHeight - coins->nHeight;
396
397                     dPriority += (double)nValueIn * nConf;
398                 }
399                 nTotalIn += tx.GetShieldedValueIn();
400             }
401
402             if (fMissingInputs) continue;
403             
404             // Priority is sum(valuein * age) / modified_txsize
405             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
406             dPriority = tx.ComputePriority(dPriority, nTxSize);
407             
408             uint256 hash = tx.GetHash();
409             mempool.ApplyDeltas(hash, dPriority, nTotalIn);
410             
411             CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
412             
413             if (porphan)
414             {
415                 porphan->dPriority = dPriority;
416                 porphan->feeRate = feeRate;
417             }
418             else
419                 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
420         }
421
422         // Collect transactions into block
423         uint64_t nBlockSize = 1000;
424         uint64_t nBlockTx = 0;
425         int64_t interest;
426         int nBlockSigOps = 100;
427         bool fSortedByFee = (nBlockPrioritySize <= 0);
428         
429         TxPriorityCompare comparer(fSortedByFee);
430         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
431         
432         while (!vecPriority.empty())
433         {
434             // Take highest priority transaction off the priority queue:
435             double dPriority = vecPriority.front().get<0>();
436             CFeeRate feeRate = vecPriority.front().get<1>();
437             const CTransaction& tx = *(vecPriority.front().get<2>());
438             
439             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
440             vecPriority.pop_back();
441             
442             // Size limits
443             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
444             if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
445             {
446                 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
447                 continue;
448             }
449             
450             // Legacy limits on sigOps:
451             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
452             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
453             {
454                 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
455                 continue;
456             }
457             // Skip free transactions if we're past the minimum block size:
458             const uint256& hash = tx.GetHash();
459             double dPriorityDelta = 0;
460             CAmount nFeeDelta = 0;
461             mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
462             if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
463             {
464                 //fprintf(stderr,"fee rate skip\n");
465                 continue;
466             }
467             // Prioritise by fee once past the priority size or we run out of high-priority
468             // transactions:
469             if (!fSortedByFee &&
470                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
471             {
472                 fSortedByFee = true;
473                 comparer = TxPriorityCompare(fSortedByFee);
474                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
475             }
476             
477             if (!view.HaveInputs(tx))
478             {
479                 //fprintf(stderr,"dont have inputs\n");
480                 continue;
481             }
482             CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();
483             
484             nTxSigOps += GetP2SHSigOpCount(tx, view);
485             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
486             {
487                 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
488                 continue;
489             }
490             // Note that flags: we don't want to set mempool/IsStandard()
491             // policy here, but we still have to ensure that the block we
492             // create only contains transactions that are valid in new blocks.
493             CValidationState state;
494             PrecomputedTransactionData txdata(tx);
495             if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
496             {
497                 //fprintf(stderr,"context failure\n");
498                 continue;
499             }
500             UpdateCoins(tx, view, nHeight);
501
502             BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
503                 sapling_tree.append(outDescription.cm);
504             }
505
506             // Added
507             pblock->vtx.push_back(tx);
508             pblocktemplate->vTxFees.push_back(nTxFees);
509             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
510             nBlockSize += nTxSize;
511             ++nBlockTx;
512             nBlockSigOps += nTxSigOps;
513             nFees += nTxFees;
514             
515             if (fPrintPriority)
516             {
517                 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
518             }
519             
520             // Add transactions that depend on this one to the priority queue
521             if (mapDependers.count(hash))
522             {
523                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
524                 {
525                     if (!porphan->setDependsOn.empty())
526                     {
527                         porphan->setDependsOn.erase(hash);
528                         if (porphan->setDependsOn.empty())
529                         {
530                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
531                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
532                         }
533                     }
534                 }
535             }
536         }
537         
538         nLastBlockTx = nBlockTx;
539         nLastBlockSize = nBlockSize;
540         blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
541         //pblock->nTime = blocktime + 1;
542         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
543
544         int32_t stakeHeight = chainActive.Height() + 1;
545
546         //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
547         if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
548         {
549             uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
550             CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), stakeHeight);
551
552             //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
553             //    blocktime = pindexPrev->GetMedianTimePast() + 60;
554             if (ASSETCHAINS_LWMAPOS != 0)
555             {
556                 uint32_t nBitsPOS;
557                 arith_uint256 posHash;
558
559                 siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);
560                 blocktime = GetAdjustedTime();
561
562                 // change the scriptPubKeyIn to the same output script exactly as the staking transaction
563                 if (siglen > 0)
564                     scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
565             }
566             else
567             {
568                 siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
569             }
570
571             if ( siglen > 0 )
572             {
573                 CAmount txfees;
574
575                 // after Sapling, stake transactions have a fee, but it is recovered in the reward
576                 // this ensures that a rebroadcast goes through quickly to begin staking again
577                 txfees = sapling ? DEFAULT_STAKE_TXFEE : 0;
578
579                 pblock->vtx.push_back(txStaked);
580                 pblocktemplate->vTxFees.push_back(txfees);
581                 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
582                 nFees += txfees;
583                 pblock->nTime = blocktime;
584                 //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->GetHeight()+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13)));
585             } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
586         }
587         
588         // Create coinbase tx
589         CMutableTransaction txNew = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
590         txNew.vin.resize(1);
591         txNew.vin[0].prevout.SetNull();
592         txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
593
594         txNew.vout.resize(1);
595         txNew.vout[0].scriptPubKey = scriptPubKeyIn;
596         txNew.vout[0].nValue = GetBlockSubsidy(nHeight,consensusParams) + nFees;
597
598         // once we get to Sapling, enable CC StakeGuard for stake transactions
599         if (isStake && sapling)
600         {
601             // if there is a specific destination, use it
602             CTransaction stakeTx = pblock->vtx[pblock->vtx.size() - 1];
603             CStakeParams p;
604             if (ValidateStakeTransaction(stakeTx, p, false))
605             {
606                 if (!p.pk.IsValid() || !MakeGuardedOutput(txNew.vout[0].nValue, p.pk, stakeTx, txNew.vout[0]))
607                 {
608                     fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
609                     return 0;
610                 }
611             }
612             else
613             {
614                 fprintf(stderr,"CreateNewBlock: invalid stake transaction\n");
615                 return 0;
616             }
617         }
618
619         txNew.nExpiryHeight = 0;
620         txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
621
622         if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
623             txNew.vout[0].nValue += 5000;
624
625         // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
626         // to transaction if so, cast for GTE operator
627         if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
628         {
629             int32_t opretlen, p2shlen, scriptlen;
630             CScriptExt opretScript = CScriptExt();
631
632             txNew.vout.resize(2);
633
634             // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
635             // protected only by the time lock rather than 100% inaccessible
636             opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
637             if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition())
638             {
639                 fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
640                 return 0;
641             }
642             
643             opretScript += scriptPubKeyIn;
644
645             txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
646             txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
647             txNew.vout[1].nValue = 0;
648         } // timelocks and commissions are currently incompatible due to validation complexity of the combination
649         else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
650         {
651             int32_t i; uint8_t *ptr;
652             txNew.vout.resize(2);
653             txNew.vout[1].nValue = commission;
654             txNew.vout[1].scriptPubKey.resize(35);
655             ptr = (uint8_t *)&txNew.vout[1].scriptPubKey[0];
656             ptr[0] = 33;
657             for (i=0; i<33; i++)
658                 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
659             ptr[34] = OP_CHECKSIG;
660             //printf("autocreate commision vout\n");
661         }
662
663         pblock->vtx[0] = txNew;
664         pblocktemplate->vTxFees[0] = -nFees;
665
666         // if not Verus stake, setup nonce, otherwise, leave it alone
667         if (!isStake || ASSETCHAINS_LWMAPOS == 0)
668         {
669             // Randomise nonce
670             arith_uint256 nonce = UintToArith256(GetRandHash());
671
672             // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
673             nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
674             nonce >>= 16;
675             pblock->nNonce = ArithToUint256(nonce);
676         }
677         
678         // Fill in header
679         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
680         pblock->hashFinalSaplingRoot   = sapling_tree.root();
681
682         // all Verus PoS chains need this data in the block at all times
683         if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )
684         {
685             UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
686             pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
687         }
688         pblock->nSolution.clear();
689         pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
690         if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
691         {
692             uint32_t r;
693             CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
694             if ( pblock->nTime < pindexPrev->nTime+60 )
695                 pblock->nTime = pindexPrev->nTime + 60;
696             if ( gpucount < 33 )
697             {
698                 uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
699                 memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
700                 memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
701                 memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
702                 vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
703                 memcpy(&r,&randvals,sizeof(r));
704                 pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
705             }
706             if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
707             {
708                 CAmount txfees = 5000;
709                 pblock->vtx.push_back(txNotary);
710                 pblocktemplate->vTxFees.push_back(txfees);
711                 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
712                 nFees += txfees;
713                 pblocktemplate->vTxFees[0] = -nFees;
714                 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
715                 //fprintf(stderr,"added notaryvin\n");
716             }
717             else
718             {
719                 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
720                 return(0);
721             }
722         }
723         else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
724         {
725             CValidationState state;
726             //fprintf(stderr,"check validity\n");
727             if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
728             {
729                 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
730             }
731             //fprintf(stderr,"valid\n");
732         }
733     }
734     //fprintf(stderr,"done new block\n");
735     return pblocktemplate.release();
736 }
737  
738 /*
739  #ifdef ENABLE_WALLET
740  boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
741  #else
742  boost::optional<CScript> GetMinerScriptPubKey()
743  #endif
744  {
745  CKeyID keyID;
746  CBitcoinAddress addr;
747  if (addr.SetString(GetArg("-mineraddress", ""))) {
748  addr.GetKeyID(keyID);
749  } else {
750  #ifdef ENABLE_WALLET
751  CPubKey pubkey;
752  if (!reservekey.GetReservedKey(pubkey)) {
753  return boost::optional<CScript>();
754  }
755  keyID = pubkey.GetID();
756  #else
757  return boost::optional<CScript>();
758  #endif
759  }
760  
761  CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
762  return scriptPubKey;
763  }
764  
765  #ifdef ENABLE_WALLET
766  CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
767  {
768  boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
769  #else
770  CBlockTemplate* CreateNewBlockWithKey()
771  {
772  boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
773  #endif
774  
775  if (!scriptPubKey) {
776  return NULL;
777  }
778  return CreateNewBlock(*scriptPubKey);
779  }*/
780
781 //////////////////////////////////////////////////////////////////////////////
782 //
783 // Internal miner
784 //
785
786 #ifdef ENABLE_MINING
787
788 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
789 {
790     // Update nExtraNonce
791     static uint256 hashPrevBlock;
792     if (hashPrevBlock != pblock->hashPrevBlock)
793     {
794         nExtraNonce = 0;
795         hashPrevBlock = pblock->hashPrevBlock;
796     }
797     ++nExtraNonce;
798     unsigned int nHeight = pindexPrev->GetHeight()+1; // Height first in coinbase required for block.version=2
799     CMutableTransaction txCoinbase(pblock->vtx[0]);
800     txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
801     assert(txCoinbase.vin[0].scriptSig.size() <= 100);
802     
803     pblock->vtx[0] = txCoinbase;
804     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
805 }
806
807 #ifdef ENABLE_WALLET
808 //////////////////////////////////////////////////////////////////////////////
809 //
810 // Internal miner
811 //
812
813 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
814 {
815     CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;
816     if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
817     {
818         scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
819     }
820     else if ( USE_EXTERNAL_PUBKEY != 0 )
821     {
822         //fprintf(stderr,"use notary pubkey\n");
823         scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
824     }
825     else
826     {
827         if (!reservekey.GetReservedKey(pubkey))
828         {
829             return NULL;
830         }
831         scriptPubKey.resize(35);
832         ptr = (uint8_t *)pubkey.begin();
833         scriptPubKey[0] = 33;
834         for (i=0; i<33; i++)
835             scriptPubKey[i+1] = ptr[i];
836         scriptPubKey[34] = OP_CHECKSIG;
837         //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
838     }
839     return CreateNewBlock(scriptPubKey, gpucount, isStake);
840 }
841
842 void komodo_broadcast(CBlock *pblock,int32_t limit)
843 {
844     int32_t n = 1;
845     //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
846     {
847         LOCK(cs_vNodes);
848         BOOST_FOREACH(CNode* pnode, vNodes)
849         {
850             if ( pnode->hSocket == INVALID_SOCKET )
851                 continue;
852             if ( (rand() % n) == 0 )
853             {
854                 pnode->PushMessage("block", *pblock);
855                 if ( n++ > limit )
856                     break;
857             }
858         }
859     }
860     //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
861 }
862
863 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
864 #else
865 static bool ProcessBlockFound(CBlock* pblock)
866 #endif // ENABLE_WALLET
867 {
868     LogPrintf("%s\n", pblock->ToString());
869     LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1);
870     
871     // Found a solution
872     {
873         if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
874         {
875             uint256 hash; int32_t i;
876             hash = pblock->hashPrevBlock;
877             for (i=31; i>=0; i--)
878                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
879             fprintf(stderr," <- prev (stale)\n");
880             hash = chainActive.LastTip()->GetBlockHash();
881             for (i=31; i>=0; i--)
882                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
883             fprintf(stderr," <- chainTip (stale)\n");
884             
885             return error("KomodoMiner: generated block is stale");
886         }
887     }
888     
889 #ifdef ENABLE_WALLET
890     // Remove key from key pool
891     if ( IS_KOMODO_NOTARY == 0 )
892     {
893         if (GetArg("-mineraddress", "").empty()) {
894             // Remove key from key pool
895             reservekey.KeepKey();
896         }
897     }
898     // Track how many getdata requests this block gets
899     //if ( 0 )
900     {
901         //fprintf(stderr,"lock cs_wallet\n");
902         LOCK(wallet.cs_wallet);
903         wallet.mapRequestCount[pblock->GetHash()] = 0;
904     }
905 #endif
906     //fprintf(stderr,"process new block\n");
907
908     // Process this block the same as if we had received it from another node
909     CValidationState state;
910     if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL))
911         return error("KomodoMiner: ProcessNewBlock, block not accepted");
912     
913     TrackMinedBlock(pblock->GetHash());
914     komodo_broadcast(pblock,16);
915     return true;
916 }
917
918 int32_t komodo_baseid(char *origbase);
919 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
920 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
921 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
922 extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;
923 int32_t roundrobin_delay;
924 arith_uint256 HASHTarget,HASHTarget_POW;
925
926 // wait for peers to connect
927 int32_t waitForPeers(const CChainParams &chainparams)
928 {
929     if (chainparams.MiningRequiresPeers())
930     {
931         bool fvNodesEmpty;
932         {
933             boost::this_thread::interruption_point();
934             LOCK(cs_vNodes);
935             fvNodesEmpty = vNodes.empty();
936         }
937         if (fvNodesEmpty || IsNotInSync())
938         {
939             int loops = 0, blockDiff = 0, newDiff = 0;
940             
941             do {
942                 if (fvNodesEmpty)
943                 {
944                     MilliSleep(1000 + rand() % 4000);
945                     boost::this_thread::interruption_point();
946                     LOCK(cs_vNodes);
947                     fvNodesEmpty = vNodes.empty();
948                     loops = 0;
949                     blockDiff = 0;
950                 }
951                 if ((newDiff = IsNotInSync()) > 1)
952                 {
953                     if (blockDiff != newDiff)
954                     {
955                         blockDiff = newDiff;
956                     }
957                     else
958                     {
959                         if (++loops <= 10)
960                         {
961                             MilliSleep(1000);
962                         }
963                         else break;
964                     }
965                 }
966             } while (fvNodesEmpty || IsNotInSync());
967             MilliSleep(100 + rand() % 400);
968         }
969     }
970 }
971
972 #ifdef ENABLE_WALLET
973 CBlockIndex *get_chainactive(int32_t height)
974 {
975     if ( chainActive.LastTip() != 0 )
976     {
977         if ( height <= chainActive.LastTip()->GetHeight() )
978         {
979             LOCK(cs_main);
980             return(chainActive[height]);
981         }
982         // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight());
983     }
984     //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height);
985     return(0);
986 }
987
988 /*
989  * A separate thread to stake, while the miner threads mine.
990  */
991 void static VerusStaker(CWallet *pwallet)
992 {
993     LogPrintf("Verus staker thread started\n");
994     RenameThread("verus-staker");
995
996     const CChainParams& chainparams = Params();
997     auto consensusParams = chainparams.GetConsensus();
998
999     // Each thread has its own key
1000     CReserveKey reservekey(pwallet);
1001
1002     // Each thread has its own counter
1003     unsigned int nExtraNonce = 0;
1004     std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
1005     solnPlaceholder.resize(Eh200_9.SolutionWidth);
1006     uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1007
1008     while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
1009     {
1010         sleep(1);
1011         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1012             break;
1013     }
1014
1015     // try a nice clean peer connection to start
1016     CBlockIndex *pindexPrev, *pindexCur;
1017     do {
1018         pindexPrev = chainActive.LastTip();
1019         MilliSleep(5000 + rand() % 5000);
1020         waitForPeers(chainparams);
1021         pindexCur = chainActive.LastTip();
1022     } while (pindexPrev != pindexCur);
1023
1024     try {
1025         while (true)
1026         {
1027             waitForPeers(chainparams);
1028             CBlockIndex* pindexPrev = chainActive.LastTip();
1029             printf("Staking height %d for %s\n", pindexPrev->GetHeight() + 1, ASSETCHAINS_SYMBOL);
1030
1031             // Create new block
1032             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1033             if ( Mining_height != pindexPrev->GetHeight()+1 )
1034             {
1035                 Mining_height = pindexPrev->GetHeight()+1;
1036                 Mining_start = (uint32_t)time(NULL);
1037             }
1038
1039             // Check for stop or if block needs to be rebuilt
1040             boost::this_thread::interruption_point();
1041
1042             // try to stake a block
1043             CBlockTemplate *ptr = NULL;
1044             if (Mining_height > VERUS_MIN_STAKEAGE)
1045                 ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true);
1046
1047             if ( ptr == 0 )
1048             {
1049                 // wait to try another staking block until after the tip moves again
1050                 while ( chainActive.LastTip() == pindexPrev )
1051                     sleep(1);
1052                 continue;
1053             }
1054
1055             unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1056             if (!pblocktemplate.get())
1057             {
1058                 if (GetArg("-mineraddress", "").empty()) {
1059                     LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1060                               ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1061                 } else {
1062                     // Should never reach here, because -mineraddress validity is checked in init.cpp
1063                     LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
1064                 }
1065                 return;
1066             }
1067
1068             CBlock *pblock = &pblocktemplate->block;
1069             LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1070             //
1071             // Search
1072             //
1073             int64_t nStart = GetTime();
1074
1075             // take up the necessary space for alignment
1076             pblock->nSolution = solnPlaceholder;
1077
1078             // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree
1079             unsigned int nExtraNonce = 0;
1080             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1081
1082             if (vNodes.empty() && chainparams.MiningRequiresPeers())
1083             {
1084                 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1085                 {
1086                     fprintf(stderr,"no nodes, attempting reconnect\n");
1087                     continue;
1088                 }
1089             }
1090
1091             if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1092             {
1093                 fprintf(stderr,"timeout, retrying\n");
1094                 continue;
1095             }
1096
1097             if ( pindexPrev != chainActive.LastTip() )
1098             {
1099                 printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight());
1100                 MilliSleep(250);
1101                 continue;
1102             }
1103
1104             int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1105             int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1106
1107             uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
1108
1109             pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
1110
1111             UpdateTime(pblock, consensusParams, pindexPrev);
1112
1113             ProcessBlockFound(pblock, *pwallet, reservekey);
1114
1115             LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1116             LogPrintf("Staked block found  \n  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1117             printf("Found block %d \n", Mining_height );
1118             printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
1119             arith_uint256 post;
1120             post.SetCompact(pblock->GetVerusPOSTarget());
1121             pindexPrev = get_chainactive(Mining_height - 100);
1122             CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1];
1123             printf("POS hash: %s  \ntarget:   %s\n", 
1124                 CTransaction::_GetVerusPOSHash(&(pblock->nNonce), sTx.vin[0].prevout.hash, sTx.vin[0].prevout.n, Mining_height, pindexPrev->GetBlockHeader().GetVerusEntropyHash(Mining_height - 100), sTx.vout[0].nValue).GetHex().c_str(), ArithToUint256(post).GetHex().c_str());
1125             if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1126                 printf("- timelocked until block %i\n", unlockTime);
1127             else
1128                 printf("\n");
1129
1130             // Check for stop or if block needs to be rebuilt
1131             boost::this_thread::interruption_point();
1132
1133             sleep(3);
1134
1135             // In regression test mode, stop mining after a block is found.
1136             if (chainparams.MineBlocksOnDemand()) {
1137                 throw boost::thread_interrupted();
1138             }
1139         }
1140     }
1141     catch (const boost::thread_interrupted&)
1142     {
1143         LogPrintf("VerusStaker terminated\n");
1144         throw;
1145     }
1146     catch (const std::runtime_error &e)
1147     {
1148         LogPrintf("VerusStaker runtime error: %s\n", e.what());
1149         return;
1150     }
1151 }
1152
1153 void static BitcoinMiner_noeq(CWallet *pwallet)
1154 #else
1155 void static BitcoinMiner_noeq()
1156 #endif
1157 {
1158     LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1159     RenameThread("verushash-miner");
1160
1161 #ifdef ENABLE_WALLET
1162     // Each thread has its own key
1163     CReserveKey reservekey(pwallet);
1164 #endif
1165
1166     const CChainParams& chainparams = Params();
1167     // Each thread has its own counter
1168     unsigned int nExtraNonce = 0;
1169     std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
1170     solnPlaceholder.resize(Eh200_9.SolutionWidth);
1171     uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1172
1173     while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
1174     {
1175         sleep(1);
1176         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1177             break;
1178     }
1179
1180     SetThreadPriority(THREAD_PRIORITY_LOWEST);
1181
1182     // try a nice clean peer connection to start
1183     CBlockIndex *pindexPrev, *pindexCur;
1184     do {
1185         pindexPrev = chainActive.LastTip();
1186         MilliSleep(5000 + rand() % 5000);
1187         waitForPeers(chainparams);
1188         pindexCur = chainActive.LastTip();
1189     } while (pindexPrev != pindexCur);
1190
1191     // this will not stop printing more than once in all cases, but it will allow us to print in all cases
1192     // and print duplicates rarely without having to synchronize
1193     static CBlockIndex *lastChainTipPrinted;
1194
1195     miningTimer.start();
1196
1197     try {
1198         printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1199         while (true)
1200         {
1201             miningTimer.stop();
1202             waitForPeers(chainparams);
1203
1204             pindexPrev = chainActive.LastTip();
1205             sleep(1);
1206
1207             // prevent forking on startup before the diff algorithm kicks in
1208             if (pindexPrev->GetHeight() < 50 || pindexPrev != chainActive.LastTip())
1209             {
1210                 do {
1211                     pindexPrev = chainActive.LastTip();
1212                     MilliSleep(5000 + rand() % 5000);
1213                 } while (pindexPrev != chainActive.LastTip());
1214             }
1215
1216             // Create new block
1217             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1218             if ( Mining_height != pindexPrev->GetHeight()+1 )
1219             {
1220                 Mining_height = pindexPrev->GetHeight()+1;
1221                 Mining_start = (uint32_t)time(NULL);
1222             }
1223
1224             if (lastChainTipPrinted != pindexPrev)
1225             {
1226                 printf("Mining height %d\n", Mining_height);
1227                 lastChainTipPrinted = pindexPrev;
1228             }
1229
1230             miningTimer.start();
1231
1232 #ifdef ENABLE_WALLET
1233             CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
1234 #else
1235             CBlockTemplate *ptr = CreateNewBlockWithKey();
1236 #endif
1237             if ( ptr == 0 )
1238             {
1239                 static uint32_t counter;
1240                 if ( counter++ < 100 )
1241                     fprintf(stderr,"created illegal block, retry\n");
1242                 continue;
1243             }
1244
1245             unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1246             if (!pblocktemplate.get())
1247             {
1248                 if (GetArg("-mineraddress", "").empty()) {
1249                     LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1250                               ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1251                 } else {
1252                     // Should never reach here, because -mineraddress validity is checked in init.cpp
1253                     LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
1254                 }
1255                 return;
1256             }
1257             CBlock *pblock = &pblocktemplate->block;
1258             if ( ASSETCHAINS_SYMBOL[0] != 0 )
1259             {
1260                 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1261                 {
1262                     if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1263                     {
1264                         static uint32_t counter;
1265                         if ( counter++ < 10 )
1266                             fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1267                         sleep(10);
1268                         continue;
1269                     } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1270                 }
1271             }
1272             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1273             LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
1274                        pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1275             //
1276             // Search
1277             //
1278             uint32_t savebits; int64_t nStart = GetTime();
1279
1280             pblock->nSolution = solnPlaceholder;
1281             savebits = pblock->nBits;
1282             arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1283             arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
1284
1285             Mining_start = 0;
1286
1287             if ( pindexPrev != chainActive.LastTip() )
1288             {
1289                 if (lastChainTipPrinted != chainActive.LastTip())
1290                 {
1291                     lastChainTipPrinted = chainActive.LastTip();
1292                     printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1293                 }
1294                 MilliSleep(250);
1295                 continue;
1296             }
1297
1298             if ( ASSETCHAINS_STAKED != 0 )
1299             {
1300                 int32_t percPoS,z;
1301                 hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);
1302                 for (z=31; z>=0; z--)
1303                     fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]);
1304                 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1305             }
1306
1307             while (true)
1308             {
1309                 arith_uint256 arNonce = UintToArith256(pblock->nNonce);
1310
1311                 CVerusHashWriter ss = CVerusHashWriter(SER_GETHASH, PROTOCOL_VERSION);
1312                 ss << *((CBlockHeader *)pblock);
1313                 int64_t *extraPtr = ss.xI64p();
1314                 CVerusHash &vh = ss.GetState();
1315                 uint256 hashResult = uint256();
1316                 vh.ClearExtra();
1317                 int64_t i, count = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1;
1318                 int64_t hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
1319
1320                 // for speed check NONCEMASK at a time
1321                 for (i = 0; i < count; i++)
1322                 {
1323                     *extraPtr = i;
1324                     vh.ExtraHash((unsigned char *)&hashResult);
1325
1326                     if ( UintToArith256(hashResult) <= hashTarget )
1327                     {
1328                         if (pblock->nSolution.size() != 1344)
1329                         {
1330                             LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
1331                             sleep(5);
1332                             break;
1333                         }
1334
1335                         SetThreadPriority(THREAD_PRIORITY_NORMAL);
1336
1337                         *((int64_t *)&(pblock->nSolution.data()[pblock->nSolution.size() - 15])) = i;
1338
1339                         int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1340                         int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1341
1342                         LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1343                         LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1344                         printf("Found block %d \n", Mining_height );
1345                         printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
1346                         printf("  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
1347                         if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1348                             printf("- timelocked until block %i\n", unlockTime);
1349                         else
1350                             printf("\n");
1351 #ifdef ENABLE_WALLET
1352                         ProcessBlockFound(pblock, *pwallet, reservekey);
1353 #else
1354                         ProcessBlockFound(pblock));
1355 #endif
1356                         SetThreadPriority(THREAD_PRIORITY_LOWEST);
1357                         break;
1358                     }
1359                     // check periodically if we're stale
1360                     if (!--hashesToGo)
1361                     {
1362                         if ( pindexPrev != chainActive.LastTip() )
1363                         {
1364                             if (lastChainTipPrinted != chainActive.LastTip())
1365                             {
1366                                 lastChainTipPrinted = chainActive.LastTip();
1367                                 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1368                             }
1369                             break;
1370                         }
1371                         hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
1372                     }
1373                 }
1374
1375                 {
1376                     LOCK(cs_metrics);
1377                     nHashCount += i;
1378                 }
1379
1380                 // Check for stop or if block needs to be rebuilt
1381                 boost::this_thread::interruption_point();
1382
1383                 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1384                 {
1385                     if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1386                     {
1387                         fprintf(stderr,"no nodes, attempting reconnect\n");
1388                         break;
1389                     }
1390                 }
1391
1392                 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1393                 {
1394                     fprintf(stderr,"timeout, retrying\n");
1395                     break;
1396                 }
1397
1398                 if ( pindexPrev != chainActive.LastTip() )
1399                 {
1400                     if (lastChainTipPrinted != chainActive.LastTip())
1401                     {
1402                         lastChainTipPrinted = chainActive.LastTip();
1403                         printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1404                     }
1405                     break;
1406                 }
1407
1408 #ifdef _WIN32
1409                 printf("%llu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
1410 #else
1411                 printf("%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
1412 #endif
1413                 break;
1414
1415             }
1416         }
1417     }
1418     catch (const boost::thread_interrupted&)
1419     {
1420         miningTimer.stop();
1421         LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1422         throw;
1423     }
1424     catch (const std::runtime_error &e)
1425     {
1426         miningTimer.stop();
1427         LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
1428         return;
1429     }
1430     miningTimer.stop();
1431 }
1432
1433 #ifdef ENABLE_WALLET
1434 void static BitcoinMiner(CWallet *pwallet)
1435 #else
1436 void static BitcoinMiner()
1437 #endif
1438 {
1439     LogPrintf("KomodoMiner started\n");
1440     SetThreadPriority(THREAD_PRIORITY_LOWEST);
1441     RenameThread("komodo-miner");
1442     const CChainParams& chainparams = Params();
1443     
1444 #ifdef ENABLE_WALLET
1445     // Each thread has its own key
1446     CReserveKey reservekey(pwallet);
1447 #endif
1448     
1449     // Each thread has its own counter
1450     unsigned int nExtraNonce = 0;
1451     
1452     unsigned int n = chainparams.EquihashN();
1453     unsigned int k = chainparams.EquihashK();
1454     uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
1455     while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
1456     {
1457         sleep(1);
1458         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1459             break;
1460     }
1461     if ( ASSETCHAINS_SYMBOL[0] == 0 )
1462         komodo_chosennotary(&notaryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
1463     if ( notaryid != My_notaryid )
1464         My_notaryid = notaryid;
1465     std::string solver;
1466     //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
1467     solver = "tromp";
1468     //else solver = "default";
1469     assert(solver == "tromp" || solver == "default");
1470     LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
1471     if ( ASSETCHAINS_SYMBOL[0] != 0 )
1472         fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
1473     std::mutex m_cs;
1474     bool cancelSolver = false;
1475     boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
1476                                                                        [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1477                                                                            std::lock_guard<std::mutex> lock{m_cs};
1478                                                                            cancelSolver = true;
1479                                                                        }
1480                                                                        );
1481     miningTimer.start();
1482     
1483     try {
1484         if ( ASSETCHAINS_SYMBOL[0] != 0 )
1485             fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
1486         while (true)
1487         {
1488             if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
1489             {
1490                 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
1491                 //    break;
1492                 // Busy-wait for the network to come online so we don't waste time mining
1493                 // on an obsolete chain. In regtest mode we expect to fly solo.
1494                 miningTimer.stop();
1495                 do {
1496                     bool fvNodesEmpty;
1497                     {
1498                         //LOCK(cs_vNodes);
1499                         fvNodesEmpty = vNodes.empty();
1500                     }
1501                     if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
1502                         break;
1503                     MilliSleep(15000);
1504                     //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
1505                     
1506                 } while (true);
1507                 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
1508                 miningTimer.start();
1509             }
1510             //
1511             // Create new block
1512             //
1513             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1514             CBlockIndex* pindexPrev = chainActive.LastTip();
1515             if ( Mining_height != pindexPrev->GetHeight()+1 )
1516             {
1517                 Mining_height = pindexPrev->GetHeight()+1;
1518                 Mining_start = (uint32_t)time(NULL);
1519             }
1520             if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
1521             {
1522                 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
1523                 //sleep(3);
1524             }
1525
1526 #ifdef ENABLE_WALLET
1527             // notaries always default to staking
1528             CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
1529 #else
1530             CBlockTemplate *ptr = CreateNewBlockWithKey();
1531 #endif
1532             if ( ptr == 0 )
1533             {
1534                 static uint32_t counter;
1535                 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1536                     fprintf(stderr,"created illegal block, retry\n");
1537                 sleep(1);
1538                 continue;
1539             }
1540             //fprintf(stderr,"get template\n");
1541             unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1542             if (!pblocktemplate.get())
1543             {
1544                 if (GetArg("-mineraddress", "").empty()) {
1545                     LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
1546                 } else {
1547                     // Should never reach here, because -mineraddress validity is checked in init.cpp
1548                     LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
1549                 }
1550                 return;
1551             }
1552             CBlock *pblock = &pblocktemplate->block;
1553             if ( ASSETCHAINS_SYMBOL[0] != 0 )
1554             {
1555                 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1556                 {
1557                     if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1558                     {
1559                         static uint32_t counter;
1560                         if ( counter++ < 10 )
1561                             fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1562                         sleep(10);
1563                         continue;
1564                     } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1565                 }
1566             }
1567             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1568             //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
1569             LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1570             //
1571             // Search
1572             //
1573             uint8_t pubkeys[66][33]; arith_uint256 bnMaxPoSdiff; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
1574             pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
1575             savebits = pblock->nBits;
1576             HASHTarget = arith_uint256().SetCompact(savebits);
1577             roundrobin_delay = ROUNDROBIN_DELAY;
1578             if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
1579             {
1580                 j = 65;
1581                 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
1582                 {
1583                     int32_t dispflag = 0;
1584                     if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
1585                         dispflag = 1;
1586                     komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
1587                     if ( nonzpkeys > 0 )
1588                     {
1589                         for (i=0; i<33; i++)
1590                             if( pubkeys[0][i] != 0 )
1591                                 break;
1592                         if ( i == 33 )
1593                             externalflag = 1;
1594                         else externalflag = 0;
1595                         if ( IS_KOMODO_NOTARY != 0 )
1596                         {
1597                             for (i=1; i<66; i++)
1598                                 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1599                                     break;
1600                             if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1601                                 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
1602                             for (j=gpucount=0; j<65; j++)
1603                             {
1604                                 if ( dispflag != 0 )
1605                                 {
1606                                     if ( mids[j] >= 0 )
1607                                         fprintf(stderr,"%d ",mids[j]);
1608                                     else fprintf(stderr,"GPU ");
1609                                 }
1610                                 if ( mids[j] == -1 )
1611                                     gpucount++;
1612                             }
1613                             if ( dispflag != 0 )
1614                                 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->GetHeight(),notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL));
1615                         }
1616                         for (j=0; j<65; j++)
1617                             if ( mids[j] == notaryid )
1618                                 break;
1619                         if ( j == 65 )
1620                             KOMODO_LASTMINED = 0;
1621                     } else fprintf(stderr,"no nonz pubkeys\n");
1622                     if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
1623                     {
1624                         HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
1625                         fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);
1626                     } //else fprintf(stderr,"duplicate at j.%d\n",j);
1627                 } else Mining_start = 0;
1628             } else Mining_start = 0;
1629             if ( ASSETCHAINS_STAKED != 0 )
1630             {
1631                 int32_t percPoS,z; bool fNegative,fOverflow;
1632                 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1633                 HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
1634                 if ( ASSETCHAINS_STAKED < 100 )
1635                 {
1636                     for (z=31; z>=0; z--)
1637                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1638                     fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1639                 }
1640             }
1641             while (true)
1642             {
1643                 if ( KOMODO_INSYNC == 0 )
1644                 {
1645                     fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
1646                     if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
1647                         KOMODO_INSYNC = 1;
1648                     sleep(3);
1649                 }
1650                 // Hash state
1651                 KOMODO_CHOSEN_ONE = 0;
1652                 
1653                 crypto_generichash_blake2b_state state;
1654                 EhInitialiseState(n, k, state);
1655                 // I = the block header minus nonce and solution.
1656                 CEquihashInput I{*pblock};
1657                 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1658                 ss << I;
1659                 // H(I||...
1660                 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
1661                 // H(I||V||...
1662                 crypto_generichash_blake2b_state curr_state;
1663                 curr_state = state;
1664                 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
1665                 // (x_1, x_2, ...) = A(I, V, n, k)
1666                 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
1667                 arith_uint256 hashTarget;
1668                 if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
1669                     hashTarget = HASHTarget_POW;
1670                 else hashTarget = HASHTarget;
1671                 std::function<bool(std::vector<unsigned char>)> validBlock =
1672 #ifdef ENABLE_WALLET
1673                 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
1674 #else
1675                 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
1676 #endif
1677                 (std::vector<unsigned char> soln) {
1678                     int32_t z; arith_uint256 h; CBlock B;
1679                     // Write the solution to the hash and compute the result.
1680                     LogPrint("pow", "- Checking solution against target\n");
1681                     pblock->nSolution = soln;
1682                     solutionTargetChecks.increment();
1683                     B = *pblock;
1684                     h = UintToArith256(B.GetHash());
1685                     /*for (z=31; z>=16; z--)
1686                         fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1687                     fprintf(stderr," mined ");
1688                     for (z=31; z>=16; z--)
1689                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
1690                     fprintf(stderr," hashTarget ");
1691                     for (z=31; z>=16; z--)
1692                         fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1693                     fprintf(stderr," POW\n");*/
1694                     if ( h > hashTarget )
1695                     {
1696                         //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
1697                         //    sleep(1);
1698                         return false;
1699                     }
1700                     if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
1701                     {
1702                         //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1703                         while ( GetAdjustedTime() < B.nTime-2 )
1704                         {
1705                             sleep(1);
1706                             if ( chainActive.LastTip()->GetHeight() >= Mining_height )
1707                             {
1708                                 fprintf(stderr,"new block arrived\n");
1709                                 return(false);
1710                             }
1711                         }
1712                     }
1713                     if ( ASSETCHAINS_STAKED == 0 )
1714                     {
1715                         if ( IS_KOMODO_NOTARY != 0 )
1716                         {
1717                             int32_t r;
1718                             if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
1719                                 MilliSleep((rand() % (r * 1000)) + 1000);
1720                         }
1721                     }
1722                     else
1723                     {
1724                         while ( B.nTime-57 > GetAdjustedTime() )
1725                         {
1726                             sleep(1);
1727                             if ( chainActive.LastTip()->GetHeight() >= Mining_height )
1728                                 return(false);
1729                         }
1730                         uint256 tmp = B.GetHash();
1731                         int32_t z; for (z=31; z>=0; z--)
1732                             fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1733                         fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
1734                     }
1735                     CValidationState state;
1736                     if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
1737                     {
1738                         h = UintToArith256(B.GetHash());
1739                         for (z=31; z>=0; z--)
1740                             fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1741                         fprintf(stderr," Invalid block mined, try again\n");
1742                         return(false);
1743                     }
1744                     KOMODO_CHOSEN_ONE = 1;
1745                     // Found a solution
1746                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
1747                     LogPrintf("KomodoMiner:\n");
1748                     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
1749 #ifdef ENABLE_WALLET
1750                     if (ProcessBlockFound(&B, *pwallet, reservekey)) {
1751 #else
1752                         if (ProcessBlockFound(&B)) {
1753 #endif
1754                             // Ignore chain updates caused by us
1755                             std::lock_guard<std::mutex> lock{m_cs};
1756                             cancelSolver = false;
1757                         }
1758                         KOMODO_CHOSEN_ONE = 0;
1759                         SetThreadPriority(THREAD_PRIORITY_LOWEST);
1760                         // In regression test mode, stop mining after a block is found.
1761                         if (chainparams.MineBlocksOnDemand()) {
1762                             // Increment here because throwing skips the call below
1763                             ehSolverRuns.increment();
1764                             throw boost::thread_interrupted();
1765                         }
1766                         return true;
1767                     };
1768                     std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1769                         std::lock_guard<std::mutex> lock{m_cs};
1770                         return cancelSolver;
1771                     };
1772                     
1773                     // TODO: factor this out into a function with the same API for each solver.
1774                     if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1775                         // Create solver and initialize it.
1776                         equi eq(1);
1777                         eq.setstate(&curr_state);
1778                         
1779                         // Initialization done, start algo driver.
1780                         eq.digit0(0);
1781                         eq.xfull = eq.bfull = eq.hfull = 0;
1782                         eq.showbsizes(0);
1783                         for (u32 r = 1; r < WK; r++) {
1784                             (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1785                             eq.xfull = eq.bfull = eq.hfull = 0;
1786                             eq.showbsizes(r);
1787                         }
1788                         eq.digitK(0);
1789                         ehSolverRuns.increment();
1790                         
1791                         // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1792                         for (size_t s = 0; s < eq.nsols; s++) {
1793                             LogPrint("pow", "Checking solution %d\n", s+1);
1794                             std::vector<eh_index> index_vector(PROOFSIZE);
1795                             for (size_t i = 0; i < PROOFSIZE; i++) {
1796                                 index_vector[i] = eq.sols[s][i];
1797                             }
1798                             std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1799                             
1800                             if (validBlock(sol_char)) {
1801                                 // If we find a POW solution, do not try other solutions
1802                                 // because they become invalid as we created a new block in blockchain.
1803                                 break;
1804                             }
1805                         }
1806                     } else {
1807                         try {
1808                             // If we find a valid block, we rebuild
1809                             bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1810                             ehSolverRuns.increment();
1811                             if (found) {
1812                                 int32_t i; uint256 hash = pblock->GetHash();
1813                                 for (i=0; i<32; i++)
1814                                     fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1815                                 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1816                                 FOUND_BLOCK = 1;
1817                                 KOMODO_MAYBEMINED = Mining_height;
1818                                 break;
1819                             }
1820                         } catch (EhSolverCancelledException&) {
1821                             LogPrint("pow", "Equihash solver cancelled\n");
1822                             std::lock_guard<std::mutex> lock{m_cs};
1823                             cancelSolver = false;
1824                         }
1825                     }
1826                     
1827                     // Check for stop or if block needs to be rebuilt
1828                     boost::this_thread::interruption_point();
1829                     // Regtest mode doesn't require peers
1830                     if ( FOUND_BLOCK != 0 )
1831                     {
1832                         FOUND_BLOCK = 0;
1833                         fprintf(stderr,"FOUND_BLOCK!\n");
1834                         //sleep(2000);
1835                     }
1836                     if (vNodes.empty() && chainparams.MiningRequiresPeers())
1837                     {
1838                         if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1839                         {
1840                             fprintf(stderr,"no nodes, break\n");
1841                             break;
1842                         }
1843                     }
1844                     if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1845                     {
1846                         //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1847                         fprintf(stderr,"0xffff, break\n");
1848                         break;
1849                     }
1850                     if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1851                     {
1852                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1853                             fprintf(stderr,"timeout, break\n");
1854                         break;
1855                     }
1856                     if ( pindexPrev != chainActive.LastTip() )
1857                     {
1858                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1859                             fprintf(stderr,"Tip advanced, break\n");
1860                         break;
1861                     }
1862                     // Update nNonce and nTime
1863                     pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1864                     pblock->nBits = savebits;
1865                     /*if ( NOTARY_PUBKEY33[0] == 0 )
1866                     {
1867                         int32_t percPoS;
1868                         UpdateTime(pblock, consensusParams, pindexPrev);
1869                         if (consensusParams.fPowAllowMinDifficultyBlocks)
1870                         {
1871                             // Changing pblock->nTime can change work required on testnet:
1872                             HASHTarget.SetCompact(pblock->nBits);
1873                             HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1874                         }
1875                     }*/
1876                 }
1877             }
1878         }
1879         catch (const boost::thread_interrupted&)
1880         {
1881             miningTimer.stop();
1882             c.disconnect();
1883             LogPrintf("KomodoMiner terminated\n");
1884             throw;
1885         }
1886         catch (const std::runtime_error &e)
1887         {
1888             miningTimer.stop();
1889             c.disconnect();
1890             LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1891             return;
1892         }
1893         miningTimer.stop();
1894         c.disconnect();
1895     }
1896     
1897 #ifdef ENABLE_WALLET
1898     void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1899 #else
1900     void GenerateBitcoins(bool fGenerate, int nThreads)
1901 #endif
1902     {
1903         // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at
1904         // initialization, and this is the first time we can get it. store the Sapling address here
1905         extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
1906         extern std::string VERUS_CHEATCATCHER;
1907         libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER);
1908         if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr))
1909         {
1910             cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);
1911         }
1912         else
1913         {
1914             if (VERUS_CHEATCATCHER.size() > 0)
1915                 fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n");
1916         }    
1917
1918         static boost::thread_group* minerThreads = NULL;
1919         
1920         if (nThreads < 0)
1921             nThreads = GetNumCores();
1922         
1923         if (minerThreads != NULL)
1924         {
1925             minerThreads->interrupt_all();
1926             delete minerThreads;
1927             minerThreads = NULL;
1928         }
1929
1930         //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
1931         if ( nThreads == 0 && ASSETCHAINS_STAKED )
1932             nThreads = 1;
1933
1934         if ((nThreads == 0 || !fGenerate) && (VERUS_MINTBLOCKS == 0 || pwallet == NULL))
1935             return;
1936
1937         minerThreads = new boost::thread_group();
1938
1939 #ifdef ENABLE_WALLET
1940         if (ASSETCHAINS_LWMAPOS != 0 && VERUS_MINTBLOCKS)
1941         {
1942             minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
1943         }
1944 #endif
1945
1946         for (int i = 0; i < nThreads; i++) {
1947
1948 #ifdef ENABLE_WALLET
1949             if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1950                 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1951             else
1952                 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
1953 #else
1954             if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1955                 minerThreads->create_thread(&BitcoinMiner);
1956             else
1957                 minerThreads->create_thread(&BitcoinMiner_noeq);
1958 #endif
1959         }
1960     }
1961     
1962 #endif // ENABLE_MINING
This page took 0.145026 seconds and 4 git commands to generate.