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>
50 #include "pbaas/pbaas.h"
51 #include "pbaas/notarization.h"
55 //////////////////////////////////////////////////////////////////////////////
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.
71 const CTransaction* ptx;
72 set<uint256> setDependsOn;
76 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
81 uint64_t nLastBlockTx = 0;
82 uint64_t nLastBlockSize = 0;
84 // We want to sort transactions by priority and fee rate, so:
85 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
86 class TxPriorityCompare
91 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
93 bool operator()(const TxPriority& a, const TxPriority& b)
97 if (a.get<1>() == b.get<1>())
98 return a.get<0>() < b.get<0>();
99 return a.get<1>() < b.get<1>();
103 if (a.get<0>() == b.get<0>())
104 return a.get<1>() < b.get<1>();
105 return a.get<0>() < b.get<0>();
110 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
112 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
114 // Updating time can change work required on testnet:
115 if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {
116 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
120 #include "komodo_defs.h"
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);
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);
148 CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
150 CScript scriptPubKeyIn(_scriptPubKeyIn);
152 CPubKey pk = CPubKey();
153 std::vector<std::vector<unsigned char>> vAddrs;
155 if (Solver(scriptPubKeyIn, txT, vAddrs))
157 if (txT == TX_PUBKEY)
158 pk = CPubKey(vAddrs[0]);
161 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
162 //fprintf(stderr,"create new block\n");
165 gpucount = KOMODO_MAXGPUCOUNT;
166 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
167 if(!pblocktemplate.get())
169 fprintf(stderr,"pblocktemplate.get() failure\n");
172 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
174 // set version according to the current tip height, add solution if it is
176 if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH)
178 pblock->nSolution.resize(Eh200_9.SolutionWidth);
182 pblock->nSolution.clear();
184 pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1);
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);
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
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));
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);
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);
211 // Collect memory pool transactions into the block
214 // we will attempt to spend any cheats we see
215 CTransaction cheatTx;
216 boost::optional<CTransaction> cheatSpend;
219 CBlockIndex* pindexPrev = 0;
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);
228 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
229 uint32_t proposedTime = GetAdjustedTime();
230 if (proposedTime == nMedianTimePast)
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++)
236 proposedTime = GetAdjustedTime();
237 if (proposedTime == nMedianTimePast)
241 pblock->nTime = GetAdjustedTime();
243 CCoinsViewCache view(pcoinsTip);
244 uint32_t expired; uint64_t commission;
246 SaplingMerkleTree sapling_tree;
247 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
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);
254 // This vector will be sorted into a priority queue:
255 vector<TxPriority> vecPriority;
256 vecPriority.reserve(mempool.mapTx.size() + 1);
258 // check if we should add cheat transaction
261 int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;
263 sapling && chainActive.Height() > 100 &&
264 (ppast = chainActive[cheatHeight]) &&
265 ppast->IsVerusPOSBlock() &&
266 cheatList.IsHeightOrGreaterInList(cheatHeight))
268 // get the block and see if there is a cheat candidate for the stake tx
270 if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, 1))
272 CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];
274 if (cheatList.IsCheatInList(stakeTx, &cheatTx))
276 // make and sign the cheat transaction to spend the coinbase to our address
277 CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
280 // get the first vout with value
281 for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)
283 if (b.vtx[0].vout[voutNum].nValue > 0)
287 // send to the same pub key as the destination of this block reward
288 if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))
290 extern CWallet *pwalletMain;
291 LOCK(pwalletMain->cs_wallet);
292 TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);
294 cbHash = cb.GetHash();
296 bool hasInput = false;
297 for (uint32_t i = 0; i < cb.vout.size(); i++)
299 // add the spends with the cheat
300 if (cb.vout[i].nValue > 0)
302 tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);
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.
315 if (pwalletMain->GetHDSeed(seed)) {
316 ovk = ovkForShieldingFromTaddr(seed);
318 // send everything to Sapling address
319 tb.SendChangeTo(cheatCatcher.value(), ovk);
321 tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);
323 cheatSpend = tb.Build();
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());
339 // add to mem pool and relay
340 if (myAddtomempool(cheatTx))
342 RelayTransaction(cheatTx);
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())
350 if (nHeight != 1 || ConnectedChains.IsVerusPBaaSAvailable())
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))
359 // we have a valid, earned notarization transaction. we may need to combine it with the coinbase if it is
365 // can't mine block 1 unless we have a connection to Verus and can notarize
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)
374 const CTransaction& tx = mi->GetTx();
376 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
378 : pblock->GetBlockTime();
380 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
382 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
386 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
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);
392 COrphan* porphan = NULL;
393 double dPriority = 0;
394 CAmount nTotalIn = 0;
395 bool fMissingInputs = false;
396 if (tx.IsCoinImport())
398 CAmount nValueIn = GetCoinImportValue(tx);
399 nTotalIn += nValueIn;
400 dPriority += (double)nValueIn * 1000; // flat multiplier
402 BOOST_FOREACH(const CTxIn& txin, tx.vin)
404 // Read prev transaction
405 if (!view.HaveCoins(txin.prevout.hash))
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))
412 LogPrintf("ERROR: mempool transaction missing input\n");
413 if (fDebug) assert("mempool transaction missing input" == 0);
414 fMissingInputs = true;
420 // Has to wait for dependencies
423 // Use list for automatic deletion
424 vOrphan.push_back(COrphan(&tx));
425 porphan = &vOrphan.back();
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;
432 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
435 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
436 nTotalIn += nValueIn;
438 int nConf = nHeight - coins->nHeight;
440 dPriority += (double)nValueIn * nConf;
442 nTotalIn += tx.GetShieldedValueIn();
445 if (fMissingInputs) continue;
447 // Priority is sum(valuein * age) / modified_txsize
448 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
449 dPriority = tx.ComputePriority(dPriority, nTxSize);
451 uint256 hash = tx.GetHash();
452 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
454 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
458 porphan->dPriority = dPriority;
459 porphan->feeRate = feeRate;
462 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
465 // Collect transactions into block
466 uint64_t nBlockSize = 1000;
467 uint64_t nBlockTx = 0;
469 int nBlockSigOps = 100;
470 bool fSortedByFee = (nBlockPrioritySize <= 0);
472 TxPriorityCompare comparer(fSortedByFee);
473 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
475 while (!vecPriority.empty())
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>());
482 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
483 vecPriority.pop_back();
486 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
487 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
489 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
493 // Legacy limits on sigOps:
494 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
495 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
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);
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))
507 //fprintf(stderr,"fee rate skip\n");
510 // Prioritise by fee once past the priority size or we run out of high-priority
513 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
516 comparer = TxPriorityCompare(fSortedByFee);
517 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
520 if (!view.HaveInputs(tx))
522 //fprintf(stderr,"dont have inputs\n");
525 CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();
527 nTxSigOps += GetP2SHSigOpCount(tx, view);
528 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
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);
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))
540 //fprintf(stderr,"context failure\n");
543 UpdateCoins(tx, view, nHeight);
545 BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
546 sapling_tree.append(outDescription.cm);
550 pblock->vtx.push_back(tx);
551 pblocktemplate->vTxFees.push_back(nTxFees);
552 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
553 nBlockSize += nTxSize;
555 nBlockSigOps += nTxSigOps;
560 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
563 // Add transactions that depend on this one to the priority queue
564 if (mapDependers.count(hash))
566 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
568 if (!porphan->setDependsOn.empty())
570 porphan->setDependsOn.erase(hash);
571 if (porphan->setDependsOn.empty())
573 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
574 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
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());
587 int32_t stakeHeight = chainActive.Height() + 1;
589 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
590 if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
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);
595 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
596 // blocktime = pindexPrev->GetMedianTimePast() + 60;
597 if (ASSETCHAINS_LWMAPOS != 0)
600 arith_uint256 posHash;
602 siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);
603 blocktime = GetAdjustedTime();
605 // change the scriptPubKeyIn to the same output script exactly as the staking transaction
607 scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
611 siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
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;
622 pblock->vtx.push_back(txStaked);
623 pblocktemplate->vTxFees.push_back(txfees);
624 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
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");
631 // Create coinbase tx
632 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
634 txNew.vin[0].prevout.SetNull();
635 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
637 txNew.vout.resize(1);
638 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
639 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,consensusParams) + nFees;
641 // once we get to Sapling, enable CC StakeGuard for stake transactions
642 if (isStake && sapling)
644 // if there is a specific destination, use it
645 CTransaction stakeTx = pblock->vtx[pblock->vtx.size() - 1];
647 if (ValidateStakeTransaction(stakeTx, p, false))
649 if (!p.pk.IsValid() || !MakeGuardedOutput(txNew.vout[0].nValue, p.pk, stakeTx, txNew.vout[0]))
651 fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
657 fprintf(stderr,"CreateNewBlock: invalid stake transaction\n");
662 txNew.nExpiryHeight = 0;
663 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
665 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
666 txNew.vout[0].nValue += 5000;
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)
672 int32_t opretlen, p2shlen, scriptlen;
673 CScriptExt opretScript = CScriptExt();
675 txNew.vout.resize(2);
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())
682 fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
686 opretScript += scriptPubKeyIn;
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 )
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];
701 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
702 ptr[34] = OP_CHECKSIG;
703 //printf("autocreate commision vout\n");
706 pblock->vtx[0] = txNew;
707 pblocktemplate->vTxFees[0] = -nFees;
709 // if not Verus stake, setup nonce, otherwise, leave it alone
710 if (!isStake || ASSETCHAINS_LWMAPOS == 0)
713 arith_uint256 nonce = UintToArith256(GetRandHash());
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];
718 pblock->nNonce = ArithToUint256(nonce);
722 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
723 pblock->hashFinalSaplingRoot = sapling_tree.root();
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 )
728 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
729 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
732 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
733 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
736 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
737 if ( pblock->nTime < pindexPrev->nTime+60 )
738 pblock->nTime = pindexPrev->nTime + 60;
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));
749 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
751 CAmount txfees = 5000;
752 pblock->vtx.push_back(txNotary);
753 pblocktemplate->vTxFees.push_back(txfees);
754 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
756 pblocktemplate->vTxFees[0] = -nFees;
757 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
758 //fprintf(stderr,"added notaryvin\n");
762 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
766 else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
768 CValidationState state;
769 //fprintf(stderr,"check validity\n");
770 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
772 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
774 //fprintf(stderr,"valid\n");
777 //fprintf(stderr,"done new block\n");
778 return pblocktemplate.release();
783 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
785 boost::optional<CScript> GetMinerScriptPubKey()
789 CBitcoinAddress addr;
790 if (addr.SetString(GetArg("-mineraddress", ""))) {
791 addr.GetKeyID(keyID);
795 if (!reservekey.GetReservedKey(pubkey)) {
796 return boost::optional<CScript>();
798 keyID = pubkey.GetID();
800 return boost::optional<CScript>();
804 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
809 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
811 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
813 CBlockTemplate* CreateNewBlockWithKey()
815 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
821 return CreateNewBlock(*scriptPubKey);
824 //////////////////////////////////////////////////////////////////////////////
831 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
833 // Update nExtraNonce
834 static uint256 hashPrevBlock;
835 if (hashPrevBlock != pblock->hashPrevBlock)
838 hashPrevBlock = pblock->hashPrevBlock;
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);
846 pblock->vtx[0] = txCoinbase;
847 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
851 //////////////////////////////////////////////////////////////////////////////
856 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
858 CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;
859 if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
861 scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
863 else if ( USE_EXTERNAL_PUBKEY != 0 )
865 //fprintf(stderr,"use notary pubkey\n");
866 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
872 if (!reservekey.GetReservedKey(pubkey))
876 scriptPubKey.resize(35);
877 ptr = (uint8_t *)pubkey.begin();
878 scriptPubKey[0] = 33;
880 scriptPubKey[i+1] = ptr[i];
881 scriptPubKey[34] = OP_CHECKSIG;
882 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
885 return CreateNewBlock(scriptPubKey, gpucount, isStake);
888 void komodo_broadcast(CBlock *pblock,int32_t limit)
891 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
894 BOOST_FOREACH(CNode* pnode, vNodes)
896 if ( pnode->hSocket == INVALID_SOCKET )
898 if ( (rand() % n) == 0 )
900 pnode->PushMessage("block", *pblock);
906 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
909 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
911 static bool ProcessBlockFound(CBlock* pblock)
912 #endif // ENABLE_WALLET
914 LogPrintf("%s\n", pblock->ToString());
915 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1);
919 if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
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");
931 return error("KomodoMiner: generated block is stale");
936 // Remove key from key pool
937 if ( IS_KOMODO_NOTARY == 0 )
939 if (GetArg("-mineraddress", "").empty()) {
940 // Remove key from key pool
941 reservekey.KeepKey();
944 // Track how many getdata requests this block gets
947 //fprintf(stderr,"lock cs_wallet\n");
948 LOCK(wallet.cs_wallet);
949 wallet.mapRequestCount[pblock->GetHash()] = 0;
952 //fprintf(stderr,"process new block\n");
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");
959 TrackMinedBlock(pblock->GetHash());
960 komodo_broadcast(pblock,16);
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();
973 // wait for peers to connect
974 void waitForPeers(const CChainParams &chainparams)
976 if (chainparams.MiningRequiresPeers())
980 boost::this_thread::interruption_point();
982 fvNodesEmpty = vNodes.empty();
984 int longestchain = komodo_longestchain();
986 if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight()))
988 int loops = 0, blockDiff = 0, newDiff = 0;
993 MilliSleep(1000 + rand() % 4000);
994 boost::this_thread::interruption_point();
996 fvNodesEmpty = vNodes.empty();
1001 else if ((newDiff = IsNotInSync()) > 0)
1003 if (blockDiff != newDiff)
1005 blockDiff = newDiff;
1017 else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight())
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)
1024 lastlongest = longestchain;
1027 } while (fvNodesEmpty || IsNotInSync());
1028 MilliSleep(100 + rand() % 400);
1033 #ifdef ENABLE_WALLET
1034 CBlockIndex *get_chainactive(int32_t height)
1036 if ( chainActive.LastTip() != 0 )
1038 if ( height <= chainActive.LastTip()->GetHeight() )
1041 return(chainActive[height]);
1043 // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight());
1045 //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height);
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
1054 void static UpdateNotarizationData()
1060 * A separate thread to stake, while the miner threads mine.
1062 void static VerusStaker(CWallet *pwallet)
1064 LogPrintf("Verus staker thread started\n");
1065 RenameThread("verus-staker");
1067 const CChainParams& chainparams = Params();
1068 auto consensusParams = chainparams.GetConsensus();
1070 // Each thread has its own key
1071 CReserveKey reservekey(pwallet);
1073 // Each thread has its own counter
1074 unsigned int nExtraNonce = 0;
1076 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1078 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
1081 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1085 // try a nice clean peer connection to start
1086 CBlockIndex *pindexPrev, *pindexCur;
1088 pindexPrev = chainActive.LastTip();
1089 MilliSleep(5000 + rand() % 5000);
1090 waitForPeers(chainparams);
1091 pindexCur = chainActive.LastTip();
1092 } while (pindexPrev != pindexCur);
1095 static int32_t lastStakingHeight = 0;
1099 waitForPeers(chainparams);
1100 CBlockIndex* pindexPrev = chainActive.LastTip();
1102 // TODO: update notarization data if this is a PBaaS chain, and there is a Verus daemon available
1105 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1107 if ( Mining_height != pindexPrev->GetHeight()+1 )
1109 Mining_height = pindexPrev->GetHeight()+1;
1110 Mining_start = (uint32_t)time(NULL);
1113 if ( Mining_height != lastStakingHeight )
1115 printf("Staking height %d for %s\n", Mining_height, ASSETCHAINS_SYMBOL);
1116 lastStakingHeight = Mining_height;
1119 // Check for stop or if block needs to be rebuilt
1120 boost::this_thread::interruption_point();
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);
1129 // wait to try another staking block until after the tip moves again
1130 while ( chainActive.LastTip() == pindexPrev )
1135 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1136 if (!pblocktemplate.get())
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]);
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);
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));
1153 int64_t nStart = GetTime();
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);
1159 // update PBaaS header
1160 if (CConstVerusSolutionVector::activationHeight.ActiveVersion(Mining_height) == CActivationHeight::SOLUTION_VERUSV3)
1162 // set the PBaaS header
1166 ChainMerkleMountainView mmv(chainActive.GetMMR(), pindexPrev->GetHeight());
1167 mmvRoot = mmv.GetRoot();
1168 pblock->AddUpdatePBaaSHeader(mmvRoot);
1172 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1174 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1176 fprintf(stderr,"no nodes, attempting reconnect\n");
1181 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1183 fprintf(stderr,"timeout, retrying\n");
1187 if ( pindexPrev != chainActive.LastTip() )
1189 printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight());
1194 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1195 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1197 uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
1199 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
1201 UpdateTime(pblock, consensusParams, pindexPrev);
1203 ProcessBlockFound(pblock, *pwallet, reservekey);
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);
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);
1220 // Check for stop or if block needs to be rebuilt
1221 boost::this_thread::interruption_point();
1225 // In regression test mode, stop mining after a block is found.
1226 if (chainparams.MineBlocksOnDemand()) {
1227 throw boost::thread_interrupted();
1231 catch (const boost::thread_interrupted&)
1233 LogPrintf("VerusStaker terminated\n");
1236 catch (const std::runtime_error &e)
1238 LogPrintf("VerusStaker runtime error: %s\n", e.what());
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);
1247 void static BitcoinMiner_noeq(CWallet *pwallet)
1249 void static BitcoinMiner_noeq()
1252 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1253 RenameThread("verushash-miner");
1255 #ifdef ENABLE_WALLET
1256 // Each thread has its own key
1257 CReserveKey reservekey(pwallet);
1260 const CChainParams& chainparams = Params();
1261 // Each thread has its own counter
1262 unsigned int nExtraNonce = 0;
1264 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1266 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
1269 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1273 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1275 // try a nice clean peer connection to start
1276 CBlockIndex *pindexPrev, *pindexCur;
1278 pindexPrev = chainActive.LastTip();
1279 MilliSleep(5000 + rand() % 5000);
1280 waitForPeers(chainparams);
1281 pindexCur = chainActive.LastTip();
1282 } while (pindexPrev != pindexCur);
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;
1289 miningTimer.start();
1292 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1295 CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION);
1300 waitForPeers(chainparams);
1302 pindexPrev = chainActive.LastTip();
1305 // prevent forking on startup before the diff algorithm kicks in
1306 if (chainparams.MiningRequiresPeers() && (pindexPrev->GetHeight() < 50 || pindexPrev != chainActive.LastTip()))
1309 pindexPrev = chainActive.LastTip();
1310 MilliSleep(5000 + rand() % 5000);
1311 } while (pindexPrev != chainActive.LastTip());
1315 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1316 if ( Mining_height != pindexPrev->GetHeight()+1 )
1318 Mining_height = pindexPrev->GetHeight()+1;
1319 if (lastMiningHeight != Mining_height)
1321 lastMiningHeight = Mining_height;
1322 printf("Mining height %d\n", Mining_height);
1324 Mining_start = (uint32_t)time(NULL);
1327 miningTimer.start();
1329 #ifdef ENABLE_WALLET
1330 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
1332 CBlockTemplate *ptr = CreateNewBlockWithKey();
1336 static uint32_t counter;
1337 if ( counter++ < 100 )
1338 fprintf(stderr,"created illegal block, retry\n");
1342 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1343 if (!pblocktemplate.get())
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]);
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);
1354 CBlock *pblock = &pblocktemplate->block;
1355 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1357 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1359 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1361 static uint32_t counter;
1362 if ( counter++ < 10 )
1363 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
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);
1370 // this builds the Merkle tree
1371 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1373 // update PBaaS header
1374 if (CConstVerusSolutionVector::activationHeight.ActiveVersion(Mining_height) == CActivationHeight::SOLUTION_VERUSV3)
1376 // set the PBaaS header
1380 ChainMerkleMountainView mmv(chainActive.GetMMR(), pindexPrev->GetHeight());
1381 mmvRoot = mmv.GetRoot();
1382 pblock->AddUpdatePBaaSHeader(mmvRoot);
1384 // tests to validate a few transactions and all past blocks
1385 for (uint32_t i = 1; i <= pindexPrev->GetHeight(); i += 10)
1387 CBlockIndex *pindex = chainActive[i - 1];
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)
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);
1402 for (auto bit : proofBits)
1404 printf("%s\n", bit ? "left" : "right");
1407 if (blockAnswer != testRoot)
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);
1413 for (auto bit : proofBits)
1415 printf("%s\n", bit ? "left" : "right");
1418 const CMMRPowerNode *ppower = mmv.GetRootNode();
1419 if (!ppower || ppower->Work() != pindex->chainPower.chainWork)
1421 printf("Work did not match:\nexpected: %s\ncalculated: %s\n", ArithToUint256(pindex->chainPower.chainWork).GetHex().c_str(), ArithToUint256(ppower->Work()).GetHex().c_str());
1423 if (!ppower || ppower->Stake() != pindex->chainPower.chainStake)
1425 printf("Stake did not match:\nexpected: %s\ncalculated: %s\n", ArithToUint256(pindex->chainPower.chainStake).GetHex().c_str(), ArithToUint256(ppower->Stake()).GetHex().c_str());
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));
1436 uint32_t savebits; int64_t nStart = GetTime();
1438 savebits = pblock->nBits;
1439 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1440 uint256 uintTarget = ArithToUint256(hashTarget);
1443 if ( pindexPrev != chainActive.LastTip() )
1445 if (lastChainTipPrinted != chainActive.LastTip())
1447 lastChainTipPrinted = chainActive.LastTip();
1448 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1454 if ( ASSETCHAINS_STAKED != 0 )
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);
1463 uint64_t count, hashesToGo;
1464 bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2;
1467 // must not be in sync
1468 printf("Mining on incorrect block version.\n");
1473 count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
1474 CVerusHashV2 *vh2 = &ss2.GetState();
1476 verusclhasher &vclh = vh2->vclh;
1477 minefunction mine_verus;
1478 mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port;
1482 uint256 hashResult = uint256();
1484 unsigned char *curBuf;
1486 // check NONCEMASK at a time
1487 for (uint64_t i = 0; i < count; i++)
1489 hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
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))
1495 // Check for stop or if block needs to be rebuilt
1496 boost::this_thread::interruption_point();
1497 if ( pindexPrev != chainActive.LastTip() )
1499 if (lastChainTipPrinted != chainActive.LastTip())
1501 lastChainTipPrinted = chainActive.LastTip();
1502 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1510 nHashCount += hashesToGo;
1517 // Check for stop or if block needs to be rebuilt
1518 boost::this_thread::interruption_point();
1520 if (pblock->nSolution.size() != 1344)
1522 LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
1526 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1528 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1529 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
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;
1537 std::string hashStr = hashResult.GetHex();
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());
1552 printf(" hash: %s\ntarget: %s", hashStr.c_str(), hashTarget.GetHex().c_str());
1554 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1555 printf(" - timelocked until block %i\n", unlockTime);
1558 #ifdef ENABLE_WALLET
1559 ProcessBlockFound(pblock, *pwallet, reservekey);
1561 ProcessBlockFound(pblock);
1563 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1570 nHashCount += hashesToGo;
1573 // Check for stop or if block needs to be rebuilt
1574 boost::this_thread::interruption_point();
1576 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1578 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1580 fprintf(stderr,"no nodes, attempting reconnect\n");
1585 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1587 fprintf(stderr,"timeout, retrying\n");
1591 if ( pindexPrev != chainActive.LastTip() )
1593 if (lastChainTipPrinted != chainActive.LastTip())
1595 lastChainTipPrinted = chainActive.LastTip();
1596 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
1602 printf("%llu mega hashes complete - working\n", ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / 1048576);
1604 printf("%lu mega hashes complete - working\n", ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / 1048576);
1611 catch (const boost::thread_interrupted&)
1614 LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1617 catch (const std::runtime_error &e)
1620 LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
1626 #ifdef ENABLE_WALLET
1627 void static BitcoinMiner(CWallet *pwallet)
1629 void static BitcoinMiner()
1632 LogPrintf("KomodoMiner started\n");
1633 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1634 RenameThread("komodo-miner");
1635 const CChainParams& chainparams = Params();
1637 #ifdef ENABLE_WALLET
1638 // Each thread has its own key
1639 CReserveKey reservekey(pwallet);
1642 // Each thread has its own counter
1643 unsigned int nExtraNonce = 0;
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) )
1651 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1654 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1655 komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
1656 if ( notaryid != My_notaryid )
1657 My_notaryid = notaryid;
1659 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
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());
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;
1674 miningTimer.start();
1677 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1678 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
1681 if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
1683 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
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.
1692 fvNodesEmpty = vNodes.empty();
1694 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
1697 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
1700 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
1701 miningTimer.start();
1706 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1707 CBlockIndex* pindexPrev = chainActive.LastTip();
1708 if ( Mining_height != pindexPrev->GetHeight()+1 )
1710 Mining_height = pindexPrev->GetHeight()+1;
1711 Mining_start = (uint32_t)time(NULL);
1713 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
1715 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
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);
1723 CBlockTemplate *ptr = CreateNewBlockWithKey();
1727 static uint32_t counter;
1728 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1729 fprintf(stderr,"created illegal block, retry\n");
1733 //fprintf(stderr,"get template\n");
1734 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1735 if (!pblocktemplate.get())
1737 if (GetArg("-mineraddress", "").empty()) {
1738 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
1740 // Should never reach here, because -mineraddress validity is checked in init.cpp
1741 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
1745 CBlock *pblock = &pblocktemplate->block;
1746 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1748 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1750 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1752 static uint32_t counter;
1753 if ( counter++ < 10 )
1754 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
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);
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));
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 )
1774 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
1776 int32_t dispflag = 0;
1777 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
1779 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
1780 if ( nonzpkeys > 0 )
1782 for (i=0; i<33; i++)
1783 if( pubkeys[0][i] != 0 )
1787 else externalflag = 0;
1788 if ( IS_KOMODO_NOTARY != 0 )
1790 for (i=1; i<66; i++)
1791 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
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++)
1797 if ( dispflag != 0 )
1800 fprintf(stderr,"%d ",mids[j]);
1801 else fprintf(stderr,"GPU ");
1803 if ( mids[j] == -1 )
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));
1809 for (j=0; j<65; j++)
1810 if ( mids[j] == notaryid )
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) )
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 )
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 )
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);
1836 if ( KOMODO_INSYNC == 0 )
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 )
1844 KOMODO_CHOSEN_ONE = 0;
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);
1853 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
1855 crypto_generichash_blake2b_state curr_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]
1868 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
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();
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 )
1889 //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
1893 if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
1895 //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1896 while ( GetAdjustedTime() < B.nTime-2 )
1899 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
1901 fprintf(stderr,"new block arrived\n");
1906 if ( ASSETCHAINS_STAKED == 0 )
1908 if ( IS_KOMODO_NOTARY != 0 )
1911 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
1912 MilliSleep((rand() % (r * 1000)) + 1000);
1917 while ( B.nTime-57 > GetAdjustedTime() )
1920 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
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);
1928 CValidationState state;
1929 if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
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");
1937 KOMODO_CHOSEN_ONE = 1;
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)) {
1945 if (ProcessBlockFound(&B)) {
1947 // Ignore chain updates caused by us
1948 std::lock_guard<std::mutex> lock{m_cs};
1949 cancelSolver = false;
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();
1961 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1962 std::lock_guard<std::mutex> lock{m_cs};
1963 return cancelSolver;
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.
1970 eq.setstate(&curr_state);
1972 // Initialization done, start algo driver.
1974 eq.xfull = eq.bfull = eq.hfull = 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;
1982 ehSolverRuns.increment();
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];
1991 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
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.
2001 // If we find a valid block, we rebuild
2002 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
2003 ehSolverRuns.increment();
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);
2010 KOMODO_MAYBEMINED = Mining_height;
2013 } catch (EhSolverCancelledException&) {
2014 LogPrint("pow", "Equihash solver cancelled\n");
2015 std::lock_guard<std::mutex> lock{m_cs};
2016 cancelSolver = false;
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 )
2026 fprintf(stderr,"FOUND_BLOCK!\n");
2029 if (vNodes.empty() && chainparams.MiningRequiresPeers())
2031 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
2033 fprintf(stderr,"no nodes, break\n");
2037 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
2039 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2040 fprintf(stderr,"0xffff, break\n");
2043 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2045 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2046 fprintf(stderr,"timeout, break\n");
2049 if ( pindexPrev != chainActive.LastTip() )
2051 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2052 fprintf(stderr,"Tip advanced, break\n");
2055 // Update nNonce and nTime
2056 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
2057 pblock->nBits = savebits;
2058 /*if ( NOTARY_PUBKEY33[0] == 0 )
2061 UpdateTime(pblock, consensusParams, pindexPrev);
2062 if (consensusParams.fPowAllowMinDifficultyBlocks)
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);
2072 catch (const boost::thread_interrupted&)
2076 LogPrintf("KomodoMiner terminated\n");
2079 catch (const std::runtime_error &e)
2083 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
2090 #ifdef ENABLE_WALLET
2091 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
2093 void GenerateBitcoins(bool fGenerate, int nThreads)
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))
2105 cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);
2112 VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0);
2114 if (fGenerate == true || VERUS_MINTBLOCKS)
2116 mapArgs["-gen"] = "1";
2118 if (VERUS_CHEATCATCHER.size() > 0)
2120 if (cheatCatcher == boost::none)
2122 LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n");
2123 fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n");
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());
2133 static boost::thread_group* minerThreads = NULL;
2136 nThreads = GetNumCores();
2138 if (minerThreads != NULL)
2140 minerThreads->interrupt_all();
2141 delete minerThreads;
2142 minerThreads = NULL;
2145 //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
2146 if ( nThreads == 0 && ASSETCHAINS_STAKED )
2152 minerThreads = new boost::thread_group();
2154 #ifdef ENABLE_WALLET
2155 if (VERUS_MINTBLOCKS && pwallet != NULL)
2157 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
2161 for (int i = 0; i < nThreads; i++) {
2163 #ifdef ENABLE_WALLET
2164 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
2165 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
2167 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
2169 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
2170 minerThreads->create_thread(&BitcoinMiner);
2172 minerThreads->create_thread(&BitcoinMiner_noeq);
2177 #endif // ENABLE_MINING