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 59
104 extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_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_PASSPORT_INITDONE == 0 || 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());
410 pblock->vtx[0] = txNew;
411 pblocktemplate->vTxFees[0] = -nFees;
413 arith_uint256 nonce = UintToArith256(GetRandHash());
414 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
417 pblock->nNonce = ArithToUint256(nonce);
420 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
421 pblock->hashReserved = uint256();
422 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
423 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
424 pblock->nSolution.clear();
425 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
427 CValidationState state;
428 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
430 static uint32_t counter;
431 if ( counter++ < 100 )
432 fprintf(stderr,"warning: testblockvalidity failed\n");
434 //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
438 return pblocktemplate.release();
441 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
443 // Update nExtraNonce
444 static uint256 hashPrevBlock;
445 if (hashPrevBlock != pblock->hashPrevBlock)
448 hashPrevBlock = pblock->hashPrevBlock;
451 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
452 CMutableTransaction txCoinbase(pblock->vtx[0]);
453 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
454 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
456 pblock->vtx[0] = txCoinbase;
457 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
461 //////////////////////////////////////////////////////////////////////////////
465 int8_t komodo_minerid(int32_t height,uint8_t *pubkey33);
467 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
469 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
470 if ( USE_EXTERNAL_PUBKEY != 0 )
472 //fprintf(stderr,"use notary pubkey\n");
473 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
477 if (!reservekey.GetReservedKey(pubkey))
481 scriptPubKey.resize(35);
482 ptr = (uint8_t *)pubkey.begin();
483 script = (uint8_t *)scriptPubKey.data();
486 script[i+1] = ptr[i];
487 script[34] = OP_CHECKSIG;
488 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
490 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
493 fprintf(stderr,"%d ",komodo_minerid(chainActive.Tip()->nHeight-i,0));
494 fprintf(stderr," minerids.special %d from ht.%d\n",komodo_is_special(chainActive.Tip()->nHeight+1,NOTARY_PUBKEY33),chainActive.Tip()->nHeight);
496 return CreateNewBlock(scriptPubKey);
499 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
501 LogPrintf("%s\n", pblock->ToString());
502 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
507 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
508 return error("KomodoMiner: generated block is stale");
511 // Remove key from key pool
512 if ( IS_KOMODO_NOTARY == 0 )
513 reservekey.KeepKey();
515 // Track how many getdata requests this block gets
517 LOCK(wallet.cs_wallet);
518 wallet.mapRequestCount[pblock->GetHash()] = 0;
521 // Process this block the same as if we had received it from another node
522 CValidationState state;
523 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
524 return error("KomodoMiner: ProcessNewBlock, block not accepted");
526 TrackMinedBlock(pblock->GetHash());
531 int32_t komodo_baseid(char *origbase);
532 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height);
533 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
534 extern int32_t KOMODO_LASTMINED;
536 void static BitcoinMiner(CWallet *pwallet)
538 LogPrintf("KomodoMiner started\n");
539 SetThreadPriority(THREAD_PRIORITY_LOWEST);
540 RenameThread("komodo-miner");
541 const CChainParams& chainparams = Params();
543 // Each thread has its own key and counter
544 CReserveKey reservekey(pwallet);
545 unsigned int nExtraNonce = 0;
547 unsigned int n = chainparams.EquihashN();
548 unsigned int k = chainparams.EquihashK();
549 int32_t notaryid = -1;
550 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
553 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
556 komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33);
559 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
561 //else solver = "default";
562 assert(solver == "tromp" || solver == "default");
563 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
564 if ( ASSETCHAINS_SYMBOL[0] != 0 )
565 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
567 bool cancelSolver = false;
568 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
569 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
570 std::lock_guard<std::mutex> lock{m_cs};
576 if ( ASSETCHAINS_SYMBOL[0] != 0 )
577 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
580 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
582 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
584 // Busy-wait for the network to come online so we don't waste time mining
585 // on an obsolete chain. In regtest mode we expect to fly solo.
586 //fprintf(stderr,"Wait for peers...\n");
591 fvNodesEmpty = vNodes.empty();
593 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
596 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
599 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
601 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
603 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
609 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
610 CBlockIndex* pindexPrev = chainActive.Tip();
611 if ( Mining_height != pindexPrev->nHeight+1 )
613 Mining_height = pindexPrev->nHeight+1;
614 Mining_start = (uint32_t)time(NULL);
616 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
617 fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
618 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
621 static uint32_t counter;
622 if ( counter++ < 100 )
623 fprintf(stderr,"created illegal block, retry\n");
626 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
627 if (!pblocktemplate.get())
629 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
632 CBlock *pblock = &pblocktemplate->block;
633 if ( ASSETCHAINS_SYMBOL[0] != 0 )
635 if ( pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
637 static uint32_t counter;
638 if ( counter++ < 10 )
639 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
642 } else fprintf(stderr,"vouts.%d mining.%d vs %d\n",(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
644 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
645 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
649 uint8_t pubkeys[66][33]; int mids[66],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
650 savebits = pblock->nBits;
651 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
652 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )//komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
655 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
657 komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight);
661 if( pubkeys[0][i] != 0 )
665 else externalflag = 0;
666 if ( NOTARY_PUBKEY33[0] != 0 && notaryid < 3 )
669 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
671 if ( externalflag == 0 && i != 66 )
672 printf("VIOLATION at %d\n",i);
676 printf("%02x",pubkeys[i][j]);
677 printf(" p%d -> %d\n",i,komodo_minerid(pindexPrev->nHeight-i,pubkeys[i]));
679 for (j=gpucount=0; j<65; j++)
682 fprintf(stderr,"%d ",mids[j]);
683 else fprintf(stderr,"GPU ");
687 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%%\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j);
690 if ( mids[j] == notaryid )
692 } else fprintf(stderr,"no nonz pubkeys\n");
693 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+3 && Mining_height > KOMODO_LASTMINED+64) )
695 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
696 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
697 } //else fprintf(stderr,"duplicate at j.%d\n",j);
698 } else Mining_start = 0;
699 } else Mining_start = 0;
702 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
704 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
709 KOMODO_CHOSEN_ONE = 0;
710 crypto_generichash_blake2b_state state;
711 EhInitialiseState(n, k, state);
712 // I = the block header minus nonce and solution.
713 CEquihashInput I{*pblock};
714 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
717 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
719 crypto_generichash_blake2b_state curr_state;
721 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
722 // (x_1, x_2, ...) = A(I, V, n, k)
723 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
724 //fprintf(stderr,"running solver\n");
725 std::function<bool(std::vector<unsigned char>)> validBlock =
726 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
727 (std::vector<unsigned char> soln)
729 // Write the solution to the hash and compute the result.
730 LogPrint("pow", "- Checking solution against target\n");
731 pblock->nSolution = soln;
732 solutionTargetChecks.increment();
733 if ( UintToArith256(pblock->GetHash()) > hashTarget )
735 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
736 // fprintf(stderr," missed target\n");
739 if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+ROUNDROBIN_DELAY )
741 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+ROUNDROBIN_DELAY-time(NULL)));
742 int32_t nseconds = Mining_start+ROUNDROBIN_DELAY-time(NULL);
745 MilliSleep((rand() % 1700) + 1);
747 KOMODO_CHOSEN_ONE = 1;
749 SetThreadPriority(THREAD_PRIORITY_NORMAL);
750 LogPrintf("KomodoMiner:\n");
751 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
752 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
753 // Ignore chain updates caused by us
754 std::lock_guard<std::mutex> lock{m_cs};
755 cancelSolver = false;
757 KOMODO_CHOSEN_ONE = 0;
758 SetThreadPriority(THREAD_PRIORITY_LOWEST);
759 // In regression test mode, stop mining after a block is found.
760 if (chainparams.MineBlocksOnDemand()) {
761 // Increment here because throwing skips the call below
762 ehSolverRuns.increment();
763 throw boost::thread_interrupted();
765 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
769 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
770 std::lock_guard<std::mutex> lock{m_cs};
774 // TODO: factor this out into a function with the same API for each solver.
775 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
776 // Create solver and initialize it.
778 eq.setstate(&curr_state);
780 // Intialization done, start algo driver.
782 eq.xfull = eq.bfull = eq.hfull = 0;
784 for (u32 r = 1; r < WK; r++) {
785 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
786 eq.xfull = eq.bfull = eq.hfull = 0;
790 ehSolverRuns.increment();
792 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
793 for (size_t s = 0; s < eq.nsols; s++) {
794 LogPrint("pow", "Checking solution %d\n", s+1);
795 std::vector<eh_index> index_vector(PROOFSIZE);
796 for (size_t i = 0; i < PROOFSIZE; i++) {
797 index_vector[i] = eq.sols[s][i];
799 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
801 if (validBlock(sol_char)) {
802 // If we find a POW solution, do not try other solutions
803 // because they become invalid as we created a new block in blockchain.
809 // If we find a valid block, we rebuild
810 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
811 ehSolverRuns.increment();
813 int32_t i; uint256 hash = pblock->GetHash();
815 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
816 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
818 KOMODO_MAYBEMINED = Mining_height;
821 } catch (EhSolverCancelledException&) {
822 LogPrint("pow", "Equihash solver cancelled\n");
823 std::lock_guard<std::mutex> lock{m_cs};
824 cancelSolver = false;
828 // Check for stop or if block needs to be rebuilt
829 boost::this_thread::interruption_point();
830 // Regtest mode doesn't require peers
831 if ( FOUND_BLOCK != 0 )
834 fprintf(stderr,"FOUND_BLOCK!\n");
837 if (vNodes.empty() && chainparams.MiningRequiresPeers())
839 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
841 fprintf(stderr,"no nodes, break\n");
845 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
847 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
848 fprintf(stderr,"0xffff, break\n");
851 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
853 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
854 fprintf(stderr,"timeout, break\n");
857 if ( pindexPrev != chainActive.Tip() )
859 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
860 fprintf(stderr,"Tip advanced, break\n");
863 // Update nNonce and nTime
864 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
865 pblock->nBits = savebits;
866 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
867 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
869 // Changing pblock->nTime can change work required on testnet:
870 hashTarget.SetCompact(pblock->nBits);
875 catch (const boost::thread_interrupted&)
878 LogPrintf("KomodoMiner terminated\n");
881 catch (const std::runtime_error &e)
884 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
890 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
892 static boost::thread_group* minerThreads = NULL;
895 // In regtest threads defaults to 1
896 if (Params().DefaultMinerThreads())
897 nThreads = Params().DefaultMinerThreads();
899 nThreads = boost::thread::hardware_concurrency();
902 if (minerThreads != NULL)
904 minerThreads->interrupt_all();
909 if (nThreads == 0 || !fGenerate)
912 minerThreads = new boost::thread_group();
913 for (int i = 0; i < nThreads; i++)
914 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
917 #endif // ENABLE_WALLET