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 58
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 fprintf(stderr,"pblocktemplate.get() failure\n");
128 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
129 if ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
131 isrealtime = komodo_isrealtime(&kmdheight);
132 deposits = komodo_paxtotal();
133 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
135 deposits = komodo_paxtotal();
136 if ( KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
138 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
140 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
142 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);
147 KOMODO_ON_DEMAND = 0;
148 if ( 0 && deposits != 0 )
149 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());
151 // -regtest only: allow overriding block.nVersion with
152 // -blockversion=N to test forking scenarios
153 if (Params().MineBlocksOnDemand())
154 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
156 // Add dummy coinbase tx as first transaction
157 pblock->vtx.push_back(CTransaction());
158 pblocktemplate->vTxFees.push_back(-1); // updated at end
159 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
161 // Largest block you're willing to create:
162 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
163 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
164 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
166 // How much of the block should be dedicated to high-priority transactions,
167 // included regardless of the fees they pay
168 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
169 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
171 // Minimum block size you want to create; block will be filled with free transactions
172 // until there are no more or the block reaches this size:
173 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
174 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
176 // Collect memory pool transactions into the block
180 LOCK2(cs_main, mempool.cs);
181 CBlockIndex* pindexPrev = chainActive.Tip();
182 const int nHeight = pindexPrev->nHeight + 1;
183 pblock->nTime = GetAdjustedTime();
184 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
185 CCoinsViewCache view(pcoinsTip);
187 // Priority order to process transactions
188 list<COrphan> vOrphan; // list memory doesn't move
189 map<uint256, vector<COrphan*> > mapDependers;
190 bool fPrintPriority = GetBoolArg("-printpriority", false);
192 // This vector will be sorted into a priority queue:
193 vector<TxPriority> vecPriority;
194 vecPriority.reserve(mempool.mapTx.size());
195 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
196 mi != mempool.mapTx.end(); ++mi)
198 const CTransaction& tx = mi->second.GetTx();
200 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
202 : pblock->GetBlockTime();
204 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
207 COrphan* porphan = NULL;
208 double dPriority = 0;
209 CAmount nTotalIn = 0;
210 bool fMissingInputs = false;
211 BOOST_FOREACH(const CTxIn& txin, tx.vin)
213 // Read prev transaction
214 if (!view.HaveCoins(txin.prevout.hash))
216 // This should never happen; all transactions in the memory
217 // pool should connect to either transactions in the chain
218 // or other transactions in the memory pool.
219 if (!mempool.mapTx.count(txin.prevout.hash))
221 LogPrintf("ERROR: mempool transaction missing input\n");
222 if (fDebug) assert("mempool transaction missing input" == 0);
223 fMissingInputs = true;
229 // Has to wait for dependencies
232 // Use list for automatic deletion
233 vOrphan.push_back(COrphan(&tx));
234 porphan = &vOrphan.back();
236 mapDependers[txin.prevout.hash].push_back(porphan);
237 porphan->setDependsOn.insert(txin.prevout.hash);
238 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
241 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
244 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
245 nTotalIn += nValueIn;
247 int nConf = nHeight - coins->nHeight;
249 dPriority += (double)nValueIn * nConf;
251 nTotalIn += tx.GetJoinSplitValueIn();
253 if (fMissingInputs) continue;
255 // Priority is sum(valuein * age) / modified_txsize
256 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
257 dPriority = tx.ComputePriority(dPriority, nTxSize);
259 uint256 hash = tx.GetHash();
260 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
262 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
266 porphan->dPriority = dPriority;
267 porphan->feeRate = feeRate;
270 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
273 // Collect transactions into block
274 uint64_t nBlockSize = 1000;
275 uint64_t nBlockTx = 0;
277 int nBlockSigOps = 100;
278 bool fSortedByFee = (nBlockPrioritySize <= 0);
280 TxPriorityCompare comparer(fSortedByFee);
281 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
283 while (!vecPriority.empty())
285 // Take highest priority transaction off the priority queue:
286 double dPriority = vecPriority.front().get<0>();
287 CFeeRate feeRate = vecPriority.front().get<1>();
288 const CTransaction& tx = *(vecPriority.front().get<2>());
290 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
291 vecPriority.pop_back();
294 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
295 if (nBlockSize + nTxSize >= nBlockMaxSize)
298 // Legacy limits on sigOps:
299 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
300 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
303 // Skip free transactions if we're past the minimum block size:
304 const uint256& hash = tx.GetHash();
305 double dPriorityDelta = 0;
306 CAmount nFeeDelta = 0;
307 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
308 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
311 // Prioritise by fee once past the priority size or we run out of high-priority
314 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
317 comparer = TxPriorityCompare(fSortedByFee);
318 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
321 if (!view.HaveInputs(tx))
324 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
326 nTxSigOps += GetP2SHSigOpCount(tx, view);
327 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
330 // Note that flags: we don't want to set mempool/IsStandard()
331 // policy here, but we still have to ensure that the block we
332 // create only contains transactions that are valid in new blocks.
333 CValidationState state;
334 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
337 UpdateCoins(tx, state, view, nHeight);
340 pblock->vtx.push_back(tx);
341 pblocktemplate->vTxFees.push_back(nTxFees);
342 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
343 nBlockSize += nTxSize;
345 nBlockSigOps += nTxSigOps;
350 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
353 // Add transactions that depend on this one to the priority queue
354 if (mapDependers.count(hash))
356 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
358 if (!porphan->setDependsOn.empty())
360 porphan->setDependsOn.erase(hash);
361 if (porphan->setDependsOn.empty())
363 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
364 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
371 nLastBlockTx = nBlockTx;
372 nLastBlockSize = nBlockSize;
373 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
375 // Create coinbase tx
376 CMutableTransaction txNew;
377 //txNew.nLockTime = (uint32_t)time(NULL) - 60;
379 txNew.vin[0].prevout.SetNull();
380 txNew.vout.resize(1);
381 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
382 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
384 txNew.vout[0].nValue += nFees;
385 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
386 if ( ASSETCHAINS_SYMBOL[0] == 0 )
388 int32_t i,opretlen; uint8_t opret[256],*ptr;
389 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
391 if ( (opretlen= komodo_pax_opreturn(opret,sizeof(opret))) > 0 ) // have pricefeed
393 txNew.vout.resize(2);
394 txNew.vout[1].scriptPubKey.resize(opretlen);
395 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
396 for (i=0; i<opretlen; i++)
398 txNew.vout[1].nValue = 0;
399 //fprintf(stderr,"opretlen.%d\n",opretlen);
403 else if ( komodo_is_issuer() != 0 )
405 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
406 //if ( txNew.vout.size() > 1 )
407 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
409 pblock->vtx[0] = txNew;
410 pblocktemplate->vTxFees[0] = -nFees;
412 arith_uint256 nonce = UintToArith256(GetRandHash());
413 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
416 pblock->nNonce = ArithToUint256(nonce);
419 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
420 pblock->hashReserved = uint256();
421 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
422 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
423 pblock->nSolution.clear();
424 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
426 CValidationState state;
427 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
429 static uint32_t counter;
430 if ( counter++ < 100 )
431 fprintf(stderr,"warning: testblockvalidity failed\n");
433 //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
437 return pblocktemplate.release();
440 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
442 // Update nExtraNonce
443 static uint256 hashPrevBlock;
444 if (hashPrevBlock != pblock->hashPrevBlock)
447 hashPrevBlock = pblock->hashPrevBlock;
450 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
451 CMutableTransaction txCoinbase(pblock->vtx[0]);
452 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
453 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
455 pblock->vtx[0] = txCoinbase;
456 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
460 //////////////////////////////////////////////////////////////////////////////
464 int8_t komodo_minerid(int32_t height,uint8_t *pubkey33);
466 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
468 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
469 if ( USE_EXTERNAL_PUBKEY != 0 )
471 //fprintf(stderr,"use notary pubkey\n");
472 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
476 if (!reservekey.GetReservedKey(pubkey))
480 scriptPubKey.resize(35);
481 ptr = (uint8_t *)pubkey.begin();
482 script = (uint8_t *)scriptPubKey.data();
485 script[i+1] = ptr[i];
486 script[34] = OP_CHECKSIG;
487 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
489 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
492 fprintf(stderr,"%d ",komodo_minerid(chainActive.Tip()->nHeight-i,0));
493 fprintf(stderr," minerids.special %d from ht.%d\n",komodo_is_special(chainActive.Tip()->nHeight+1,NOTARY_PUBKEY33),chainActive.Tip()->nHeight);
495 return CreateNewBlock(scriptPubKey);
498 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
500 LogPrintf("%s\n", pblock->ToString());
501 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
506 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
507 return error("KomodoMiner: generated block is stale");
510 // Remove key from key pool
511 if ( IS_KOMODO_NOTARY == 0 )
512 reservekey.KeepKey();
514 // Track how many getdata requests this block gets
516 LOCK(wallet.cs_wallet);
517 wallet.mapRequestCount[pblock->GetHash()] = 0;
520 // Process this block the same as if we had received it from another node
521 CValidationState state;
522 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
523 return error("KomodoMiner: ProcessNewBlock, block not accepted");
525 TrackMinedBlock(pblock->GetHash());
530 int32_t komodo_baseid(char *origbase);
531 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height);
532 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
533 extern int32_t KOMODO_LASTMINED;
535 void static BitcoinMiner(CWallet *pwallet)
537 LogPrintf("KomodoMiner started\n");
538 SetThreadPriority(THREAD_PRIORITY_LOWEST);
539 RenameThread("komodo-miner");
540 const CChainParams& chainparams = Params();
542 // Each thread has its own key and counter
543 CReserveKey reservekey(pwallet);
544 unsigned int nExtraNonce = 0;
546 unsigned int n = chainparams.EquihashN();
547 unsigned int k = chainparams.EquihashK();
548 int32_t notaryid = -1;
549 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
552 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
555 komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33);
558 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
560 //else solver = "default";
561 assert(solver == "tromp" || solver == "default");
562 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
563 if ( ASSETCHAINS_SYMBOL[0] != 0 )
564 fprintf(stderr,"notaryid.%d Mining with %s\n",notaryid,solver.c_str());
566 bool cancelSolver = false;
567 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
568 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
569 std::lock_guard<std::mutex> lock{m_cs};
575 if ( ASSETCHAINS_SYMBOL[0] != 0 )
576 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
579 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
581 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
583 // Busy-wait for the network to come online so we don't waste time mining
584 // on an obsolete chain. In regtest mode we expect to fly solo.
585 //fprintf(stderr,"Wait for peers...\n");
590 fvNodesEmpty = vNodes.empty();
592 if (!fvNodesEmpty && !IsInitialBlockDownload())
595 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
598 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
600 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
602 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
608 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
609 CBlockIndex* pindexPrev = chainActive.Tip();
610 if ( Mining_height != pindexPrev->nHeight+1 )
612 Mining_height = pindexPrev->nHeight+1;
613 Mining_start = (uint32_t)time(NULL);
615 if ( ASSETCHAINS_SYMBOL[0] != 0 )
616 fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
617 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
620 static uint32_t counter;
621 if ( counter++ < 100 )
622 fprintf(stderr,"created illegal block, retry\n");
625 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
626 if (!pblocktemplate.get())
628 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
631 CBlock *pblock = &pblocktemplate->block;
632 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
633 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
637 uint8_t pubkeys[66][33]; int mids[66],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
638 savebits = pblock->nBits;
639 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
640 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )//komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
643 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
645 komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight);
649 if( pubkeys[0][i] != 0 )
653 else externalflag = 0;
654 if ( NOTARY_PUBKEY33[0] != 0 && notaryid < 3 )
657 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
659 if ( externalflag == 0 && i != 66 )
660 printf("VIOLATION at %d\n",i);
664 printf("%02x",pubkeys[i][j]);
665 printf(" p%d -> %d\n",i,komodo_minerid(pindexPrev->nHeight-i,pubkeys[i]));
667 for (j=gpucount=0; j<65; j++)
669 fprintf(stderr,"%d ",mids[j]);
673 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%%\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j);
676 if ( mids[j] == notaryid )
678 } else fprintf(stderr,"no nonz pubkeys\n");
679 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+3 && Mining_height > KOMODO_LASTMINED+64) )
681 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
682 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
683 } //else fprintf(stderr,"duplicate at j.%d\n",j);
684 } else Mining_start = 0;
685 } else Mining_start = 0;
688 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
690 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
695 KOMODO_CHOSEN_ONE = 0;
696 crypto_generichash_blake2b_state state;
697 EhInitialiseState(n, k, state);
698 // I = the block header minus nonce and solution.
699 CEquihashInput I{*pblock};
700 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
703 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
705 crypto_generichash_blake2b_state curr_state;
707 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
708 // (x_1, x_2, ...) = A(I, V, n, k)
709 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
710 //fprintf(stderr,"running solver\n");
711 std::function<bool(std::vector<unsigned char>)> validBlock =
712 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
713 (std::vector<unsigned char> soln)
715 // Write the solution to the hash and compute the result.
716 LogPrint("pow", "- Checking solution against target\n");
717 pblock->nSolution = soln;
718 solutionTargetChecks.increment();
719 if ( UintToArith256(pblock->GetHash()) > hashTarget )
721 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
722 // fprintf(stderr," missed target\n");
725 if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+ROUNDROBIN_DELAY )
727 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+ROUNDROBIN_DELAY-time(NULL)));
728 int32_t nseconds = Mining_start+ROUNDROBIN_DELAY-time(NULL);
731 MilliSleep((rand() % 700) + 1);
733 KOMODO_CHOSEN_ONE = 1;
735 SetThreadPriority(THREAD_PRIORITY_NORMAL);
736 LogPrintf("KomodoMiner:\n");
737 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
738 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
739 // Ignore chain updates caused by us
740 std::lock_guard<std::mutex> lock{m_cs};
741 cancelSolver = false;
743 KOMODO_CHOSEN_ONE = 0;
744 SetThreadPriority(THREAD_PRIORITY_LOWEST);
745 // In regression test mode, stop mining after a block is found.
746 if (chainparams.MineBlocksOnDemand()) {
747 // Increment here because throwing skips the call below
748 ehSolverRuns.increment();
749 throw boost::thread_interrupted();
751 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
755 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
756 std::lock_guard<std::mutex> lock{m_cs};
760 // TODO: factor this out into a function with the same API for each solver.
761 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
762 // Create solver and initialize it.
764 eq.setstate(&curr_state);
766 // Intialization done, start algo driver.
768 eq.xfull = eq.bfull = eq.hfull = 0;
770 for (u32 r = 1; r < WK; r++) {
771 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
772 eq.xfull = eq.bfull = eq.hfull = 0;
776 ehSolverRuns.increment();
778 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
779 for (size_t s = 0; s < eq.nsols; s++) {
780 LogPrint("pow", "Checking solution %d\n", s+1);
781 std::vector<eh_index> index_vector(PROOFSIZE);
782 for (size_t i = 0; i < PROOFSIZE; i++) {
783 index_vector[i] = eq.sols[s][i];
785 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
787 if (validBlock(sol_char)) {
788 // If we find a POW solution, do not try other solutions
789 // because they become invalid as we created a new block in blockchain.
795 // If we find a valid block, we rebuild
796 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
797 ehSolverRuns.increment();
799 int32_t i; uint256 hash = pblock->GetHash();
801 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
802 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
804 KOMODO_MAYBEMINED = Mining_height;
807 } catch (EhSolverCancelledException&) {
808 LogPrint("pow", "Equihash solver cancelled\n");
809 std::lock_guard<std::mutex> lock{m_cs};
810 cancelSolver = false;
814 // Check for stop or if block needs to be rebuilt
815 boost::this_thread::interruption_point();
816 // Regtest mode doesn't require peers
817 if ( FOUND_BLOCK != 0 )
820 fprintf(stderr,"FOUND_BLOCK!\n");
823 if (vNodes.empty() && chainparams.MiningRequiresPeers())
825 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
827 fprintf(stderr,"no nodes, break\n");
831 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
833 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
834 fprintf(stderr,"0xffff, break\n");
837 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
839 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
840 fprintf(stderr,"timeout, break\n");
843 if ( pindexPrev != chainActive.Tip() )
845 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
846 fprintf(stderr,"Tip advanced, break\n");
849 // Update nNonce and nTime
850 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
851 pblock->nBits = savebits;
852 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
853 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
855 // Changing pblock->nTime can change work required on testnet:
856 hashTarget.SetCompact(pblock->nBits);
861 catch (const boost::thread_interrupted&)
864 LogPrintf("KomodoMiner terminated\n");
867 catch (const std::runtime_error &e)
870 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
876 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
878 static boost::thread_group* minerThreads = NULL;
881 // In regtest threads defaults to 1
882 if (Params().DefaultMinerThreads())
883 nThreads = Params().DefaultMinerThreads();
885 nThreads = boost::thread::hardware_concurrency();
888 if (minerThreads != NULL)
890 minerThreads->interrupt_all();
895 if (nThreads == 0 || !fGenerate)
898 minerThreads = new boost::thread_group();
899 for (int i = 0; i < nThreads; i++)
900 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
903 #endif // ENABLE_WALLET