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"
13 #include "chainparams.h"
14 #include "consensus/consensus.h"
15 #include "consensus/upgrades.h"
16 #include "consensus/validation.h"
18 #include "crypto/equihash.h"
19 #include "crypto/verus_hash.h"
27 #include "primitives/transaction.h"
30 #include "ui_interface.h"
32 #include "utilmoneystr.h"
34 #include "wallet/wallet.h"
39 #include <boost/thread.hpp>
40 #include <boost/tuple/tuple.hpp>
48 //////////////////////////////////////////////////////////////////////////////
54 // Unconfirmed transactions in the memory pool often depend on other
55 // transactions in the memory pool. When we select transactions from the
56 // pool, we select by highest priority or fee rate, so we might consider
57 // transactions that depend on transactions that aren't yet in the block.
58 // The COrphan class keeps track of these 'temporary orphans' while
59 // CreateBlock is figuring out which transactions to include.
64 const CTransaction* ptx;
65 set<uint256> setDependsOn;
69 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
74 uint64_t nLastBlockTx = 0;
75 uint64_t nLastBlockSize = 0;
77 // We want to sort transactions by priority and fee rate, so:
78 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
79 class TxPriorityCompare
84 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
86 bool operator()(const TxPriority& a, const TxPriority& b)
90 if (a.get<1>() == b.get<1>())
91 return a.get<0>() < b.get<0>();
92 return a.get<1>() < b.get<1>();
96 if (a.get<0>() == b.get<0>())
97 return a.get<1>() < b.get<1>();
98 return a.get<0>() < b.get<0>();
103 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
105 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
108 #include "komodo_defs.h"
110 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;
111 extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
112 extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
113 extern const char *ASSETCHAINS_ALGORITHMS[];
114 extern int32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
115 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
116 extern std::string NOTARY_PUBKEY;
117 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
118 uint32_t Mining_start,Mining_height;
119 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
120 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
121 //uint64_t komodo_paxtotal();
122 int32_t komodo_baseid(char *origbase);
123 //int32_t komodo_is_issuer();
124 //int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
125 //int32_t komodo_isrealtime(int32_t *kmdheightp);
126 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
127 int64_t komodo_block_unlocktime(uint32_t nHeight);
128 uint64_t komodo_commission(const CBlock *block);
129 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);
130 int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
132 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
134 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
136 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
137 if(!pblocktemplate.get())
139 fprintf(stderr,"pblocktemplate.get() failure\n");
142 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
143 /*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
145 isrealtime = komodo_isrealtime(&kmdheight);
146 deposits = komodo_paxtotal();
147 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
149 deposits = komodo_paxtotal();
150 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
152 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
154 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
156 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);
161 KOMODO_ON_DEMAND = 0;
162 if ( 0 && deposits != 0 )
163 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());
165 // -regtest only: allow overriding block.nVersion with
166 // -blockversion=N to test forking scenarios
167 if (Params().MineBlocksOnDemand())
168 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
170 // Add dummy coinbase tx as first transaction
171 pblock->vtx.push_back(CTransaction());
172 pblocktemplate->vTxFees.push_back(-1); // updated at end
173 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
175 // Largest block you're willing to create:
176 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
177 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
178 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
180 // How much of the block should be dedicated to high-priority transactions,
181 // included regardless of the fees they pay
182 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
183 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
185 // Minimum block size you want to create; block will be filled with free transactions
186 // until there are no more or the block reaches this size:
187 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
188 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
190 // Collect memory pool transactions into the block
194 LOCK2(cs_main, mempool.cs);
195 CBlockIndex* pindexPrev = chainActive.Tip();
196 const int nHeight = pindexPrev->nHeight + 1;
197 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
199 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
200 uint32_t proposedTime = GetAdjustedTime();
201 if (proposedTime == nMedianTimePast)
203 // too fast or stuck, this addresses the too fast issue, while moving
204 // forward as quickly as possible
205 for (int i; i < 100; i++)
207 proposedTime = GetAdjustedTime();
208 if (proposedTime == nMedianTimePast)
212 pblock->nTime = GetAdjustedTime();
214 CCoinsViewCache view(pcoinsTip);
215 uint32_t expired; uint64_t commission;
217 // Priority order to process transactions
218 list<COrphan> vOrphan; // list memory doesn't move
219 map<uint256, vector<COrphan*> > mapDependers;
220 bool fPrintPriority = GetBoolArg("-printpriority", false);
222 // This vector will be sorted into a priority queue:
223 vector<TxPriority> vecPriority;
224 vecPriority.reserve(mempool.mapTx.size());
225 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
226 mi != mempool.mapTx.end(); ++mi)
228 const CTransaction& tx = mi->GetTx();
230 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
232 : pblock->GetBlockTime();
234 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
236 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
239 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
241 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
244 COrphan* porphan = NULL;
245 double dPriority = 0;
246 CAmount nTotalIn = 0;
247 bool fMissingInputs = false;
248 BOOST_FOREACH(const CTxIn& txin, tx.vin)
250 // Read prev transaction
251 if (!view.HaveCoins(txin.prevout.hash))
253 // This should never happen; all transactions in the memory
254 // pool should connect to either transactions in the chain
255 // or other transactions in the memory pool.
256 if (!mempool.mapTx.count(txin.prevout.hash))
258 LogPrintf("ERROR: mempool transaction missing input\n");
259 if (fDebug) assert("mempool transaction missing input" == 0);
260 fMissingInputs = true;
266 // Has to wait for dependencies
269 // Use list for automatic deletion
270 vOrphan.push_back(COrphan(&tx));
271 porphan = &vOrphan.back();
273 mapDependers[txin.prevout.hash].push_back(porphan);
274 porphan->setDependsOn.insert(txin.prevout.hash);
275 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
278 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
281 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
282 nTotalIn += nValueIn;
284 int nConf = nHeight - coins->nHeight;
286 dPriority += (double)nValueIn * nConf;
288 nTotalIn += tx.GetJoinSplitValueIn();
290 if (fMissingInputs) continue;
292 // Priority is sum(valuein * age) / modified_txsize
293 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
294 dPriority = tx.ComputePriority(dPriority, nTxSize);
296 uint256 hash = tx.GetHash();
297 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
299 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
303 porphan->dPriority = dPriority;
304 porphan->feeRate = feeRate;
307 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
310 // Collect transactions into block
311 uint64_t nBlockSize = 1000;
312 uint64_t nBlockTx = 0;
314 int nBlockSigOps = 100;
315 bool fSortedByFee = (nBlockPrioritySize <= 0);
317 TxPriorityCompare comparer(fSortedByFee);
318 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
320 while (!vecPriority.empty())
322 // Take highest priority transaction off the priority queue:
323 double dPriority = vecPriority.front().get<0>();
324 CFeeRate feeRate = vecPriority.front().get<1>();
325 const CTransaction& tx = *(vecPriority.front().get<2>());
327 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
328 vecPriority.pop_back();
331 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
332 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
334 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
338 // Legacy limits on sigOps:
339 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
340 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
342 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
345 // Skip free transactions if we're past the minimum block size:
346 const uint256& hash = tx.GetHash();
347 double dPriorityDelta = 0;
348 CAmount nFeeDelta = 0;
349 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
350 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
352 //fprintf(stderr,"fee rate skip\n");
355 // Prioritise by fee once past the priority size or we run out of high-priority
358 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
361 comparer = TxPriorityCompare(fSortedByFee);
362 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
365 if (!view.HaveInputs(tx))
367 //fprintf(stderr,"dont have inputs\n");
370 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
372 nTxSigOps += GetP2SHSigOpCount(tx, view);
373 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
375 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
378 // Note that flags: we don't want to set mempool/IsStandard()
379 // policy here, but we still have to ensure that the block we
380 // create only contains transactions that are valid in new blocks.
381 CValidationState state;
382 PrecomputedTransactionData txdata(tx);
383 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
385 //fprintf(stderr,"context failure\n");
388 UpdateCoins(tx, view, nHeight);
391 pblock->vtx.push_back(tx);
392 pblocktemplate->vTxFees.push_back(nTxFees);
393 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
394 nBlockSize += nTxSize;
396 nBlockSigOps += nTxSigOps;
401 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
404 // Add transactions that depend on this one to the priority queue
405 if (mapDependers.count(hash))
407 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
409 if (!porphan->setDependsOn.empty())
411 porphan->setDependsOn.erase(hash);
412 if (porphan->setDependsOn.empty())
414 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
415 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
422 nLastBlockTx = nBlockTx;
423 nLastBlockSize = nBlockSize;
424 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
425 //pblock->nTime = blocktime + 1;
426 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
427 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
428 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
430 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
431 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
432 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
433 // blocktime = pindexPrev->GetMedianTimePast() + 60;
434 if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
437 if ( GetAdjustedTime() < blocktime-13 )
439 pblock->vtx.push_back(txStaked);
440 pblocktemplate->vTxFees.push_back(txfees);
441 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
443 pblock->nTime = blocktime;
444 //printf("PoS ht.%d t%u\n",(int32_t)chainActive.Tip()->nHeight+1,blocktime);
445 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
448 // Create coinbase tx
449 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
451 txNew.vin[0].prevout.SetNull();
452 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
454 txNew.vout.resize(1);
455 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
456 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()) + nFees;
457 txNew.nExpiryHeight = 0;
458 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
460 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
461 // to transaction if so, cast for GTE operator
462 if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
464 int32_t opretlen, p2shlen, scriptlen;
465 CScriptExt opretScript = CScriptExt();
467 txNew.vout.resize(2);
469 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
470 // protected only by the time lock rather than 100% inaccessible
471 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
472 if (!scriptPubKeyIn.IsPayToScriptHash())
473 opretScript += scriptPubKeyIn;
475 txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
476 txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
477 txNew.vout[1].nValue = 0;
478 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
479 else if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
481 int32_t i; uint8_t *ptr;
482 txNew.vout.resize(2);
483 txNew.vout[1].nValue = commission;
484 txNew.vout[1].scriptPubKey.resize(35);
485 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
488 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
489 ptr[34] = OP_CHECKSIG;
490 //printf("autocreate commision vout\n");
493 pblock->vtx[0] = txNew;
494 pblocktemplate->vTxFees[0] = -nFees;
497 arith_uint256 nonce = UintToArith256(GetRandHash());
499 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
500 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
502 pblock->nNonce = ArithToUint256(nonce);
505 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
506 pblock->hashReserved = uint256();
507 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
509 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
510 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
512 pblock->nSolution.clear();
513 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
514 if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
516 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
517 if ( pblock->nTime < pindexPrev->nTime+65 )
518 pblock->nTime = pindexPrev->nTime + 65;
519 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
522 pblock->vtx.push_back(txNotary);
523 pblocktemplate->vTxFees.push_back(txfees);
524 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
526 //fprintf(stderr,"added notaryvin\n");
530 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
536 CValidationState state;
537 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
539 //static uint32_t counter;
540 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
541 // fprintf(stderr,"warning: miner testblockvalidity failed\n");
547 return pblocktemplate.release();
552 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
554 boost::optional<CScript> GetMinerScriptPubKey()
558 CBitcoinAddress addr;
559 if (addr.SetString(GetArg("-mineraddress", ""))) {
560 addr.GetKeyID(keyID);
564 if (!reservekey.GetReservedKey(pubkey)) {
565 return boost::optional<CScript>();
567 keyID = pubkey.GetID();
569 return boost::optional<CScript>();
573 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
578 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
580 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
582 CBlockTemplate* CreateNewBlockWithKey()
584 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
590 return CreateNewBlock(*scriptPubKey);
593 //////////////////////////////////////////////////////////////////////////////
600 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
602 // Update nExtraNonce
603 static uint256 hashPrevBlock;
604 if (hashPrevBlock != pblock->hashPrevBlock)
607 hashPrevBlock = pblock->hashPrevBlock;
610 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
611 CMutableTransaction txCoinbase(pblock->vtx[0]);
612 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
613 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
615 pblock->vtx[0] = txCoinbase;
616 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
620 //////////////////////////////////////////////////////////////////////////////
625 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
627 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
628 if ( USE_EXTERNAL_PUBKEY != 0 )
630 //fprintf(stderr,"use notary pubkey\n");
631 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
635 if (!reservekey.GetReservedKey(pubkey))
639 scriptPubKey.resize(35);
640 ptr = (uint8_t *)pubkey.begin();
641 script = (uint8_t *)scriptPubKey.data();
644 script[i+1] = ptr[i];
645 script[34] = OP_CHECKSIG;
646 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
648 return CreateNewBlock(scriptPubKey);
651 void komodo_broadcast(CBlock *pblock,int32_t limit)
654 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
657 BOOST_FOREACH(CNode* pnode, vNodes)
659 if ( pnode->hSocket == INVALID_SOCKET )
661 if ( (rand() % n) == 0 )
663 pnode->PushMessage("block", *pblock);
669 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
672 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
674 static bool ProcessBlockFound(CBlock* pblock)
675 #endif // ENABLE_WALLET
677 LogPrintf("%s\n", pblock->ToString());
678 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
683 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
685 uint256 hash; int32_t i;
686 hash = pblock->hashPrevBlock;
687 for (i=31; i>=0; i--)
688 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
689 fprintf(stderr," <- prev (stale)\n");
690 hash = chainActive.Tip()->GetBlockHash();
691 for (i=31; i>=0; i--)
692 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
693 fprintf(stderr," <- chainTip (stale)\n");
695 return error("KomodoMiner: generated block is stale");
700 // Remove key from key pool
701 if ( IS_KOMODO_NOTARY == 0 )
703 if (GetArg("-mineraddress", "").empty()) {
704 // Remove key from key pool
705 reservekey.KeepKey();
708 // Track how many getdata requests this block gets
711 LOCK(wallet.cs_wallet);
712 wallet.mapRequestCount[pblock->GetHash()] = 0;
716 // Process this block the same as if we had received it from another node
717 CValidationState state;
718 if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
719 return error("KomodoMiner: ProcessNewBlock, block not accepted");
721 TrackMinedBlock(pblock->GetHash());
722 komodo_broadcast(pblock,16);
726 int32_t komodo_baseid(char *origbase);
727 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
728 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
729 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
730 extern int32_t KOMODO_LASTMINED;
731 int32_t roundrobin_delay;
732 arith_uint256 HASHTarget,HASHTarget_POW;
734 // wait for peers to connect
735 int32_t waitForPeers(const CChainParams &chainparams)
737 if (chainparams.MiningRequiresPeers())
743 fvNodesEmpty = vNodes.empty();
753 void static BitcoinMiner_noeq(CWallet *pwallet)
755 void static BitcoinMiner_noeq()
758 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
759 RenameThread("verushash-miner");
762 // Each thread has its own key
763 CReserveKey reservekey(pwallet);
766 const CChainParams& chainparams = Params();
767 // Each thread has its own counter
768 unsigned int nExtraNonce = 0;
769 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
770 solnPlaceholder.resize(Eh200_9.SolutionWidth);
771 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
773 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
776 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
780 // try a nice clean peer connection to start
781 waitForPeers(chainparams);
785 curTip = chainActive.Tip();
786 printf("Verifying block height %d \n", chainActive.Tip()->nHeight);
787 MilliSleep(1000 + rand() % 1900);
788 } while (curTip != chainActive.Tip());
790 SetThreadPriority(THREAD_PRIORITY_LOWEST);
793 printf("Mining height %d\n", chainActive.Tip()->nHeight + 1);
798 fprintf(stderr,"Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
802 waitForPeers(chainparams);
806 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
807 CBlockIndex* pindexPrev = chainActive.Tip();
808 if ( Mining_height != pindexPrev->nHeight+1 )
810 Mining_height = pindexPrev->nHeight+1;
811 Mining_start = (uint32_t)time(NULL);
814 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
817 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
819 CBlockTemplate *ptr = CreateNewBlockWithKey();
823 static uint32_t counter;
824 if ( counter++ < 100 )
825 fprintf(stderr,"created illegal block, retry\n");
828 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
829 if (!pblocktemplate.get())
831 if (GetArg("-mineraddress", "").empty()) {
832 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
833 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
835 // Should never reach here, because -mineraddress validity is checked in init.cpp
836 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
840 CBlock *pblock = &pblocktemplate->block;
841 if ( ASSETCHAINS_SYMBOL[0] != 0 )
843 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
845 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
847 static uint32_t counter;
848 if ( counter++ < 10 )
849 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
852 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
855 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
856 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
857 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
861 uint32_t savebits; int64_t nStart = GetTime();
863 pblock->nSolution = solnPlaceholder;
864 savebits = pblock->nBits;
865 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
866 arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
870 if ( pindexPrev != chainActive.Tip() )
872 printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
879 // for speed check multiples at a time
880 for (int i = 0; i < ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; i++)
882 solutionTargetChecks.increment();
884 // Update nNonce and nTime
885 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
887 if ( UintToArith256(pblock->GetHash()) <= hashTarget )
889 SetThreadPriority(THREAD_PRIORITY_NORMAL);
891 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
892 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
894 LogPrintf("KomodoMiner using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
895 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
896 printf("Found block %d \n", Mining_height );
897 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
898 printf(" hash: %s \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
899 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
900 printf("- timelocked until block %i\n", unlockTime);
905 ProcessBlockFound(pblock, *pwallet, reservekey);
907 ProcessBlockFound(pblock));
909 SetThreadPriority(THREAD_PRIORITY_LOWEST);
911 // In regression test mode, stop mining after a block is found.
912 if (chainparams.MineBlocksOnDemand()) {
913 throw boost::thread_interrupted();
919 if ((UintToArith256(pblock->nNonce) & mask) == mask)
926 // Check for stop or if block needs to be rebuilt
927 boost::this_thread::interruption_point();
929 if (vNodes.empty() && chainparams.MiningRequiresPeers())
931 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
933 fprintf(stderr,"no nodes, attempting reconnect\n");
938 if ((UintToArith256(pblock->nNonce) & mask) == mask)
940 fprintf(stderr,"%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
944 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
946 fprintf(stderr,"timeout, retrying\n");
950 if ( pindexPrev != chainActive.Tip() )
952 printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
956 pblock->nBits = savebits;
957 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
958 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
960 // Changing pblock->nTime can change work required on testnet:
961 hashTarget.SetCompact(pblock->nBits);
966 catch (const boost::thread_interrupted&)
969 LogPrintf("KomodoMiner terminated\n");
972 catch (const std::runtime_error &e)
975 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
982 void static BitcoinMiner(CWallet *pwallet)
984 void static BitcoinMiner()
987 LogPrintf("KomodoMiner started\n");
988 SetThreadPriority(THREAD_PRIORITY_LOWEST);
989 RenameThread("komodo-miner");
990 const CChainParams& chainparams = Params();
993 // Each thread has its own key
994 CReserveKey reservekey(pwallet);
997 // Each thread has its own counter
998 unsigned int nExtraNonce = 0;
1000 unsigned int n = chainparams.EquihashN();
1001 unsigned int k = chainparams.EquihashK();
1002 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
1003 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
1006 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1009 komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
1012 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
1014 //else solver = "default";
1015 assert(solver == "tromp" || solver == "default");
1016 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
1017 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1018 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
1020 bool cancelSolver = false;
1021 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
1022 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1023 std::lock_guard<std::mutex> lock{m_cs};
1024 cancelSolver = true;
1027 miningTimer.start();
1030 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1031 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
1034 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
1036 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
1038 // Busy-wait for the network to come online so we don't waste time mining
1039 // on an obsolete chain. In regtest mode we expect to fly solo.
1045 fvNodesEmpty = vNodes.empty();
1047 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
1050 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
1053 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
1054 miningTimer.start();
1056 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
1058 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
1064 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1065 CBlockIndex* pindexPrev = chainActive.Tip();
1066 if ( Mining_height != pindexPrev->nHeight+1 )
1068 Mining_height = pindexPrev->nHeight+1;
1069 Mining_start = (uint32_t)time(NULL);
1071 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
1073 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
1076 #ifdef ENABLE_WALLET
1077 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
1079 CBlockTemplate *ptr = CreateNewBlockWithKey();
1083 static uint32_t counter;
1084 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1085 fprintf(stderr,"created illegal block, retry\n");
1089 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1090 if (!pblocktemplate.get())
1092 if (GetArg("-mineraddress", "").empty()) {
1093 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
1095 // Should never reach here, because -mineraddress validity is checked in init.cpp
1096 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
1100 CBlock *pblock = &pblocktemplate->block;
1101 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1103 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1105 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1107 static uint32_t counter;
1108 if ( counter++ < 10 )
1109 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1112 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1115 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1116 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1120 uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
1121 savebits = pblock->nBits;
1122 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
1123 roundrobin_delay = ROUNDROBIN_DELAY;
1124 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
1127 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
1129 int32_t dispflag = 0;
1130 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
1132 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
1133 if ( nonzpkeys > 0 )
1135 for (i=0; i<33; i++)
1136 if( pubkeys[0][i] != 0 )
1140 else externalflag = 0;
1141 if ( NOTARY_PUBKEY33[0] != 0 )
1143 for (i=1; i<66; i++)
1144 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1146 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1147 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
1148 for (j=gpucount=0; j<65; j++)
1150 if ( dispflag != 0 )
1153 fprintf(stderr,"%d ",mids[j]);
1154 else fprintf(stderr,"GPU ");
1156 if ( mids[j] == -1 )
1159 if ( gpucount > j/2 )
1164 else i = ((Mining_height + notaryid) % 64);
1165 delta = sqrt((double)gpucount - j/2) / 2.;
1166 roundrobin_delay += ((delta * i) / 64) - delta;
1167 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
1169 if ( dispflag != 0 )
1170 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay);
1172 for (j=0; j<65; j++)
1173 if ( mids[j] == notaryid )
1176 KOMODO_LASTMINED = 0;
1177 } else fprintf(stderr,"no nonz pubkeys\n");
1178 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
1180 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
1181 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
1182 } //else fprintf(stderr,"duplicate at j.%d\n",j);
1183 } else Mining_start = 0;
1184 } else Mining_start = 0;
1185 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
1188 /*if ( Mining_height <= 100 )
1193 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1194 for (z=31; z>=0; z--)
1195 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1196 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1200 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
1202 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1207 KOMODO_CHOSEN_ONE = 0;
1209 crypto_generichash_blake2b_state state;
1210 EhInitialiseState(n, k, state);
1211 // I = the block header minus nonce and solution.
1212 CEquihashInput I{*pblock};
1213 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1216 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
1218 crypto_generichash_blake2b_state curr_state;
1220 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
1221 // (x_1, x_2, ...) = A(I, V, n, k)
1222 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
1223 arith_uint256 hashTarget;
1224 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 )
1225 hashTarget = HASHTarget_POW;
1226 else hashTarget = HASHTarget;
1227 std::function<bool(std::vector<unsigned char>)> validBlock =
1228 #ifdef ENABLE_WALLET
1229 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
1231 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
1233 (std::vector<unsigned char> soln) {
1234 int32_t z; arith_uint256 h; CBlock B;
1235 // Write the solution to the hash and compute the result.
1236 LogPrint("pow", "- Checking solution against target\n");
1237 pblock->nSolution = soln;
1238 solutionTargetChecks.increment();
1240 h = UintToArith256(B.GetHash());
1241 if ( h > hashTarget )
1243 /*for (z=31; z>=16; z--)
1244 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1245 fprintf(stderr," mined ");
1246 for (z=31; z>=16; z--)
1247 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
1248 fprintf(stderr," hashTarget ");
1249 for (z=31; z>=16; z--)
1250 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1251 fprintf(stderr," POW\n");*/
1252 if ( NOTARY_PUBKEY33[0] != 0 && B.nTime > GetAdjustedTime() )
1254 fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1255 while ( GetAdjustedTime() < B.nTime-2 )
1258 if ( chainActive.Tip()->nHeight >= Mining_height )
1260 fprintf(stderr,"new block arrived\n");
1265 if ( ASSETCHAINS_STAKED == 0 )
1267 if ( NOTARY_PUBKEY33[0] != 0 )
1270 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
1271 MilliSleep((rand() % (r * 1000)) + 1000);
1276 if ( NOTARY_PUBKEY33[0] != 0 )
1278 printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
1279 while ( GetAdjustedTime() < B.nTime )
1284 uint256 tmp = B.GetHash();
1285 int32_t z; for (z=31; z>=0; z--)
1286 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1287 fprintf(stderr," mined block!\n");
1290 CValidationState state;
1291 if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
1293 h = UintToArith256(B.GetHash());
1294 for (z=31; z>=0; z--)
1295 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1296 fprintf(stderr," Invalid block mined, try again\n");
1299 KOMODO_CHOSEN_ONE = 1;
1301 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1302 LogPrintf("KomodoMiner:\n");
1303 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
1304 #ifdef ENABLE_WALLET
1305 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
1307 if (ProcessBlockFound(&B)) {
1309 // Ignore chain updates caused by us
1310 std::lock_guard<std::mutex> lock{m_cs};
1311 cancelSolver = false;
1313 KOMODO_CHOSEN_ONE = 0;
1314 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1315 // In regression test mode, stop mining after a block is found.
1316 if (chainparams.MineBlocksOnDemand()) {
1317 // Increment here because throwing skips the call below
1318 ehSolverRuns.increment();
1319 throw boost::thread_interrupted();
1321 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1325 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1326 std::lock_guard<std::mutex> lock{m_cs};
1327 return cancelSolver;
1330 // TODO: factor this out into a function with the same API for each solver.
1331 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1332 // Create solver and initialize it.
1334 eq.setstate(&curr_state);
1336 // Initialization done, start algo driver.
1338 eq.xfull = eq.bfull = eq.hfull = 0;
1340 for (u32 r = 1; r < WK; r++) {
1341 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1342 eq.xfull = eq.bfull = eq.hfull = 0;
1346 ehSolverRuns.increment();
1348 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1349 for (size_t s = 0; s < eq.nsols; s++) {
1350 LogPrint("pow", "Checking solution %d\n", s+1);
1351 std::vector<eh_index> index_vector(PROOFSIZE);
1352 for (size_t i = 0; i < PROOFSIZE; i++) {
1353 index_vector[i] = eq.sols[s][i];
1355 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1357 if (validBlock(sol_char)) {
1358 // If we find a POW solution, do not try other solutions
1359 // because they become invalid as we created a new block in blockchain.
1365 // If we find a valid block, we rebuild
1366 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1367 ehSolverRuns.increment();
1369 int32_t i; uint256 hash = pblock->GetHash();
1370 for (i=0; i<32; i++)
1371 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1372 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1374 KOMODO_MAYBEMINED = Mining_height;
1377 } catch (EhSolverCancelledException&) {
1378 LogPrint("pow", "Equihash solver cancelled\n");
1379 std::lock_guard<std::mutex> lock{m_cs};
1380 cancelSolver = false;
1384 // Check for stop or if block needs to be rebuilt
1385 boost::this_thread::interruption_point();
1386 // Regtest mode doesn't require peers
1387 if ( FOUND_BLOCK != 0 )
1390 fprintf(stderr,"FOUND_BLOCK!\n");
1393 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1395 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1397 fprintf(stderr,"no nodes, break\n");
1401 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1403 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1404 fprintf(stderr,"0xffff, break\n");
1407 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1409 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1410 fprintf(stderr,"timeout, break\n");
1413 if ( pindexPrev != chainActive.Tip() )
1415 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1416 fprintf(stderr,"Tip advanced, break\n");
1419 // Update nNonce and nTime
1420 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1421 pblock->nBits = savebits;
1422 /*if ( NOTARY_PUBKEY33[0] == 0 )
1425 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1426 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1428 // Changing pblock->nTime can change work required on testnet:
1429 HASHTarget.SetCompact(pblock->nBits);
1430 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1436 catch (const boost::thread_interrupted&)
1440 LogPrintf("KomodoMiner terminated\n");
1443 catch (const std::runtime_error &e)
1447 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1454 #ifdef ENABLE_WALLET
1455 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1457 void GenerateBitcoins(bool fGenerate, int nThreads)
1460 static boost::thread_group* minerThreads = NULL;
1463 nThreads = GetNumCores();
1465 if (minerThreads != NULL)
1467 minerThreads->interrupt_all();
1468 delete minerThreads;
1469 minerThreads = NULL;
1472 if (nThreads == 0 || !fGenerate)
1475 minerThreads = new boost::thread_group();
1476 for (int i = 0; i < nThreads; i++) {
1477 #ifdef ENABLE_WALLET
1478 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1479 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1481 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
1483 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1484 minerThreads->create_thread(&BitcoinMiner);
1486 minerThreads->create_thread(&BitcoinMiner_noeq);
1491 #endif // ENABLE_MINING