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.
8 #include "pow/tromp/equi_miner.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"
19 #include "crypto/equihash.h"
20 #include "crypto/verus_hash.h"
28 #include "primitives/transaction.h"
31 #include "ui_interface.h"
33 #include "utilmoneystr.h"
35 #include "wallet/wallet.h"
38 #include "zcash/Address.hpp"
39 #include "transaction_builder.h"
43 #include <boost/thread.hpp>
44 #include <boost/tuple/tuple.hpp>
52 //////////////////////////////////////////////////////////////////////////////
58 // Unconfirmed transactions in the memory pool often depend on other
59 // transactions in the memory pool. When we select transactions from the
60 // pool, we select by highest priority or fee rate, so we might consider
61 // transactions that depend on transactions that aren't yet in the block.
62 // The COrphan class keeps track of these 'temporary orphans' while
63 // CreateBlock is figuring out which transactions to include.
68 const CTransaction* ptx;
69 set<uint256> setDependsOn;
73 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
78 uint64_t nLastBlockTx = 0;
79 uint64_t nLastBlockSize = 0;
81 // We want to sort transactions by priority and fee rate, so:
82 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
83 class TxPriorityCompare
88 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
90 bool operator()(const TxPriority& a, const TxPriority& b)
94 if (a.get<1>() == b.get<1>())
95 return a.get<0>() < b.get<0>();
96 return a.get<1>() < b.get<1>();
100 if (a.get<0>() == b.get<0>())
101 return a.get<1>() < b.get<1>();
102 return a.get<0>() < b.get<0>();
107 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
109 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
111 // Updating time can change work required on testnet:
112 if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {
113 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
117 #include "komodo_defs.h"
119 extern CCriticalSection cs_metrics;
120 extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
121 extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
122 extern bool VERUS_MINTBLOCKS;
123 extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
124 extern const char *ASSETCHAINS_ALGORITHMS[];
125 extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
126 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
127 extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
128 void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
130 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
131 uint32_t Mining_start,Mining_height;
132 int32_t My_notaryid = -1;
133 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
134 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
135 int32_t komodo_baseid(char *origbase);
136 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
137 int64_t komodo_block_unlocktime(uint32_t nHeight);
138 uint64_t komodo_commission(const CBlock *block);
139 int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
140 int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk);
141 int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
143 CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
145 CScript scriptPubKeyIn(_scriptPubKeyIn);
147 CPubKey pk = CPubKey();
148 std::vector<std::vector<unsigned char>> vAddrs;
150 if (Solver(scriptPubKeyIn, txT, vAddrs))
152 if (txT == TX_PUBKEY)
153 pk = CPubKey(vAddrs[0]);
156 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
157 //fprintf(stderr,"create new block\n");
160 gpucount = KOMODO_MAXGPUCOUNT;
161 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
162 if(!pblocktemplate.get())
164 fprintf(stderr,"pblocktemplate.get() failure\n");
167 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
168 // -regtest only: allow overriding block.nVersion with
169 // -blockversion=N to test forking scenarios
170 if (Params().MineBlocksOnDemand())
171 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
173 // Add dummy coinbase tx as first transaction
174 pblock->vtx.push_back(CTransaction());
175 pblocktemplate->vTxFees.push_back(-1); // updated at end
176 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
178 // Largest block you're willing to create:
179 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
180 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
181 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
183 // How much of the block should be dedicated to high-priority transactions,
184 // included regardless of the fees they pay
185 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
186 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
188 // Minimum block size you want to create; block will be filled with free transactions
189 // until there are no more or the block reaches this size:
190 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
191 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
193 // Collect memory pool transactions into the block
196 // we will attempt to spend any cheats we see
197 CTransaction cheatTx;
198 boost::optional<CTransaction> cheatSpend;
201 CBlockIndex* pindexPrev = 0;
203 LOCK2(cs_main, mempool.cs);
204 pindexPrev = chainActive.LastTip();
205 const int nHeight = pindexPrev->GetHeight() + 1;
206 const Consensus::Params &consensusParams = chainparams.GetConsensus();
207 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams);
208 bool sapling = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING);
210 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
211 uint32_t proposedTime = GetAdjustedTime();
212 if (proposedTime == nMedianTimePast)
214 // too fast or stuck, this addresses the too fast issue, while moving
215 // forward as quickly as possible
216 for (int i; i < 100; i++)
218 proposedTime = GetAdjustedTime();
219 if (proposedTime == nMedianTimePast)
223 pblock->nTime = GetAdjustedTime();
225 CCoinsViewCache view(pcoinsTip);
226 uint32_t expired; uint64_t commission;
228 SaplingMerkleTree sapling_tree;
229 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
231 // Priority order to process transactions
232 list<COrphan> vOrphan; // list memory doesn't move
233 map<uint256, vector<COrphan*> > mapDependers;
234 bool fPrintPriority = GetBoolArg("-printpriority", false);
236 // This vector will be sorted into a priority queue:
237 vector<TxPriority> vecPriority;
238 vecPriority.reserve(mempool.mapTx.size() + 1);
240 // check if we should add cheat transaction
243 int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;
245 sapling && chainActive.Height() > 100 &&
246 (ppast = chainActive[cheatHeight]) &&
247 ppast->IsVerusPOSBlock() &&
248 cheatList.IsHeightOrGreaterInList(cheatHeight))
250 // get the block and see if there is a cheat candidate for the stake tx
252 if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, 1))
254 CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];
256 if (cheatList.IsCheatInList(stakeTx, &cheatTx))
258 // make and sign the cheat transaction to spend the coinbase to our address
259 CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
262 // get the first vout with value
263 for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)
265 if (b.vtx[0].vout[voutNum].nValue > 0)
269 // send to the same pub key as the destination of this block reward
270 if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))
272 extern CWallet *pwalletMain;
273 LOCK(pwalletMain->cs_wallet);
274 TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);
276 cbHash = cb.GetHash();
278 bool hasInput = false;
279 for (uint32_t i = 0; i < cb.vout.size(); i++)
281 // add the spends with the cheat
282 if (cb.vout[i].nValue > 0)
284 tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);
291 // this is a send from a t-address to a sapling address, which we don't have an ovk for.
292 // Instead, generate a common one from the HD seed. This ensures the data is
293 // recoverable, at least for us, while keeping it logically separate from the ZIP 32
294 // Sapling key hierarchy, which the user might not be using.
297 if (pwalletMain->GetHDSeed(seed)) {
298 ovk = ovkForShieldingFromTaddr(seed);
300 // send everything to Sapling address
301 tb.SendChangeTo(cheatCatcher.value(), ovk);
303 tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);
305 cheatSpend = tb.Build();
308 cheatTx = boost::get<CTransaction>(cheatSpend);
309 unsigned int nTxSize = ::GetSerializeSize(cheatTx, SER_NETWORK, PROTOCOL_VERSION);
310 double dPriority = cheatTx.ComputePriority(dPriority, nTxSize);
311 CFeeRate feeRate(DEFAULT_TRANSACTION_MAXFEE, nTxSize);
312 vecPriority.push_back(TxPriority(dPriority, feeRate, &cheatTx));
323 std::list<CTransaction> removed;
324 mempool.removeConflicts(cheatSpend.value(), removed);
325 printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n",
326 (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str());
329 // now add transactions from the mem pool
330 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
331 mi != mempool.mapTx.end(); ++mi)
333 const CTransaction& tx = mi->GetTx();
335 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
337 : pblock->GetBlockTime();
339 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
341 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
345 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
347 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
351 COrphan* porphan = NULL;
352 double dPriority = 0;
353 CAmount nTotalIn = 0;
354 bool fMissingInputs = false;
355 if (tx.IsCoinImport())
357 CAmount nValueIn = GetCoinImportValue(tx);
358 nTotalIn += nValueIn;
359 dPriority += (double)nValueIn * 1000; // flat multiplier
361 BOOST_FOREACH(const CTxIn& txin, tx.vin)
363 // Read prev transaction
364 if (!view.HaveCoins(txin.prevout.hash))
366 // This should never happen; all transactions in the memory
367 // pool should connect to either transactions in the chain
368 // or other transactions in the memory pool.
369 if (!mempool.mapTx.count(txin.prevout.hash))
371 LogPrintf("ERROR: mempool transaction missing input\n");
372 if (fDebug) assert("mempool transaction missing input" == 0);
373 fMissingInputs = true;
379 // Has to wait for dependencies
382 // Use list for automatic deletion
383 vOrphan.push_back(COrphan(&tx));
384 porphan = &vOrphan.back();
386 mapDependers[txin.prevout.hash].push_back(porphan);
387 porphan->setDependsOn.insert(txin.prevout.hash);
388 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
391 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
394 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
395 nTotalIn += nValueIn;
397 int nConf = nHeight - coins->nHeight;
399 dPriority += (double)nValueIn * nConf;
401 nTotalIn += tx.GetShieldedValueIn();
404 if (fMissingInputs) continue;
406 // Priority is sum(valuein * age) / modified_txsize
407 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
408 dPriority = tx.ComputePriority(dPriority, nTxSize);
410 uint256 hash = tx.GetHash();
411 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
413 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
417 porphan->dPriority = dPriority;
418 porphan->feeRate = feeRate;
421 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
424 // Collect transactions into block
425 uint64_t nBlockSize = 1000;
426 uint64_t nBlockTx = 0;
428 int nBlockSigOps = 100;
429 bool fSortedByFee = (nBlockPrioritySize <= 0);
431 TxPriorityCompare comparer(fSortedByFee);
432 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
434 while (!vecPriority.empty())
436 // Take highest priority transaction off the priority queue:
437 double dPriority = vecPriority.front().get<0>();
438 CFeeRate feeRate = vecPriority.front().get<1>();
439 const CTransaction& tx = *(vecPriority.front().get<2>());
441 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
442 vecPriority.pop_back();
445 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
446 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
448 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
452 // Legacy limits on sigOps:
453 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
454 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
456 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
459 // Skip free transactions if we're past the minimum block size:
460 const uint256& hash = tx.GetHash();
461 double dPriorityDelta = 0;
462 CAmount nFeeDelta = 0;
463 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
464 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
466 //fprintf(stderr,"fee rate skip\n");
469 // Prioritise by fee once past the priority size or we run out of high-priority
472 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
475 comparer = TxPriorityCompare(fSortedByFee);
476 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
479 if (!view.HaveInputs(tx))
481 //fprintf(stderr,"dont have inputs\n");
484 CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();
486 nTxSigOps += GetP2SHSigOpCount(tx, view);
487 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
489 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
492 // Note that flags: we don't want to set mempool/IsStandard()
493 // policy here, but we still have to ensure that the block we
494 // create only contains transactions that are valid in new blocks.
495 CValidationState state;
496 PrecomputedTransactionData txdata(tx);
497 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
499 //fprintf(stderr,"context failure\n");
502 UpdateCoins(tx, view, nHeight);
504 BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
505 sapling_tree.append(outDescription.cm);
509 pblock->vtx.push_back(tx);
510 pblocktemplate->vTxFees.push_back(nTxFees);
511 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
512 nBlockSize += nTxSize;
514 nBlockSigOps += nTxSigOps;
519 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
522 // Add transactions that depend on this one to the priority queue
523 if (mapDependers.count(hash))
525 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
527 if (!porphan->setDependsOn.empty())
529 porphan->setDependsOn.erase(hash);
530 if (porphan->setDependsOn.empty())
532 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
533 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
540 nLastBlockTx = nBlockTx;
541 nLastBlockSize = nBlockSize;
542 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
543 //pblock->nTime = blocktime + 1;
544 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
546 int32_t stakeHeight = chainActive.Height() + 1;
548 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
549 if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
551 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
552 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), stakeHeight);
554 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
555 // blocktime = pindexPrev->GetMedianTimePast() + 60;
556 if (ASSETCHAINS_LWMAPOS != 0)
559 arith_uint256 posHash;
561 siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);
562 blocktime = GetAdjustedTime();
564 // change the scriptPubKeyIn to the same output script exactly as the staking transaction
566 scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
570 siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
577 // after Sapling, stake transactions have a fee, but it is recovered in the reward
578 // this ensures that a rebroadcast goes through quickly to begin staking again
579 txfees = sapling ? DEFAULT_STAKE_TXFEE : 0;
581 pblock->vtx.push_back(txStaked);
582 pblocktemplate->vTxFees.push_back(txfees);
583 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
585 pblock->nTime = blocktime;
586 //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->GetHeight()+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13)));
587 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
590 // Create coinbase tx
591 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
593 txNew.vin[0].prevout.SetNull();
594 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
596 txNew.vout.resize(1);
597 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
598 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,consensusParams) + nFees;
600 // once we get to Sapling, enable CC StakeGuard for stake transactions
601 if (isStake && sapling)
603 // if there is a specific destination, use it
604 CTransaction stakeTx = pblock->vtx[pblock->vtx.size() - 1];
606 if (ValidateStakeTransaction(stakeTx, p, false))
608 if (!p.pk.IsValid() || !MakeGuardedOutput(txNew.vout[0].nValue, p.pk, stakeTx, txNew.vout[0]))
610 fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
616 fprintf(stderr,"CreateNewBlock: invalid stake transaction\n");
621 txNew.nExpiryHeight = 0;
622 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
624 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
625 txNew.vout[0].nValue += 5000;
627 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
628 // to transaction if so, cast for GTE operator
629 if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
631 int32_t opretlen, p2shlen, scriptlen;
632 CScriptExt opretScript = CScriptExt();
634 txNew.vout.resize(2);
636 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
637 // protected only by the time lock rather than 100% inaccessible
638 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
639 if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition())
641 fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
645 opretScript += scriptPubKeyIn;
647 txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
648 txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
649 txNew.vout[1].nValue = 0;
650 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
651 else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
653 int32_t i; uint8_t *ptr;
654 txNew.vout.resize(2);
655 txNew.vout[1].nValue = commission;
656 txNew.vout[1].scriptPubKey.resize(35);
657 ptr = (uint8_t *)&txNew.vout[1].scriptPubKey[0];
660 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
661 ptr[34] = OP_CHECKSIG;
662 //printf("autocreate commision vout\n");
665 pblock->vtx[0] = txNew;
666 pblocktemplate->vTxFees[0] = -nFees;
668 // if not Verus stake, setup nonce, otherwise, leave it alone
669 if (!isStake || ASSETCHAINS_LWMAPOS == 0)
672 arith_uint256 nonce = UintToArith256(GetRandHash());
674 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
675 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
677 pblock->nNonce = ArithToUint256(nonce);
681 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
682 pblock->hashFinalSaplingRoot = sapling_tree.root();
684 // all Verus PoS chains need this data in the block at all times
685 if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )
687 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
688 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
690 pblock->nSolution.clear();
691 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
692 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
695 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
696 if ( pblock->nTime < pindexPrev->nTime+60 )
697 pblock->nTime = pindexPrev->nTime + 60;
700 uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
701 memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
702 memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
703 memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
704 vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
705 memcpy(&r,&randvals,sizeof(r));
706 pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
708 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
710 CAmount txfees = 5000;
711 pblock->vtx.push_back(txNotary);
712 pblocktemplate->vTxFees.push_back(txfees);
713 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
715 pblocktemplate->vTxFees[0] = -nFees;
716 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
717 //fprintf(stderr,"added notaryvin\n");
721 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
725 else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
727 CValidationState state;
728 //fprintf(stderr,"check validity\n");
729 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
731 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
733 //fprintf(stderr,"valid\n");
736 //fprintf(stderr,"done new block\n");
737 return pblocktemplate.release();
742 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
744 boost::optional<CScript> GetMinerScriptPubKey()
748 CBitcoinAddress addr;
749 if (addr.SetString(GetArg("-mineraddress", ""))) {
750 addr.GetKeyID(keyID);
754 if (!reservekey.GetReservedKey(pubkey)) {
755 return boost::optional<CScript>();
757 keyID = pubkey.GetID();
759 return boost::optional<CScript>();
763 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
768 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
770 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
772 CBlockTemplate* CreateNewBlockWithKey()
774 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
780 return CreateNewBlock(*scriptPubKey);
783 //////////////////////////////////////////////////////////////////////////////
790 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
792 // Update nExtraNonce
793 static uint256 hashPrevBlock;
794 if (hashPrevBlock != pblock->hashPrevBlock)
797 hashPrevBlock = pblock->hashPrevBlock;
800 unsigned int nHeight = pindexPrev->GetHeight()+1; // Height first in coinbase required for block.version=2
801 CMutableTransaction txCoinbase(pblock->vtx[0]);
802 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
803 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
805 pblock->vtx[0] = txCoinbase;
806 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
810 //////////////////////////////////////////////////////////////////////////////
815 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
817 CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;
818 if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
820 scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
822 else if ( USE_EXTERNAL_PUBKEY != 0 )
824 //fprintf(stderr,"use notary pubkey\n");
825 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
829 if (!reservekey.GetReservedKey(pubkey))
833 scriptPubKey.resize(35);
834 ptr = (uint8_t *)pubkey.begin();
835 scriptPubKey[0] = 33;
837 scriptPubKey[i+1] = ptr[i];
838 scriptPubKey[34] = OP_CHECKSIG;
839 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
841 return CreateNewBlock(scriptPubKey, gpucount, isStake);
844 void komodo_broadcast(CBlock *pblock,int32_t limit)
847 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
850 BOOST_FOREACH(CNode* pnode, vNodes)
852 if ( pnode->hSocket == INVALID_SOCKET )
854 if ( (rand() % n) == 0 )
856 pnode->PushMessage("block", *pblock);
862 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
865 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
867 static bool ProcessBlockFound(CBlock* pblock)
868 #endif // ENABLE_WALLET
870 LogPrintf("%s\n", pblock->ToString());
871 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1);
875 if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
877 uint256 hash; int32_t i;
878 hash = pblock->hashPrevBlock;
879 for (i=31; i>=0; i--)
880 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
881 fprintf(stderr," <- prev (stale)\n");
882 hash = chainActive.LastTip()->GetBlockHash();
883 for (i=31; i>=0; i--)
884 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
885 fprintf(stderr," <- chainTip (stale)\n");
887 return error("KomodoMiner: generated block is stale");
892 // Remove key from key pool
893 if ( IS_KOMODO_NOTARY == 0 )
895 if (GetArg("-mineraddress", "").empty()) {
896 // Remove key from key pool
897 reservekey.KeepKey();
900 // Track how many getdata requests this block gets
903 //fprintf(stderr,"lock cs_wallet\n");
904 LOCK(wallet.cs_wallet);
905 wallet.mapRequestCount[pblock->GetHash()] = 0;
908 //fprintf(stderr,"process new block\n");
910 // Process this block the same as if we had received it from another node
911 CValidationState state;
912 if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL))
913 return error("KomodoMiner: ProcessNewBlock, block not accepted");
915 TrackMinedBlock(pblock->GetHash());
916 komodo_broadcast(pblock,16);
920 int32_t komodo_baseid(char *origbase);
921 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
922 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
923 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
924 extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;
925 int32_t roundrobin_delay;
926 arith_uint256 HASHTarget,HASHTarget_POW;
928 // wait for peers to connect
929 int32_t waitForPeers(const CChainParams &chainparams)
931 if (chainparams.MiningRequiresPeers())
935 boost::this_thread::interruption_point();
937 fvNodesEmpty = vNodes.empty();
939 if (fvNodesEmpty || IsNotInSync())
941 int loops = 0, blockDiff = 0, newDiff = 0;
946 MilliSleep(1000 + rand() % 4000);
947 boost::this_thread::interruption_point();
949 fvNodesEmpty = vNodes.empty();
953 if ((newDiff = IsNotInSync()) > 1)
955 if (blockDiff != newDiff)
968 } while (fvNodesEmpty || IsNotInSync());
969 MilliSleep(100 + rand() % 400);
975 CBlockIndex *get_chainactive(int32_t height)
977 if ( chainActive.LastTip() != 0 )
979 if ( height <= chainActive.LastTip()->GetHeight() )
982 return(chainActive[height]);
984 // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight());
986 //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height);
991 * A separate thread to stake, while the miner threads mine.
993 void static VerusStaker(CWallet *pwallet)
995 LogPrintf("Verus staker thread started\n");
996 RenameThread("verus-staker");
998 const CChainParams& chainparams = Params();
999 auto consensusParams = chainparams.GetConsensus();
1001 // Each thread has its own key
1002 CReserveKey reservekey(pwallet);
1004 // Each thread has its own counter
1005 unsigned int nExtraNonce = 0;
1006 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
1007 solnPlaceholder.resize(Eh200_9.SolutionWidth);
1008 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1010 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
1013 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1017 // try a nice clean peer connection to start
1018 CBlockIndex *pindexPrev, *pindexCur;
1020 pindexPrev = chainActive.LastTip();
1021 MilliSleep(5000 + rand() % 5000);
1022 waitForPeers(chainparams);
1023 pindexCur = chainActive.LastTip();
1024 } while (pindexPrev != pindexCur);
1029 waitForPeers(chainparams);
1030 CBlockIndex* pindexPrev = chainActive.LastTip();
1031 printf("Staking height %d for %s\n", pindexPrev->GetHeight() + 1, ASSETCHAINS_SYMBOL);
1034 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1035 if ( Mining_height != pindexPrev->GetHeight()+1 )
1037 Mining_height = pindexPrev->GetHeight()+1;
1038 Mining_start = (uint32_t)time(NULL);
1041 // Check for stop or if block needs to be rebuilt
1042 boost::this_thread::interruption_point();
1044 // try to stake a block
1045 CBlockTemplate *ptr = NULL;
1046 if (Mining_height > VERUS_MIN_STAKEAGE)
1047 ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true);
1051 // wait to try another staking block until after the tip moves again
1052 while ( chainActive.LastTip() == pindexPrev )
1057 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1058 if (!pblocktemplate.get())
1060 if (GetArg("-mineraddress", "").empty()) {
1061 LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1062 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1064 // Should never reach here, because -mineraddress validity is checked in init.cpp
1065 LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
1070 CBlock *pblock = &pblocktemplate->block;
1071 LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1075 int64_t nStart = GetTime();
1077 // take up the necessary space for alignment
1078 pblock->nSolution = solnPlaceholder;
1080 // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree
1081 unsigned int nExtraNonce = 0;
1082 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1084 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1086 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1088 fprintf(stderr,"no nodes, attempting reconnect\n");
1093 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1095 fprintf(stderr,"timeout, retrying\n");
1099 if ( pindexPrev != chainActive.LastTip() )
1101 printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight());
1106 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1107 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1109 uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
1111 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
1113 UpdateTime(pblock, consensusParams, pindexPrev);
1115 ProcessBlockFound(pblock, *pwallet, reservekey);
1117 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1118 LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1119 printf("Found block %d \n", Mining_height );
1120 printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
1122 post.SetCompact(pblock->GetVerusPOSTarget());
1123 pindexPrev = get_chainactive(Mining_height - 100);
1124 CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1];
1125 printf("POS hash: %s \ntarget: %s\n",
1126 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());
1127 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1128 printf("- timelocked until block %i\n", unlockTime);
1132 // Check for stop or if block needs to be rebuilt
1133 boost::this_thread::interruption_point();
1137 // In regression test mode, stop mining after a block is found.
1138 if (chainparams.MineBlocksOnDemand()) {
1139 throw boost::thread_interrupted();
1143 catch (const boost::thread_interrupted&)
1145 LogPrintf("VerusStaker terminated\n");
1148 catch (const std::runtime_error &e)
1150 LogPrintf("VerusStaker runtime error: %s\n", e.what());
1155 void static BitcoinMiner_noeq(CWallet *pwallet)
1157 void static BitcoinMiner_noeq()
1160 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1161 RenameThread("verushash-miner");
1163 #ifdef ENABLE_WALLET
1164 // Each thread has its own key
1165 CReserveKey reservekey(pwallet);
1168 const CChainParams& chainparams = Params();
1169 // Each thread has its own counter
1170 unsigned int nExtraNonce = 0;
1171 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
1172 solnPlaceholder.resize(Eh200_9.SolutionWidth);
1173 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1175 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
1178 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1182 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1184 // try a nice clean peer connection to start
1185 CBlockIndex *pindexPrev, *pindexCur;
1187 pindexPrev = chainActive.LastTip();
1188 MilliSleep(5000 + rand() % 5000);
1189 waitForPeers(chainparams);
1190 pindexCur = chainActive.LastTip();
1191 } while (pindexPrev != pindexCur);
1193 // this will not stop printing more than once in all cases, but it will allow us to print in all cases
1194 // and print duplicates rarely without having to synchronize
1195 static CBlockIndex *lastChainTipPrinted;
1197 miningTimer.start();
1200 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1204 waitForPeers(chainparams);
1206 pindexPrev = chainActive.LastTip();
1209 // prevent forking on startup before the diff algorithm kicks in
1210 if (pindexPrev->GetHeight() < 50 || pindexPrev != chainActive.LastTip())
1213 pindexPrev = chainActive.LastTip();
1214 MilliSleep(5000 + rand() % 5000);
1215 } while (pindexPrev != chainActive.LastTip());
1219 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1220 if ( Mining_height != pindexPrev->GetHeight()+1 )
1222 Mining_height = pindexPrev->GetHeight()+1;
1223 Mining_start = (uint32_t)time(NULL);
1226 if (lastChainTipPrinted != pindexPrev)
1228 printf("Mining height %d\n", Mining_height);
1229 lastChainTipPrinted = pindexPrev;
1232 miningTimer.start();
1234 #ifdef ENABLE_WALLET
1235 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
1237 CBlockTemplate *ptr = CreateNewBlockWithKey();
1241 static uint32_t counter;
1242 if ( counter++ < 100 )
1243 fprintf(stderr,"created illegal block, retry\n");
1247 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1248 if (!pblocktemplate.get())
1250 if (GetArg("-mineraddress", "").empty()) {
1251 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1252 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1254 // Should never reach here, because -mineraddress validity is checked in init.cpp
1255 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
1259 CBlock *pblock = &pblocktemplate->block;
1260 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1262 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1264 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1266 static uint32_t counter;
1267 if ( counter++ < 10 )
1268 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1271 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1274 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1275 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
1276 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1280 uint32_t savebits; int64_t nStart = GetTime();
1282 pblock->nSolution = solnPlaceholder;
1283 savebits = pblock->nBits;
1284 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1285 arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
1289 if ( pindexPrev != chainActive.LastTip() )
1291 if (lastChainTipPrinted != chainActive.LastTip())
1293 lastChainTipPrinted = chainActive.LastTip();
1294 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1300 if ( ASSETCHAINS_STAKED != 0 )
1303 hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);
1304 for (z=31; z>=0; z--)
1305 fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]);
1306 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1311 arith_uint256 arNonce = UintToArith256(pblock->nNonce);
1313 CVerusHashWriter ss = CVerusHashWriter(SER_GETHASH, PROTOCOL_VERSION);
1314 ss << *((CBlockHeader *)pblock);
1315 int64_t *extraPtr = ss.xI64p();
1316 CVerusHash &vh = ss.GetState();
1317 uint256 hashResult = uint256();
1319 int64_t i, count = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1;
1320 int64_t hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
1322 // for speed check NONCEMASK at a time
1323 for (i = 0; i < count; i++)
1326 vh.ExtraHash((unsigned char *)&hashResult);
1328 if ( UintToArith256(hashResult) <= hashTarget )
1330 if (pblock->nSolution.size() != 1344)
1332 LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
1337 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1339 *((int64_t *)&(pblock->nSolution.data()[pblock->nSolution.size() - 15])) = i;
1341 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1342 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1344 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1345 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1346 printf("Found block %d \n", Mining_height );
1347 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
1348 printf(" hash: %s \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
1349 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1350 printf("- timelocked until block %i\n", unlockTime);
1353 #ifdef ENABLE_WALLET
1354 ProcessBlockFound(pblock, *pwallet, reservekey);
1356 ProcessBlockFound(pblock));
1358 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1361 // check periodically if we're stale
1364 if ( pindexPrev != chainActive.LastTip() )
1366 if (lastChainTipPrinted != chainActive.LastTip())
1368 lastChainTipPrinted = chainActive.LastTip();
1369 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1373 hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
1382 // Check for stop or if block needs to be rebuilt
1383 boost::this_thread::interruption_point();
1385 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1387 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1389 fprintf(stderr,"no nodes, attempting reconnect\n");
1394 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1396 fprintf(stderr,"timeout, retrying\n");
1400 if ( pindexPrev != chainActive.LastTip() )
1402 if (lastChainTipPrinted != chainActive.LastTip())
1404 lastChainTipPrinted = chainActive.LastTip();
1405 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1411 printf("%llu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
1413 printf("%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
1420 catch (const boost::thread_interrupted&)
1423 LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1426 catch (const std::runtime_error &e)
1429 LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
1435 #ifdef ENABLE_WALLET
1436 void static BitcoinMiner(CWallet *pwallet)
1438 void static BitcoinMiner()
1441 LogPrintf("KomodoMiner started\n");
1442 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1443 RenameThread("komodo-miner");
1444 const CChainParams& chainparams = Params();
1446 #ifdef ENABLE_WALLET
1447 // Each thread has its own key
1448 CReserveKey reservekey(pwallet);
1451 // Each thread has its own counter
1452 unsigned int nExtraNonce = 0;
1454 unsigned int n = chainparams.EquihashN();
1455 unsigned int k = chainparams.EquihashK();
1456 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
1457 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
1460 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1463 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1464 komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
1465 if ( notaryid != My_notaryid )
1466 My_notaryid = notaryid;
1468 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
1470 //else solver = "default";
1471 assert(solver == "tromp" || solver == "default");
1472 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
1473 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1474 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
1476 bool cancelSolver = false;
1477 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
1478 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1479 std::lock_guard<std::mutex> lock{m_cs};
1480 cancelSolver = true;
1483 miningTimer.start();
1486 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1487 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
1490 if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
1492 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
1494 // Busy-wait for the network to come online so we don't waste time mining
1495 // on an obsolete chain. In regtest mode we expect to fly solo.
1501 fvNodesEmpty = vNodes.empty();
1503 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
1506 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
1509 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
1510 miningTimer.start();
1515 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1516 CBlockIndex* pindexPrev = chainActive.LastTip();
1517 if ( Mining_height != pindexPrev->GetHeight()+1 )
1519 Mining_height = pindexPrev->GetHeight()+1;
1520 Mining_start = (uint32_t)time(NULL);
1522 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
1524 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
1528 #ifdef ENABLE_WALLET
1529 // notaries always default to staking
1530 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
1532 CBlockTemplate *ptr = CreateNewBlockWithKey();
1536 static uint32_t counter;
1537 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1538 fprintf(stderr,"created illegal block, retry\n");
1542 //fprintf(stderr,"get template\n");
1543 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1544 if (!pblocktemplate.get())
1546 if (GetArg("-mineraddress", "").empty()) {
1547 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
1549 // Should never reach here, because -mineraddress validity is checked in init.cpp
1550 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
1554 CBlock *pblock = &pblocktemplate->block;
1555 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1557 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1559 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1561 static uint32_t counter;
1562 if ( counter++ < 10 )
1563 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1566 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1569 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1570 //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
1571 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1575 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();
1576 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
1577 savebits = pblock->nBits;
1578 HASHTarget = arith_uint256().SetCompact(savebits);
1579 roundrobin_delay = ROUNDROBIN_DELAY;
1580 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
1583 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
1585 int32_t dispflag = 0;
1586 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
1588 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
1589 if ( nonzpkeys > 0 )
1591 for (i=0; i<33; i++)
1592 if( pubkeys[0][i] != 0 )
1596 else externalflag = 0;
1597 if ( IS_KOMODO_NOTARY != 0 )
1599 for (i=1; i<66; i++)
1600 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1602 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1603 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
1604 for (j=gpucount=0; j<65; j++)
1606 if ( dispflag != 0 )
1609 fprintf(stderr,"%d ",mids[j]);
1610 else fprintf(stderr,"GPU ");
1612 if ( mids[j] == -1 )
1615 if ( dispflag != 0 )
1616 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));
1618 for (j=0; j<65; j++)
1619 if ( mids[j] == notaryid )
1622 KOMODO_LASTMINED = 0;
1623 } else fprintf(stderr,"no nonz pubkeys\n");
1624 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
1626 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
1627 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);
1628 } //else fprintf(stderr,"duplicate at j.%d\n",j);
1629 } else Mining_start = 0;
1630 } else Mining_start = 0;
1631 if ( ASSETCHAINS_STAKED != 0 )
1633 int32_t percPoS,z; bool fNegative,fOverflow;
1634 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1635 HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
1636 if ( ASSETCHAINS_STAKED < 100 )
1638 for (z=31; z>=0; z--)
1639 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1640 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1645 if ( KOMODO_INSYNC == 0 )
1647 fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
1648 if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
1653 KOMODO_CHOSEN_ONE = 0;
1655 crypto_generichash_blake2b_state state;
1656 EhInitialiseState(n, k, state);
1657 // I = the block header minus nonce and solution.
1658 CEquihashInput I{*pblock};
1659 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1662 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
1664 crypto_generichash_blake2b_state curr_state;
1666 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
1667 // (x_1, x_2, ...) = A(I, V, n, k)
1668 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
1669 arith_uint256 hashTarget;
1670 if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
1671 hashTarget = HASHTarget_POW;
1672 else hashTarget = HASHTarget;
1673 std::function<bool(std::vector<unsigned char>)> validBlock =
1674 #ifdef ENABLE_WALLET
1675 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
1677 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
1679 (std::vector<unsigned char> soln) {
1680 int32_t z; arith_uint256 h; CBlock B;
1681 // Write the solution to the hash and compute the result.
1682 LogPrint("pow", "- Checking solution against target\n");
1683 pblock->nSolution = soln;
1684 solutionTargetChecks.increment();
1686 h = UintToArith256(B.GetHash());
1687 /*for (z=31; z>=16; z--)
1688 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1689 fprintf(stderr," mined ");
1690 for (z=31; z>=16; z--)
1691 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
1692 fprintf(stderr," hashTarget ");
1693 for (z=31; z>=16; z--)
1694 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1695 fprintf(stderr," POW\n");*/
1696 if ( h > hashTarget )
1698 //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
1702 if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
1704 //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1705 while ( GetAdjustedTime() < B.nTime-2 )
1708 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
1710 fprintf(stderr,"new block arrived\n");
1715 if ( ASSETCHAINS_STAKED == 0 )
1717 if ( IS_KOMODO_NOTARY != 0 )
1720 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
1721 MilliSleep((rand() % (r * 1000)) + 1000);
1726 while ( B.nTime-57 > GetAdjustedTime() )
1729 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
1732 uint256 tmp = B.GetHash();
1733 int32_t z; for (z=31; z>=0; z--)
1734 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1735 fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
1737 CValidationState state;
1738 if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
1740 h = UintToArith256(B.GetHash());
1741 for (z=31; z>=0; z--)
1742 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1743 fprintf(stderr," Invalid block mined, try again\n");
1746 KOMODO_CHOSEN_ONE = 1;
1748 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1749 LogPrintf("KomodoMiner:\n");
1750 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
1751 #ifdef ENABLE_WALLET
1752 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
1754 if (ProcessBlockFound(&B)) {
1756 // Ignore chain updates caused by us
1757 std::lock_guard<std::mutex> lock{m_cs};
1758 cancelSolver = false;
1760 KOMODO_CHOSEN_ONE = 0;
1761 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1762 // In regression test mode, stop mining after a block is found.
1763 if (chainparams.MineBlocksOnDemand()) {
1764 // Increment here because throwing skips the call below
1765 ehSolverRuns.increment();
1766 throw boost::thread_interrupted();
1770 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1771 std::lock_guard<std::mutex> lock{m_cs};
1772 return cancelSolver;
1775 // TODO: factor this out into a function with the same API for each solver.
1776 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1777 // Create solver and initialize it.
1779 eq.setstate(&curr_state);
1781 // Initialization done, start algo driver.
1783 eq.xfull = eq.bfull = eq.hfull = 0;
1785 for (u32 r = 1; r < WK; r++) {
1786 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1787 eq.xfull = eq.bfull = eq.hfull = 0;
1791 ehSolverRuns.increment();
1793 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1794 for (size_t s = 0; s < eq.nsols; s++) {
1795 LogPrint("pow", "Checking solution %d\n", s+1);
1796 std::vector<eh_index> index_vector(PROOFSIZE);
1797 for (size_t i = 0; i < PROOFSIZE; i++) {
1798 index_vector[i] = eq.sols[s][i];
1800 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1802 if (validBlock(sol_char)) {
1803 // If we find a POW solution, do not try other solutions
1804 // because they become invalid as we created a new block in blockchain.
1810 // If we find a valid block, we rebuild
1811 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1812 ehSolverRuns.increment();
1814 int32_t i; uint256 hash = pblock->GetHash();
1815 for (i=0; i<32; i++)
1816 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1817 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1819 KOMODO_MAYBEMINED = Mining_height;
1822 } catch (EhSolverCancelledException&) {
1823 LogPrint("pow", "Equihash solver cancelled\n");
1824 std::lock_guard<std::mutex> lock{m_cs};
1825 cancelSolver = false;
1829 // Check for stop or if block needs to be rebuilt
1830 boost::this_thread::interruption_point();
1831 // Regtest mode doesn't require peers
1832 if ( FOUND_BLOCK != 0 )
1835 fprintf(stderr,"FOUND_BLOCK!\n");
1838 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1840 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1842 fprintf(stderr,"no nodes, break\n");
1846 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1848 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1849 fprintf(stderr,"0xffff, break\n");
1852 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1854 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1855 fprintf(stderr,"timeout, break\n");
1858 if ( pindexPrev != chainActive.LastTip() )
1860 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1861 fprintf(stderr,"Tip advanced, break\n");
1864 // Update nNonce and nTime
1865 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1866 pblock->nBits = savebits;
1867 /*if ( NOTARY_PUBKEY33[0] == 0 )
1870 UpdateTime(pblock, consensusParams, pindexPrev);
1871 if (consensusParams.fPowAllowMinDifficultyBlocks)
1873 // Changing pblock->nTime can change work required on testnet:
1874 HASHTarget.SetCompact(pblock->nBits);
1875 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1881 catch (const boost::thread_interrupted&)
1885 LogPrintf("KomodoMiner terminated\n");
1888 catch (const std::runtime_error &e)
1892 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1899 #ifdef ENABLE_WALLET
1900 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1902 void GenerateBitcoins(bool fGenerate, int nThreads)
1905 // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at
1906 // initialization, and this is the first time we can get it. store the Sapling address here
1907 extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
1908 extern std::string VERUS_CHEATCATCHER;
1909 libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER);
1910 if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr))
1912 cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);
1916 if (VERUS_CHEATCATCHER.size() > 0)
1917 fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n");
1920 static boost::thread_group* minerThreads = NULL;
1923 nThreads = GetNumCores();
1925 if (minerThreads != NULL)
1927 minerThreads->interrupt_all();
1928 delete minerThreads;
1929 minerThreads = NULL;
1932 //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
1933 if ( nThreads == 0 && ASSETCHAINS_STAKED )
1936 if ((nThreads == 0 || !fGenerate) && (VERUS_MINTBLOCKS == 0 || pwallet == NULL))
1939 minerThreads = new boost::thread_group();
1941 #ifdef ENABLE_WALLET
1942 if (ASSETCHAINS_LWMAPOS != 0 && VERUS_MINTBLOCKS)
1944 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
1948 for (int i = 0; i < nThreads; i++) {
1950 #ifdef ENABLE_WALLET
1951 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1952 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1954 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
1956 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1957 minerThreads->create_thread(&BitcoinMiner);
1959 minerThreads->create_thread(&BitcoinMiner_noeq);
1964 #endif // ENABLE_MINING