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