]> Git Repo - VerusCoin.git/blame_incremental - src/miner.cpp
Test
[VerusCoin.git] / src / miner.cpp
... / ...
CommitLineData
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.
5
6#include "miner.h"
7#ifdef ENABLE_MINING
8#include "pow/tromp/equi_miner.h"
9#endif
10
11#include "amount.h"
12#include "base58.h"
13#include "chainparams.h"
14#include "consensus/consensus.h"
15#include "consensus/upgrades.h"
16#include "consensus/validation.h"
17#ifdef ENABLE_MINING
18#include "crypto/equihash.h"
19#endif
20#include "hash.h"
21#include "main.h"
22#include "metrics.h"
23#include "net.h"
24#include "pow.h"
25#include "primitives/transaction.h"
26#include "random.h"
27#include "timedata.h"
28#include "ui_interface.h"
29#include "util.h"
30#include "utilmoneystr.h"
31#ifdef ENABLE_WALLET
32#include "wallet/wallet.h"
33#endif
34
35#include "sodium.h"
36
37#include <boost/thread.hpp>
38#include <boost/tuple/tuple.hpp>
39#ifdef ENABLE_MINING
40#include <functional>
41#endif
42#include <mutex>
43
44using namespace std;
45
46//////////////////////////////////////////////////////////////////////////////
47//
48// BitcoinMiner
49//
50
51//
52// Unconfirmed transactions in the memory pool often depend on other
53// transactions in the memory pool. When we select transactions from the
54// pool, we select by highest priority or fee rate, so we might consider
55// transactions that depend on transactions that aren't yet in the block.
56// The COrphan class keeps track of these 'temporary orphans' while
57// CreateBlock is figuring out which transactions to include.
58//
59class COrphan
60{
61public:
62 const CTransaction* ptx;
63 set<uint256> setDependsOn;
64 CFeeRate feeRate;
65 double dPriority;
66
67 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
68 {
69 }
70};
71
72uint64_t nLastBlockTx = 0;
73uint64_t nLastBlockSize = 0;
74
75// We want to sort transactions by priority and fee rate, so:
76typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
77class TxPriorityCompare
78{
79 bool byFee;
80
81public:
82 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
83
84 bool operator()(const TxPriority& a, const TxPriority& b)
85 {
86 if (byFee)
87 {
88 if (a.get<1>() == b.get<1>())
89 return a.get<0>() < b.get<0>();
90 return a.get<1>() < b.get<1>();
91 }
92 else
93 {
94 if (a.get<0>() == b.get<0>())
95 return a.get<1>() < b.get<1>();
96 return a.get<0>() < b.get<0>();
97 }
98 }
99};
100
101void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
102{
103 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
104}
105
106#include "komodo_defs.h"
107
108extern 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;
109extern uint64_t ASSETCHAINS_REWARD,ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED;
110extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
111extern std::string NOTARY_PUBKEY;
112extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
113uint32_t Mining_start,Mining_height;
114int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
115int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
116uint64_t komodo_paxtotal();
117int32_t komodo_baseid(char *origbase);
118int32_t komodo_is_issuer();
119int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
120int32_t komodo_isrealtime(int32_t *kmdheightp);
121int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
122uint64_t komodo_commission(const CBlock &block);
123int32_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);
124
125CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
126{
127 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
128 // Create new block
129 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
130 if(!pblocktemplate.get())
131 {
132 fprintf(stderr,"pblocktemplate.get() failure\n");
133 return NULL;
134 }
135 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
136 if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
137 {
138 isrealtime = komodo_isrealtime(&kmdheight);
139 deposits = komodo_paxtotal();
140 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
141 {
142 deposits = komodo_paxtotal();
143 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
144 {
145 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
146 }
147 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
148 {
149 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);
150 break;
151 }
152 sleep(10);
153 }
154 KOMODO_ON_DEMAND = 0;
155 if ( 0 && deposits != 0 )
156 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());
157 }
158 // -regtest only: allow overriding block.nVersion with
159 // -blockversion=N to test forking scenarios
160 if (Params().MineBlocksOnDemand())
161 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
162
163 // Add dummy coinbase tx as first transaction
164 pblock->vtx.push_back(CTransaction());
165 pblocktemplate->vTxFees.push_back(-1); // updated at end
166 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
167
168 // Largest block you're willing to create:
169 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
170 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
171 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
172
173 // How much of the block should be dedicated to high-priority transactions,
174 // included regardless of the fees they pay
175 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
176 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
177
178 // Minimum block size you want to create; block will be filled with free transactions
179 // until there are no more or the block reaches this size:
180 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
181 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
182
183 // Collect memory pool transactions into the block
184 CAmount nFees = 0;
185
186 {
187 LOCK2(cs_main, mempool.cs);
188 CBlockIndex* pindexPrev = chainActive.Tip();
189 const int nHeight = pindexPrev->nHeight + 1;
190 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
191 pblock->nTime = GetAdjustedTime();
192 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
193 CCoinsViewCache view(pcoinsTip);
194 uint32_t expired; uint64_t commission;
195
196 // Priority order to process transactions
197 list<COrphan> vOrphan; // list memory doesn't move
198 map<uint256, vector<COrphan*> > mapDependers;
199 bool fPrintPriority = GetBoolArg("-printpriority", false);
200
201 // This vector will be sorted into a priority queue:
202 vector<TxPriority> vecPriority;
203 vecPriority.reserve(mempool.mapTx.size());
204 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
205 mi != mempool.mapTx.end(); ++mi)
206 {
207 const CTransaction& tx = mi->GetTx();
208
209 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
210 ? nMedianTimePast
211 : pblock->GetBlockTime();
212
213 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
214 continue;
215 if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
216 {
217 fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure\n");
218 continue;
219 }
220 COrphan* porphan = NULL;
221 double dPriority = 0;
222 CAmount nTotalIn = 0;
223 bool fMissingInputs = false;
224 BOOST_FOREACH(const CTxIn& txin, tx.vin)
225 {
226 // Read prev transaction
227 if (!view.HaveCoins(txin.prevout.hash))
228 {
229 // This should never happen; all transactions in the memory
230 // pool should connect to either transactions in the chain
231 // or other transactions in the memory pool.
232 if (!mempool.mapTx.count(txin.prevout.hash))
233 {
234 LogPrintf("ERROR: mempool transaction missing input\n");
235 if (fDebug) assert("mempool transaction missing input" == 0);
236 fMissingInputs = true;
237 if (porphan)
238 vOrphan.pop_back();
239 break;
240 }
241
242 // Has to wait for dependencies
243 if (!porphan)
244 {
245 // Use list for automatic deletion
246 vOrphan.push_back(COrphan(&tx));
247 porphan = &vOrphan.back();
248 }
249 mapDependers[txin.prevout.hash].push_back(porphan);
250 porphan->setDependsOn.insert(txin.prevout.hash);
251 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
252 continue;
253 }
254 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
255 assert(coins);
256
257 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
258 nTotalIn += nValueIn;
259
260 int nConf = nHeight - coins->nHeight;
261
262 dPriority += (double)nValueIn * nConf;
263 }
264 nTotalIn += tx.GetJoinSplitValueIn();
265
266 if (fMissingInputs) continue;
267
268 // Priority is sum(valuein * age) / modified_txsize
269 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
270 dPriority = tx.ComputePriority(dPriority, nTxSize);
271
272 uint256 hash = tx.GetHash();
273 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
274
275 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
276
277 if (porphan)
278 {
279 porphan->dPriority = dPriority;
280 porphan->feeRate = feeRate;
281 }
282 else
283 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
284 }
285
286 // Collect transactions into block
287 uint64_t nBlockSize = 1000;
288 uint64_t nBlockTx = 0;
289 int64_t interest;
290 int nBlockSigOps = 100;
291 bool fSortedByFee = (nBlockPrioritySize <= 0);
292
293 TxPriorityCompare comparer(fSortedByFee);
294 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
295
296 while (!vecPriority.empty())
297 {
298 // Take highest priority transaction off the priority queue:
299 double dPriority = vecPriority.front().get<0>();
300 CFeeRate feeRate = vecPriority.front().get<1>();
301 const CTransaction& tx = *(vecPriority.front().get<2>());
302
303 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
304 vecPriority.pop_back();
305
306 // Size limits
307 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
308 if (nBlockSize + nTxSize >= nBlockMaxSize)
309 continue;
310
311 // Legacy limits on sigOps:
312 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
313 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
314 continue;
315
316 // Skip free transactions if we're past the minimum block size:
317 const uint256& hash = tx.GetHash();
318 double dPriorityDelta = 0;
319 CAmount nFeeDelta = 0;
320 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
321 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
322 continue;
323
324 // Prioritise by fee once past the priority size or we run out of high-priority
325 // transactions:
326 if (!fSortedByFee &&
327 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
328 {
329 fSortedByFee = true;
330 comparer = TxPriorityCompare(fSortedByFee);
331 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
332 }
333
334 if (!view.HaveInputs(tx))
335 continue;
336
337 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
338
339 nTxSigOps += GetP2SHSigOpCount(tx, view);
340 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
341 continue;
342
343 // Note that flags: we don't want to set mempool/IsStandard()
344 // policy here, but we still have to ensure that the block we
345 // create only contains transactions that are valid in new blocks.
346 CValidationState state;
347 PrecomputedTransactionData txdata(tx);
348 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
349 continue;
350
351 UpdateCoins(tx, view, nHeight);
352
353 // Added
354 pblock->vtx.push_back(tx);
355 pblocktemplate->vTxFees.push_back(nTxFees);
356 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
357 nBlockSize += nTxSize;
358 ++nBlockTx;
359 nBlockSigOps += nTxSigOps;
360 nFees += nTxFees;
361
362 if (fPrintPriority)
363 {
364 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
365 }
366
367 // Add transactions that depend on this one to the priority queue
368 if (mapDependers.count(hash))
369 {
370 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
371 {
372 if (!porphan->setDependsOn.empty())
373 {
374 porphan->setDependsOn.erase(hash);
375 if (porphan->setDependsOn.empty())
376 {
377 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
378 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
379 }
380 }
381 }
382 }
383 }
384
385 nLastBlockTx = nBlockTx;
386 nLastBlockSize = nBlockSize;
387 blocktime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
388 //pblock->nTime = blocktime + 1;
389 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
390 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
391 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
392 {
393 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
394 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
395 blocktime += 2;
396 if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
397 {
398 CAmount txfees = 0;
399 pblock->vtx.push_back(txStaked);
400 pblocktemplate->vTxFees.push_back(txfees);
401 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
402 nFees += txfees;
403 pblock->nTime = blocktime;
404 if ( GetAdjustedTime() < pblock->nTime )
405 {
406 printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime()));
407 while ( GetAdjustedTime()+30 < pblock->nTime )
408 {
409 sleep(30);
410 fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime()));
411 }
412 fprintf(stderr,"finished waiting\n");
413 //sleep(pblock->nTime - GetAdjustedTime());
414 }
415
416 } else fprintf(stderr,"no utxos eligible for staking\n");
417 }
418
419 // Create coinbase tx
420 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
421 txNew.vin.resize(1);
422 txNew.vin[0].prevout.SetNull();
423 txNew.vout.resize(1);
424 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
425 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
426 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
427 txNew.nExpiryHeight = 0;
428 // Add fees
429 txNew.vout[0].nValue += nFees;
430 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
431
432 /*if ( ASSETCHAINS_SYMBOL[0] == 0 )
433 {
434 int32_t i,opretlen; uint8_t opret[256],*ptr;
435 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
436 {
437 if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed
438 {
439 txNew.vout.resize(2);
440 txNew.vout[1].scriptPubKey.resize(opretlen);
441 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
442 for (i=0; i<opretlen; i++)
443 ptr[i] = opret[i];
444 txNew.vout[1].nValue = 0;
445 //fprintf(stderr,"opretlen.%d\n",opretlen);
446 } //else printf("null opretlen for prices\n");
447 }
448 }
449 else if ( komodo_is_issuer() != 0 )
450 {
451 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
452 if ( txNew.vout.size() > 1 )
453 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
454 }*/
455
456 pblock->vtx[0] = txNew;
457 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission(pblocktemplate->block)) != 0 )
458 {
459 int32_t i; uint8_t *ptr;
460 txNew.vout.resize(2);
461 txNew.vout[1].nValue = commission;
462 txNew.vout[1].scriptPubKey.resize(35);
463 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
464 ptr[0] = 33;
465 for (i=0; i<33; i++)
466 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
467 ptr[34] = OP_CHECKSIG;
468 //printf("autocreate commision vout\n");
469 pblock->vtx[0] = txNew;
470 }
471 pblocktemplate->vTxFees[0] = -nFees;
472 // Randomise nonce
473 arith_uint256 nonce = UintToArith256(GetRandHash());
474 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
475 nonce <<= 32;
476 nonce >>= 16;
477 pblock->nNonce = ArithToUint256(nonce);
478
479 // Fill in header
480 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
481 pblock->hashReserved = uint256();
482 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
483 {
484 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
485 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
486 }
487 pblock->nSolution.clear();
488 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
489
490 CValidationState state;
491 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
492 {
493 static uint32_t counter;
494 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
495 fprintf(stderr,"warning: miner testblockvalidity failed\n");
496 return(0);
497 }
498 }
499
500 return pblocktemplate.release();
501}
502
503/*
504#ifdef ENABLE_WALLET
505boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
506#else
507boost::optional<CScript> GetMinerScriptPubKey()
508#endif
509{
510 CKeyID keyID;
511 CBitcoinAddress addr;
512 if (addr.SetString(GetArg("-mineraddress", ""))) {
513 addr.GetKeyID(keyID);
514 } else {
515#ifdef ENABLE_WALLET
516 CPubKey pubkey;
517 if (!reservekey.GetReservedKey(pubkey)) {
518 return boost::optional<CScript>();
519 }
520 keyID = pubkey.GetID();
521#else
522 return boost::optional<CScript>();
523#endif
524 }
525
526 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
527 return scriptPubKey;
528}
529
530#ifdef ENABLE_WALLET
531CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
532{
533 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
534#else
535CBlockTemplate* CreateNewBlockWithKey()
536{
537 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
538#endif
539
540 if (!scriptPubKey) {
541 return NULL;
542 }
543 return CreateNewBlock(*scriptPubKey);
544}*/
545
546//////////////////////////////////////////////////////////////////////////////
547//
548// Internal miner
549//
550
551#ifdef ENABLE_MINING
552
553void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
554{
555 // Update nExtraNonce
556 static uint256 hashPrevBlock;
557 if (hashPrevBlock != pblock->hashPrevBlock)
558 {
559 nExtraNonce = 0;
560 hashPrevBlock = pblock->hashPrevBlock;
561 }
562 ++nExtraNonce;
563 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
564 CMutableTransaction txCoinbase(pblock->vtx[0]);
565 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
566 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
567
568 pblock->vtx[0] = txCoinbase;
569 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
570}
571
572#ifdef ENABLE_WALLET
573//////////////////////////////////////////////////////////////////////////////
574//
575// Internal miner
576//
577
578CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
579{
580 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
581 if ( USE_EXTERNAL_PUBKEY != 0 )
582 {
583 //fprintf(stderr,"use notary pubkey\n");
584 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
585 }
586 else
587 {
588 if (!reservekey.GetReservedKey(pubkey))
589 {
590 return NULL;
591 }
592 scriptPubKey.resize(35);
593 ptr = (uint8_t *)pubkey.begin();
594 script = (uint8_t *)scriptPubKey.data();
595 script[0] = 33;
596 for (i=0; i<33; i++)
597 script[i+1] = ptr[i];
598 script[34] = OP_CHECKSIG;
599 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
600 }
601 return CreateNewBlock(scriptPubKey);
602}
603
604
605static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
606#else
607static bool ProcessBlockFound(CBlock* pblock)
608#endif // ENABLE_WALLET
609{
610 LogPrintf("%s\n", pblock->ToString());
611 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
612
613 // Found a solution
614 {
615 LOCK(cs_main);
616 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
617 {
618 uint256 hash; int32_t i;
619 hash = pblock->hashPrevBlock;
620 for (i=31; i>=0; i--)
621 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
622 fprintf(stderr," <- prev (stale)\n");
623 hash = chainActive.Tip()->GetBlockHash();
624 for (i=31; i>=0; i--)
625 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
626 fprintf(stderr," <- chainTip (stale)\n");
627
628 return error("KomodoMiner: generated block is stale");
629 }
630 }
631
632#ifdef ENABLE_WALLET
633 // Remove key from key pool
634 if ( IS_KOMODO_NOTARY == 0 )
635 {
636 if (GetArg("-mineraddress", "").empty()) {
637 // Remove key from key pool
638 reservekey.KeepKey();
639 }
640 }
641 // Track how many getdata requests this block gets
642 //if ( 0 )
643 {
644 LOCK(wallet.cs_wallet);
645 wallet.mapRequestCount[pblock->GetHash()] = 0;
646 }
647#endif
648
649 // Process this block the same as if we had received it from another node
650 CValidationState state;
651 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
652 return error("KomodoMiner: ProcessNewBlock, block not accepted");
653
654 TrackMinedBlock(pblock->GetHash());
655
656 return true;
657}
658
659int32_t komodo_baseid(char *origbase);
660int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
661arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
662int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
663extern int32_t KOMODO_LASTMINED;
664int32_t roundrobin_delay;
665arith_uint256 HASHTarget;
666
667#ifdef ENABLE_WALLET
668void static BitcoinMiner(CWallet *pwallet)
669#else
670void static BitcoinMiner()
671#endif
672{
673 LogPrintf("KomodoMiner started\n");
674 SetThreadPriority(THREAD_PRIORITY_LOWEST);
675 RenameThread("komodo-miner");
676 const CChainParams& chainparams = Params();
677
678#ifdef ENABLE_WALLET
679 // Each thread has its own key
680 CReserveKey reservekey(pwallet);
681#endif
682
683 // Each thread has its own counter
684 unsigned int nExtraNonce = 0;
685
686 unsigned int n = chainparams.EquihashN();
687 unsigned int k = chainparams.EquihashK();
688 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
689 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
690 {
691 sleep(1);
692 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
693 break;
694 }
695 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
696
697 std::string solver;
698 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
699 solver = "tromp";
700 //else solver = "default";
701 assert(solver == "tromp" || solver == "default");
702 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
703 if ( ASSETCHAINS_SYMBOL[0] != 0 )
704 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
705 std::mutex m_cs;
706 bool cancelSolver = false;
707 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
708 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
709 std::lock_guard<std::mutex> lock{m_cs};
710 cancelSolver = true;
711 }
712 );
713 miningTimer.start();
714
715 try {
716 if ( ASSETCHAINS_SYMBOL[0] != 0 )
717 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
718 while (true)
719 {
720 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
721 {
722 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
723 // break;
724 // Busy-wait for the network to come online so we don't waste time mining
725 // on an obsolete chain. In regtest mode we expect to fly solo.
726 miningTimer.stop();
727 do {
728 bool fvNodesEmpty;
729 {
730 LOCK(cs_vNodes);
731 fvNodesEmpty = vNodes.empty();
732 }
733 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
734 break;
735 MilliSleep(5000);
736 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
737
738 } while (true);
739 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
740 miningTimer.start();
741 }
742 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
743 {
744 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
745 sleep(3);
746 }*/
747 //
748 // Create new block
749 //
750 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
751 CBlockIndex* pindexPrev = chainActive.Tip();
752 if ( Mining_height != pindexPrev->nHeight+1 )
753 {
754 Mining_height = pindexPrev->nHeight+1;
755 Mining_start = (uint32_t)time(NULL);
756 }
757 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
758 {
759 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
760 sleep(3);
761 }
762#ifdef ENABLE_WALLET
763 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
764#else
765 CBlockTemplate *ptr = CreateNewBlockWithKey();
766#endif
767 if ( ptr == 0 )
768 {
769 static uint32_t counter;
770 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
771 fprintf(stderr,"created illegal block, retry\n");
772 continue;
773 }
774 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
775 if (!pblocktemplate.get())
776 {
777 if (GetArg("-mineraddress", "").empty()) {
778 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
779 } else {
780 // Should never reach here, because -mineraddress validity is checked in init.cpp
781 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
782 }
783 return;
784 }
785 CBlock *pblock = &pblocktemplate->block;
786 if ( ASSETCHAINS_SYMBOL[0] != 0 )
787 {
788 if ( ASSETCHAINS_REWARD == 0 )
789 {
790 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
791 {
792 static uint32_t counter;
793 if ( counter++ < 10 )
794 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
795 sleep(10);
796 continue;
797 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
798 }
799 }
800 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
801 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
802 //
803 // Search
804 //
805 uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
806 savebits = pblock->nBits;
807 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
808 roundrobin_delay = ROUNDROBIN_DELAY;
809 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
810 {
811 j = 65;
812 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
813 {
814 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
815 if ( nonzpkeys > 0 )
816 {
817 for (i=0; i<33; i++)
818 if( pubkeys[0][i] != 0 )
819 break;
820 if ( i == 33 )
821 externalflag = 1;
822 else externalflag = 0;
823 if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) )
824 {
825 for (i=1; i<66; i++)
826 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
827 break;
828 if ( externalflag == 0 && i != 66 )
829 printf("VIOLATION at %d\n",i);
830 for (j=gpucount=0; j<65; j++)
831 {
832 if ( mids[j] >= 0 || notaryid == 34 )
833 fprintf(stderr,"%d ",mids[j]);
834 else fprintf(stderr,"GPU ");
835 if ( mids[j] == -1 )
836 gpucount++;
837 }
838 if ( gpucount > j/2 )
839 {
840 double delta;
841 if ( notaryid < 0 )
842 i = (rand() % 64);
843 else i = ((Mining_height + notaryid) % 64);
844 delta = sqrt((double)gpucount - j/2) / 2.;
845 roundrobin_delay += ((delta * i) / 64) - delta;
846 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
847 }
848 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);
849 }
850 for (j=0; j<65; j++)
851 if ( mids[j] == notaryid )
852 break;
853 if ( j == 65 )
854 KOMODO_LASTMINED = 0;
855 } else fprintf(stderr,"no nonz pubkeys\n");
856 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
857 {
858 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
859 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
860 } //else fprintf(stderr,"duplicate at j.%d\n",j);
861 } else Mining_start = 0;
862 } else Mining_start = 0;
863 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
864 {
865 int32_t percPoS,z;
866 if ( Mining_height <= 100 )
867 {
868 sleep(60);
869 continue;
870 }
871 HASHTarget = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
872 for (z=31; z>=0; z--)
873 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
874 fprintf(stderr," PoW for staked coin\n");
875 }
876 while (true)
877 {
878 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
879 {
880 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
881 sleep(10);
882 break;
883 }*/
884 // Hash state
885 KOMODO_CHOSEN_ONE = 0;
886 crypto_generichash_blake2b_state state;
887 EhInitialiseState(n, k, state);
888 // I = the block header minus nonce and solution.
889 CEquihashInput I{*pblock};
890 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
891 ss << I;
892 // H(I||...
893 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
894 // H(I||V||...
895 crypto_generichash_blake2b_state curr_state;
896 curr_state = state;
897 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
898 // (x_1, x_2, ...) = A(I, V, n, k)
899 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
900 arith_uint256 hashTarget = HASHTarget;
901 //fprintf(stderr,"running solver\n");
902 std::function<bool(std::vector<unsigned char>)> validBlock =
903#ifdef ENABLE_WALLET
904 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
905#else
906 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
907#endif
908 (std::vector<unsigned char> soln) {
909 // Write the solution to the hash and compute the result.
910 LogPrint("pow", "- Checking solution against target\n");
911 pblock->nSolution = soln;
912 solutionTargetChecks.increment();
913 if ( UintToArith256(pblock->GetHash()) > HASHTarget )
914 {
915 //if ( ASSETCHAINS_SYMBOL[0] != 0 )
916 // fprintf(stderr," missed target\n");
917 return false;
918 }
919 CValidationState state;
920 if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false))
921 {
922 fprintf(stderr,"Invalid block mined, try again\n");
923 return(false);
924 }
925 if ( ASSETCHAINS_STAKED == 0 )
926 {
927 if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay )
928 {
929 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL)));
930 int32_t nseconds = Mining_start+roundrobin_delay-time(NULL);
931 if ( nseconds > 0 )
932 sleep(nseconds);
933 MilliSleep((rand() % 1700) + 1);
934 }
935 else if ( ASSETCHAINS_SYMBOL[0] != 0 )
936 {
937 sleep(rand() % 30);
938 }
939 }
940 else
941 {
942 if ( NOTARY_PUBKEY33[0] != 0 )
943 {
944 printf("need to wait %d seconds to submit\n",(int32_t)(pblock->nTime - GetAdjustedTime()));
945 while ( GetAdjustedTime() < pblock->nTime )
946 sleep(1);
947 }
948 else
949 {
950 uint256 tmp = pblock->GetHash();
951 int32_t z; for (z=31; z>=0; z--)
952 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
953 fprintf(stderr," mined block!\n");
954 }
955 }
956 KOMODO_CHOSEN_ONE = 1;
957 // Found a solution
958 SetThreadPriority(THREAD_PRIORITY_NORMAL);
959 LogPrintf("KomodoMiner:\n");
960 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), HASHTarget.GetHex());
961#ifdef ENABLE_WALLET
962 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
963#else
964 if (ProcessBlockFound(pblock)) {
965#endif
966 // Ignore chain updates caused by us
967 std::lock_guard<std::mutex> lock{m_cs};
968 cancelSolver = false;
969 }
970 KOMODO_CHOSEN_ONE = 0;
971 SetThreadPriority(THREAD_PRIORITY_LOWEST);
972 // In regression test mode, stop mining after a block is found.
973 if (chainparams.MineBlocksOnDemand()) {
974 // Increment here because throwing skips the call below
975 ehSolverRuns.increment();
976 throw boost::thread_interrupted();
977 }
978 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
979 // sleep(1800);
980 return true;
981 };
982 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
983 std::lock_guard<std::mutex> lock{m_cs};
984 return cancelSolver;
985 };
986
987 // TODO: factor this out into a function with the same API for each solver.
988 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
989 // Create solver and initialize it.
990 equi eq(1);
991 eq.setstate(&curr_state);
992
993 // Initialization done, start algo driver.
994 eq.digit0(0);
995 eq.xfull = eq.bfull = eq.hfull = 0;
996 eq.showbsizes(0);
997 for (u32 r = 1; r < WK; r++) {
998 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
999 eq.xfull = eq.bfull = eq.hfull = 0;
1000 eq.showbsizes(r);
1001 }
1002 eq.digitK(0);
1003 ehSolverRuns.increment();
1004
1005 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1006 for (size_t s = 0; s < eq.nsols; s++) {
1007 LogPrint("pow", "Checking solution %d\n", s+1);
1008 std::vector<eh_index> index_vector(PROOFSIZE);
1009 for (size_t i = 0; i < PROOFSIZE; i++) {
1010 index_vector[i] = eq.sols[s][i];
1011 }
1012 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1013
1014 if (validBlock(sol_char)) {
1015 // If we find a POW solution, do not try other solutions
1016 // because they become invalid as we created a new block in blockchain.
1017 break;
1018 }
1019 }
1020 } else {
1021 try {
1022 // If we find a valid block, we rebuild
1023 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1024 ehSolverRuns.increment();
1025 if (found) {
1026 int32_t i; uint256 hash = pblock->GetHash();
1027 for (i=0; i<32; i++)
1028 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1029 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1030 FOUND_BLOCK = 1;
1031 KOMODO_MAYBEMINED = Mining_height;
1032 break;
1033 }
1034 } catch (EhSolverCancelledException&) {
1035 LogPrint("pow", "Equihash solver cancelled\n");
1036 std::lock_guard<std::mutex> lock{m_cs};
1037 cancelSolver = false;
1038 }
1039 }
1040
1041 // Check for stop or if block needs to be rebuilt
1042 boost::this_thread::interruption_point();
1043 // Regtest mode doesn't require peers
1044 if ( FOUND_BLOCK != 0 )
1045 {
1046 FOUND_BLOCK = 0;
1047 fprintf(stderr,"FOUND_BLOCK!\n");
1048 //sleep(2000);
1049 }
1050 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1051 {
1052 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1053 {
1054 fprintf(stderr,"no nodes, break\n");
1055 break;
1056 }
1057 }
1058 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1059 {
1060 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1061 fprintf(stderr,"0xffff, break\n");
1062 break;
1063 }
1064 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1065 {
1066 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1067 fprintf(stderr,"timeout, break\n");
1068 break;
1069 }
1070 if ( pindexPrev != chainActive.Tip() )
1071 {
1072 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1073 fprintf(stderr,"Tip advanced, break\n");
1074 break;
1075 }
1076 // Update nNonce and nTime
1077 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1078 pblock->nBits = savebits;
1079 if ( ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
1080 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1081 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1082 {
1083 // Changing pblock->nTime can change work required on testnet:
1084 HASHTarget.SetCompact(pblock->nBits);
1085 }
1086 }
1087 }
1088 }
1089 catch (const boost::thread_interrupted&)
1090 {
1091 miningTimer.stop();
1092 c.disconnect();
1093 LogPrintf("KomodoMiner terminated\n");
1094 throw;
1095 }
1096 catch (const std::runtime_error &e)
1097 {
1098 miningTimer.stop();
1099 c.disconnect();
1100 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1101 return;
1102 }
1103 miningTimer.stop();
1104 c.disconnect();
1105}
1106
1107#ifdef ENABLE_WALLET
1108void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1109#else
1110void GenerateBitcoins(bool fGenerate, int nThreads)
1111#endif
1112{
1113 static boost::thread_group* minerThreads = NULL;
1114
1115 if (nThreads < 0)
1116 nThreads = GetNumCores();
1117
1118 if (minerThreads != NULL)
1119 {
1120 minerThreads->interrupt_all();
1121 delete minerThreads;
1122 minerThreads = NULL;
1123 }
1124
1125 if (nThreads == 0 || !fGenerate)
1126 return;
1127
1128 minerThreads = new boost::thread_group();
1129 for (int i = 0; i < nThreads; i++) {
1130#ifdef ENABLE_WALLET
1131 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1132#else
1133 minerThreads->create_thread(&BitcoinMiner);
1134#endif
1135 }
1136}
1137
1138#endif // ENABLE_MINING
This page took 0.036033 seconds and 4 git commands to generate.