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.
7 #include "pow/tromp/equi_miner.h"
10 #include "chainparams.h"
11 #include "consensus/consensus.h"
12 #include "consensus/validation.h"
18 #include "primitives/transaction.h"
22 #include "utilmoneystr.h"
24 #include "crypto/equihash.h"
25 #include "wallet/wallet.h"
31 #include <boost/thread.hpp>
32 #include <boost/tuple/tuple.hpp>
37 //////////////////////////////////////////////////////////////////////////////
43 // Unconfirmed transactions in the memory pool often depend on other
44 // transactions in the memory pool. When we select transactions from the
45 // pool, we select by highest priority or fee rate, so we might consider
46 // transactions that depend on transactions that aren't yet in the block.
47 // The COrphan class keeps track of these 'temporary orphans' while
48 // CreateBlock is figuring out which transactions to include.
53 const CTransaction* ptx;
54 set<uint256> setDependsOn;
58 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
63 uint64_t nLastBlockTx = 0;
64 uint64_t nLastBlockSize = 0;
66 // We want to sort transactions by priority and fee rate, so:
67 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
68 class TxPriorityCompare
73 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
75 bool operator()(const TxPriority& a, const TxPriority& b)
79 if (a.get<1>() == b.get<1>())
80 return a.get<0>() < b.get<0>();
81 return a.get<1>() < b.get<1>();
85 if (a.get<0>() == b.get<0>())
86 return a.get<1>() < b.get<1>();
87 return a.get<0>() < b.get<0>();
92 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
94 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
96 // Updating time can change work required on testnet:
97 if (consensusParams.fPowAllowMinDifficultyBlocks)
98 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
101 #define ASSETCHAINS_MINHEIGHT 100
102 #define KOMODO_ELECTION_GAP 2000
103 #define ROUNDROBIN_DELAY 57
104 extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE;
105 extern char ASSETCHAINS_SYMBOL[16];
106 extern std::string NOTARY_PUBKEY;
107 extern uint8_t NOTARY_PUBKEY33[33];
108 uint32_t Mining_start,Mining_height;
109 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33);
110 int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]);
111 int32_t komodo_pax_opreturn(uint8_t *opret,int32_t maxsize);
112 uint64_t komodo_paxtotal();
113 int32_t komodo_baseid(char *origbase);
114 int32_t komodo_is_issuer();
115 int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
116 int32_t komodo_isrealtime(int32_t *kmdheightp);
118 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
120 uint64_t deposits; int32_t isrealtime,kmdheight; const CChainParams& chainparams = Params();
122 unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
123 if(!pblocktemplate.get())
125 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
126 if ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
128 isrealtime = komodo_isrealtime(&kmdheight);
129 deposits = komodo_paxtotal();
130 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
132 deposits = komodo_paxtotal();
133 if ( KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
135 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
137 else if ( deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0 )
139 fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND);
144 KOMODO_ON_DEMAND = 0;
145 if ( 0 && deposits != 0 )
146 printf("miner KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)komodo_paxtotal(),(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
148 // -regtest only: allow overriding block.nVersion with
149 // -blockversion=N to test forking scenarios
150 if (Params().MineBlocksOnDemand())
151 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
153 // Add dummy coinbase tx as first transaction
154 pblock->vtx.push_back(CTransaction());
155 pblocktemplate->vTxFees.push_back(-1); // updated at end
156 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
158 // Largest block you're willing to create:
159 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
160 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
161 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
163 // How much of the block should be dedicated to high-priority transactions,
164 // included regardless of the fees they pay
165 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
166 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
168 // Minimum block size you want to create; block will be filled with free transactions
169 // until there are no more or the block reaches this size:
170 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
171 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
173 // Collect memory pool transactions into the block
177 LOCK2(cs_main, mempool.cs);
178 CBlockIndex* pindexPrev = chainActive.Tip();
179 const int nHeight = pindexPrev->nHeight + 1;
180 pblock->nTime = GetAdjustedTime();
181 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
182 CCoinsViewCache view(pcoinsTip);
184 // Priority order to process transactions
185 list<COrphan> vOrphan; // list memory doesn't move
186 map<uint256, vector<COrphan*> > mapDependers;
187 bool fPrintPriority = GetBoolArg("-printpriority", false);
189 // This vector will be sorted into a priority queue:
190 vector<TxPriority> vecPriority;
191 vecPriority.reserve(mempool.mapTx.size());
192 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
193 mi != mempool.mapTx.end(); ++mi)
195 const CTransaction& tx = mi->second.GetTx();
197 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
199 : pblock->GetBlockTime();
201 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
204 COrphan* porphan = NULL;
205 double dPriority = 0;
206 CAmount nTotalIn = 0;
207 bool fMissingInputs = false;
208 BOOST_FOREACH(const CTxIn& txin, tx.vin)
210 // Read prev transaction
211 if (!view.HaveCoins(txin.prevout.hash))
213 // This should never happen; all transactions in the memory
214 // pool should connect to either transactions in the chain
215 // or other transactions in the memory pool.
216 if (!mempool.mapTx.count(txin.prevout.hash))
218 LogPrintf("ERROR: mempool transaction missing input\n");
219 if (fDebug) assert("mempool transaction missing input" == 0);
220 fMissingInputs = true;
226 // Has to wait for dependencies
229 // Use list for automatic deletion
230 vOrphan.push_back(COrphan(&tx));
231 porphan = &vOrphan.back();
233 mapDependers[txin.prevout.hash].push_back(porphan);
234 porphan->setDependsOn.insert(txin.prevout.hash);
235 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
238 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
241 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
242 nTotalIn += nValueIn;
244 int nConf = nHeight - coins->nHeight;
246 dPriority += (double)nValueIn * nConf;
248 nTotalIn += tx.GetJoinSplitValueIn();
250 if (fMissingInputs) continue;
252 // Priority is sum(valuein * age) / modified_txsize
253 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
254 dPriority = tx.ComputePriority(dPriority, nTxSize);
256 uint256 hash = tx.GetHash();
257 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
259 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
263 porphan->dPriority = dPriority;
264 porphan->feeRate = feeRate;
267 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
270 // Collect transactions into block
271 uint64_t nBlockSize = 1000;
272 uint64_t nBlockTx = 0;
274 int nBlockSigOps = 100;
275 bool fSortedByFee = (nBlockPrioritySize <= 0);
277 TxPriorityCompare comparer(fSortedByFee);
278 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
280 while (!vecPriority.empty())
282 // Take highest priority transaction off the priority queue:
283 double dPriority = vecPriority.front().get<0>();
284 CFeeRate feeRate = vecPriority.front().get<1>();
285 const CTransaction& tx = *(vecPriority.front().get<2>());
287 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
288 vecPriority.pop_back();
291 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
292 if (nBlockSize + nTxSize >= nBlockMaxSize)
295 // Legacy limits on sigOps:
296 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
297 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
300 // Skip free transactions if we're past the minimum block size:
301 const uint256& hash = tx.GetHash();
302 double dPriorityDelta = 0;
303 CAmount nFeeDelta = 0;
304 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
305 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
308 // Prioritise by fee once past the priority size or we run out of high-priority
311 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
314 comparer = TxPriorityCompare(fSortedByFee);
315 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
318 if (!view.HaveInputs(tx))
321 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
323 nTxSigOps += GetP2SHSigOpCount(tx, view);
324 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
327 // Note that flags: we don't want to set mempool/IsStandard()
328 // policy here, but we still have to ensure that the block we
329 // create only contains transactions that are valid in new blocks.
330 CValidationState state;
331 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
334 UpdateCoins(tx, state, view, nHeight);
337 pblock->vtx.push_back(tx);
338 pblocktemplate->vTxFees.push_back(nTxFees);
339 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
340 nBlockSize += nTxSize;
342 nBlockSigOps += nTxSigOps;
347 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
350 // Add transactions that depend on this one to the priority queue
351 if (mapDependers.count(hash))
353 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
355 if (!porphan->setDependsOn.empty())
357 porphan->setDependsOn.erase(hash);
358 if (porphan->setDependsOn.empty())
360 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
361 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
368 nLastBlockTx = nBlockTx;
369 nLastBlockSize = nBlockSize;
370 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
372 // Create coinbase tx
373 CMutableTransaction txNew;
374 //txNew.nLockTime = (uint32_t)time(NULL) - 60;
376 txNew.vin[0].prevout.SetNull();
377 txNew.vout.resize(1);
378 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
379 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
381 txNew.vout[0].nValue += nFees;
382 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
383 if ( ASSETCHAINS_SYMBOL[0] == 0 )
385 int32_t i,opretlen; uint8_t opret[256],*ptr;
386 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
388 if ( (opretlen= komodo_pax_opreturn(opret,sizeof(opret))) > 0 ) // have pricefeed
390 txNew.vout.resize(2);
391 txNew.vout[1].scriptPubKey.resize(opretlen);
392 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
393 for (i=0; i<opretlen; i++)
395 txNew.vout[1].nValue = 0;
396 //fprintf(stderr,"opretlen.%d\n",opretlen);
400 else if ( komodo_is_issuer() != 0 )
402 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
403 if ( txNew.vout.size() > 1 )
404 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
406 pblock->vtx[0] = txNew;
407 pblocktemplate->vTxFees[0] = -nFees;
409 arith_uint256 nonce = UintToArith256(GetRandHash());
410 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
413 pblock->nNonce = ArithToUint256(nonce);
416 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
417 pblock->hashReserved = uint256();
418 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
419 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
420 pblock->nSolution.clear();
421 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
423 CValidationState state;
424 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
426 fprintf(stderr,"testblockvalidity failed\n");
427 //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
431 return pblocktemplate.release();
434 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
436 // Update nExtraNonce
437 static uint256 hashPrevBlock;
438 if (hashPrevBlock != pblock->hashPrevBlock)
441 hashPrevBlock = pblock->hashPrevBlock;
444 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
445 CMutableTransaction txCoinbase(pblock->vtx[0]);
446 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
447 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
449 pblock->vtx[0] = txCoinbase;
450 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
454 //////////////////////////////////////////////////////////////////////////////
458 int8_t komodo_minerid(int32_t height);
460 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
462 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
463 if ( USE_EXTERNAL_PUBKEY != 0 )
465 //fprintf(stderr,"use notary pubkey\n");
466 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
470 if (!reservekey.GetReservedKey(pubkey))
472 scriptPubKey.resize(35);
473 ptr = (uint8_t *)pubkey.begin();
474 script = (uint8_t *)scriptPubKey.data();
477 script[i+1] = ptr[i];
478 script[34] = OP_CHECKSIG;
479 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
481 if ( 0 && ASSETCHAINS_SYMBOL[0] == 0 )
484 fprintf(stderr,"%d ",komodo_minerid(chainActive.Tip()->nHeight-i));
485 fprintf(stderr," minerids.special %d from ht.%d\n",komodo_is_special(chainActive.Tip()->nHeight+1,NOTARY_PUBKEY33),chainActive.Tip()->nHeight);
487 return CreateNewBlock(scriptPubKey);
490 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
492 LogPrintf("%s\n", pblock->ToString());
493 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
498 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
499 return error("KomodoMiner: generated block is stale");
502 // Remove key from key pool
503 if ( IS_KOMODO_NOTARY == 0 )
504 reservekey.KeepKey();
506 // Track how many getdata requests this block gets
508 LOCK(wallet.cs_wallet);
509 wallet.mapRequestCount[pblock->GetHash()] = 0;
512 // Process this block the same as if we had received it from another node
513 CValidationState state;
514 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
515 return error("KomodoMiner: ProcessNewBlock, block not accepted");
517 TrackMinedBlock(pblock->GetHash());
522 int32_t komodo_baseid(char *origbase);
524 void static BitcoinMiner(CWallet *pwallet)
526 LogPrintf("KomodoMiner started\n");
527 SetThreadPriority(THREAD_PRIORITY_LOWEST);
528 RenameThread("komodo-miner");
529 const CChainParams& chainparams = Params();
531 // Each thread has its own key and counter
532 CReserveKey reservekey(pwallet);
533 unsigned int nExtraNonce = 0;
535 unsigned int n = chainparams.EquihashN();
536 unsigned int k = chainparams.EquihashK();
537 int32_t notaryid = -1;
538 while ( ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0 )
541 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
544 komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33);
547 if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
549 else solver = "default";
550 assert(solver == "tromp" || solver == "default");
551 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
552 //fprintf(stderr,"Mining with %s\n",solver.c_str());
554 bool cancelSolver = false;
555 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
556 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
557 std::lock_guard<std::mutex> lock{m_cs};
563 //fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
566 if (chainparams.MiningRequiresPeers())
568 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
570 // Busy-wait for the network to come online so we don't waste time mining
571 // on an obsolete chain. In regtest mode we expect to fly solo.
572 //fprintf(stderr,"Wait for peers...\n");
577 fvNodesEmpty = vNodes.empty();
579 if (!fvNodesEmpty && !IsInitialBlockDownload())
582 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
585 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
587 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
589 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
595 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
596 CBlockIndex* pindexPrev = chainActive.Tip();
597 if ( Mining_height != pindexPrev->nHeight+1 )
599 Mining_height = pindexPrev->nHeight+1;
600 Mining_start = (uint32_t)time(NULL);
602 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
603 fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
605 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
606 if (!pblocktemplate.get())
608 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
611 CBlock *pblock = &pblocktemplate->block;
612 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
613 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
617 uint32_t savebits; int64_t nStart = GetTime();
618 savebits = pblock->nBits;
619 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
620 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
622 if ( (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
624 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
625 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
626 } else Mining_start = 0;
627 } else Mining_start = 0;
630 if ( ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
632 //fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
637 KOMODO_CHOSEN_ONE = 0;
638 crypto_generichash_blake2b_state state;
639 EhInitialiseState(n, k, state);
640 // I = the block header minus nonce and solution.
641 CEquihashInput I{*pblock};
642 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
645 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
647 crypto_generichash_blake2b_state curr_state;
649 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
650 // (x_1, x_2, ...) = A(I, V, n, k)
651 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
652 std::function<bool(std::vector<unsigned char>)> validBlock =
653 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
654 (std::vector<unsigned char> soln)
656 // Write the solution to the hash and compute the result.
657 LogPrint("pow", "- Checking solution against target\n");
658 pblock->nSolution = soln;
659 solutionTargetChecks.increment();
660 if ( UintToArith256(pblock->GetHash()) > hashTarget )
662 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
663 fprintf(stderr,"missed target\n");
666 if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+ROUNDROBIN_DELAY )
668 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+ROUNDROBIN_DELAY-time(NULL)));
669 int32_t nseconds = Mining_start+ROUNDROBIN_DELAY-time(NULL);
672 MilliSleep((rand() % 700) + 1);
674 KOMODO_CHOSEN_ONE = 1;
676 SetThreadPriority(THREAD_PRIORITY_NORMAL);
677 LogPrintf("KomodoMiner:\n");
678 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
679 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
680 // Ignore chain updates caused by us
681 std::lock_guard<std::mutex> lock{m_cs};
682 cancelSolver = false;
684 KOMODO_CHOSEN_ONE = 0;
685 SetThreadPriority(THREAD_PRIORITY_LOWEST);
686 // In regression test mode, stop mining after a block is found.
687 if (chainparams.MineBlocksOnDemand()) {
688 // Increment here because throwing skips the call below
689 ehSolverRuns.increment();
690 throw boost::thread_interrupted();
694 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
695 std::lock_guard<std::mutex> lock{m_cs};
699 // TODO: factor this out into a function with the same API for each solver.
700 if (solver == "tromp" && notaryid >= 0 ) {
701 // Create solver and initialize it.
703 eq.setstate(&curr_state);
705 // Intialization done, start algo driver.
707 eq.xfull = eq.bfull = eq.hfull = 0;
709 for (u32 r = 1; r < WK; r++) {
710 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
711 eq.xfull = eq.bfull = eq.hfull = 0;
715 ehSolverRuns.increment();
717 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
718 for (size_t s = 0; s < eq.nsols; s++) {
719 LogPrint("pow", "Checking solution %d\n", s+1);
720 std::vector<eh_index> index_vector(PROOFSIZE);
721 for (size_t i = 0; i < PROOFSIZE; i++) {
722 index_vector[i] = eq.sols[s][i];
724 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
726 if (validBlock(sol_char)) {
727 // If we find a POW solution, do not try other solutions
728 // because they become invalid as we created a new block in blockchain.
734 // If we find a valid block, we rebuild
735 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
736 ehSolverRuns.increment();
738 int32_t i; uint256 hash = pblock->GetHash();
740 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
741 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
742 sleep(60); // avoid mining forks
745 } catch (EhSolverCancelledException&) {
746 LogPrint("pow", "Equihash solver cancelled\n");
747 std::lock_guard<std::mutex> lock{m_cs};
748 cancelSolver = false;
752 // Check for stop or if block needs to be rebuilt
753 boost::this_thread::interruption_point();
754 // Regtest mode doesn't require peers
755 if (vNodes.empty() && chainparams.MiningRequiresPeers())
757 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
759 //fprintf(stderr,"no nodes, break\n");
763 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
765 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
766 fprintf(stderr,"0xffff, break\n");
769 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
771 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
772 fprintf(stderr,"timeout, break\n");
775 if ( pindexPrev != chainActive.Tip() )
777 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
778 fprintf(stderr,"Tip advanced, break\n");
781 // Update nNonce and nTime
782 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
783 pblock->nBits = savebits;
784 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
785 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
787 // Changing pblock->nTime can change work required on testnet:
788 hashTarget.SetCompact(pblock->nBits);
793 catch (const boost::thread_interrupted&)
796 LogPrintf("KomodoMiner terminated\n");
799 catch (const std::runtime_error &e)
802 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
808 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
810 static boost::thread_group* minerThreads = NULL;
813 // In regtest threads defaults to 1
814 if (Params().DefaultMinerThreads())
815 nThreads = Params().DefaultMinerThreads();
817 nThreads = boost::thread::hardware_concurrency();
820 if (minerThreads != NULL)
822 minerThreads->interrupt_all();
827 if (nThreads == 0 || !fGenerate)
830 minerThreads = new boost::thread_group();
831 for (int i = 0; i < nThreads; i++)
832 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
835 #endif // ENABLE_WALLET