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