]> Git Repo - VerusCoin.git/blob - src/miner.cpp
test
[VerusCoin.git] / src / miner.cpp
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 #include "pow/tromp/equi_miner.h"
8
9 #include "amount.h"
10 #include "chainparams.h"
11 #include "consensus/consensus.h"
12 #include "consensus/validation.h"
13 #include "hash.h"
14 #include "main.h"
15 #include "metrics.h"
16 #include "net.h"
17 #include "pow.h"
18 #include "primitives/transaction.h"
19 #include "random.h"
20 #include "timedata.h"
21 #include "util.h"
22 #include "utilmoneystr.h"
23 #ifdef ENABLE_WALLET
24 #include "crypto/equihash.h"
25 #include "wallet/wallet.h"
26 #include <functional>
27 #endif
28
29 #include "sodium.h"
30
31 #include <boost/thread.hpp>
32 #include <boost/tuple/tuple.hpp>
33 #include <mutex>
34
35 using namespace std;
36
37 //////////////////////////////////////////////////////////////////////////////
38 //
39 // BitcoinMiner
40 //
41
42 //
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.
49 //
50 class COrphan
51 {
52 public:
53     const CTransaction* ptx;
54     set<uint256> setDependsOn;
55     CFeeRate feeRate;
56     double dPriority;
57
58     COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
59     {
60     }
61 };
62
63 uint64_t nLastBlockTx = 0;
64 uint64_t nLastBlockSize = 0;
65
66 // We want to sort transactions by priority and fee rate, so:
67 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
68 class TxPriorityCompare
69 {
70     bool byFee;
71
72 public:
73     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
74
75     bool operator()(const TxPriority& a, const TxPriority& b)
76     {
77         if (byFee)
78         {
79             if (a.get<1>() == b.get<1>())
80                 return a.get<0>() < b.get<0>();
81             return a.get<1>() < b.get<1>();
82         }
83         else
84         {
85             if (a.get<0>() == b.get<0>())
86                 return a.get<1>() < b.get<1>();
87             return a.get<0>() < b.get<0>();
88         }
89     }
90 };
91
92 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
93 {
94     pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
95
96     // Updating time can change work required on testnet:
97     if (consensusParams.fPowAllowMinDifficultyBlocks)
98         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
99 }
100
101 #define ASSETCHAINS_MINHEIGHT 100
102 #define KOMODO_ELECTION_GAP 2000
103 #define ROUNDROBIN_DELAY 57
104 extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE;
105 extern char ASSETCHAINS_SYMBOL[16];
106 extern std::string NOTARY_PUBKEY;
107 extern uint8_t NOTARY_PUBKEY33[33];
108 uint32_t Mining_start,Mining_height;
109 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33);
110 int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]);
111 int32_t komodo_pax_opreturn(uint8_t *opret,int32_t maxsize);
112 uint64_t komodo_paxtotal();
113 int32_t komodo_baseid(char *origbase);
114 int32_t komodo_is_issuer();
115 int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
116 int32_t komodo_isrealtime(int32_t *kmdheightp);
117
118 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
119 {
120     uint64_t deposits; int32_t isrealtime,kmdheight; const CChainParams& chainparams = Params();
121     // Create new block
122     unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
123     if(!pblocktemplate.get())
124         return NULL;
125     CBlock *pblock = &pblocktemplate->block; // pointer for convenience
126     if ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
127     {
128         isrealtime = komodo_isrealtime(&kmdheight);
129         deposits = komodo_paxtotal();
130         while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
131         {
132             deposits = komodo_paxtotal();
133             if ( KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
134             {
135                 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
136             }
137             else if ( deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0 )
138             {
139                 fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND);
140                 break;
141             }
142             sleep(10);
143         }
144         KOMODO_ON_DEMAND = 0;
145         if ( 0 && deposits != 0 )
146             printf("miner KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)komodo_paxtotal(),(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
147     }
148     // -regtest only: allow overriding block.nVersion with
149     // -blockversion=N to test forking scenarios
150     if (Params().MineBlocksOnDemand())
151         pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
152
153     // Add dummy coinbase tx as first transaction
154     pblock->vtx.push_back(CTransaction());
155     pblocktemplate->vTxFees.push_back(-1); // updated at end
156     pblocktemplate->vTxSigOps.push_back(-1); // updated at end
157
158     // Largest block you're willing to create:
159     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
160     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
161     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
162
163     // How much of the block should be dedicated to high-priority transactions,
164     // included regardless of the fees they pay
165     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
166     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
167
168     // Minimum block size you want to create; block will be filled with free transactions
169     // until there are no more or the block reaches this size:
170     unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
171     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
172
173     // Collect memory pool transactions into the block
174     CAmount nFees = 0;
175
176     {
177         LOCK2(cs_main, mempool.cs);
178         CBlockIndex* pindexPrev = chainActive.Tip();
179         const int nHeight = pindexPrev->nHeight + 1;
180         pblock->nTime = GetAdjustedTime();
181         const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
182         CCoinsViewCache view(pcoinsTip);
183
184         // Priority order to process transactions
185         list<COrphan> vOrphan; // list memory doesn't move
186         map<uint256, vector<COrphan*> > mapDependers;
187         bool fPrintPriority = GetBoolArg("-printpriority", false);
188
189         // This vector will be sorted into a priority queue:
190         vector<TxPriority> vecPriority;
191         vecPriority.reserve(mempool.mapTx.size());
192         for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
193              mi != mempool.mapTx.end(); ++mi)
194         {
195             const CTransaction& tx = mi->second.GetTx();
196
197             int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
198                                     ? nMedianTimePast
199                                     : pblock->GetBlockTime();
200
201             if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
202                 continue;
203
204             COrphan* porphan = NULL;
205             double dPriority = 0;
206             CAmount nTotalIn = 0;
207             bool fMissingInputs = false;
208             BOOST_FOREACH(const CTxIn& txin, tx.vin)
209             {
210                 // Read prev transaction
211                 if (!view.HaveCoins(txin.prevout.hash))
212                 {
213                     // This should never happen; all transactions in the memory
214                     // pool should connect to either transactions in the chain
215                     // or other transactions in the memory pool.
216                     if (!mempool.mapTx.count(txin.prevout.hash))
217                     {
218                         LogPrintf("ERROR: mempool transaction missing input\n");
219                         if (fDebug) assert("mempool transaction missing input" == 0);
220                         fMissingInputs = true;
221                         if (porphan)
222                             vOrphan.pop_back();
223                         break;
224                     }
225
226                     // Has to wait for dependencies
227                     if (!porphan)
228                     {
229                         // Use list for automatic deletion
230                         vOrphan.push_back(COrphan(&tx));
231                         porphan = &vOrphan.back();
232                     }
233                     mapDependers[txin.prevout.hash].push_back(porphan);
234                     porphan->setDependsOn.insert(txin.prevout.hash);
235                     nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
236                     continue;
237                 }
238                 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
239                 assert(coins);
240
241                 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
242                 nTotalIn += nValueIn;
243
244                 int nConf = nHeight - coins->nHeight;
245
246                 dPriority += (double)nValueIn * nConf;
247             }
248             nTotalIn += tx.GetJoinSplitValueIn();
249
250             if (fMissingInputs) continue;
251
252             // Priority is sum(valuein * age) / modified_txsize
253             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
254             dPriority = tx.ComputePriority(dPriority, nTxSize);
255
256             uint256 hash = tx.GetHash();
257             mempool.ApplyDeltas(hash, dPriority, nTotalIn);
258
259             CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
260
261             if (porphan)
262             {
263                 porphan->dPriority = dPriority;
264                 porphan->feeRate = feeRate;
265             }
266             else
267                 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
268         }
269
270         // Collect transactions into block
271         uint64_t nBlockSize = 1000;
272         uint64_t nBlockTx = 0;
273         int64_t interest;
274         int nBlockSigOps = 100;
275         bool fSortedByFee = (nBlockPrioritySize <= 0);
276
277         TxPriorityCompare comparer(fSortedByFee);
278         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
279
280         while (!vecPriority.empty())
281         {
282             // Take highest priority transaction off the priority queue:
283             double dPriority = vecPriority.front().get<0>();
284             CFeeRate feeRate = vecPriority.front().get<1>();
285             const CTransaction& tx = *(vecPriority.front().get<2>());
286
287             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
288             vecPriority.pop_back();
289
290             // Size limits
291             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
292             if (nBlockSize + nTxSize >= nBlockMaxSize)
293                 continue;
294
295             // Legacy limits on sigOps:
296             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
297             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
298                 continue;
299
300             // Skip free transactions if we're past the minimum block size:
301             const uint256& hash = tx.GetHash();
302             double dPriorityDelta = 0;
303             CAmount nFeeDelta = 0;
304             mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
305             if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
306                 continue;
307
308             // Prioritise by fee once past the priority size or we run out of high-priority
309             // transactions:
310             if (!fSortedByFee &&
311                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
312             {
313                 fSortedByFee = true;
314                 comparer = TxPriorityCompare(fSortedByFee);
315                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
316             }
317
318             if (!view.HaveInputs(tx))
319                 continue;
320
321             CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
322
323             nTxSigOps += GetP2SHSigOpCount(tx, view);
324             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
325                 continue;
326
327             // Note that flags: we don't want to set mempool/IsStandard()
328             // policy here, but we still have to ensure that the block we
329             // create only contains transactions that are valid in new blocks.
330             CValidationState state;
331             if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
332                 continue;
333
334             UpdateCoins(tx, state, view, nHeight);
335
336             // Added
337             pblock->vtx.push_back(tx);
338             pblocktemplate->vTxFees.push_back(nTxFees);
339             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
340             nBlockSize += nTxSize;
341             ++nBlockTx;
342             nBlockSigOps += nTxSigOps;
343             nFees += nTxFees;
344
345             if (fPrintPriority)
346             {
347                 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
348             }
349
350             // Add transactions that depend on this one to the priority queue
351             if (mapDependers.count(hash))
352             {
353                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
354                 {
355                     if (!porphan->setDependsOn.empty())
356                     {
357                         porphan->setDependsOn.erase(hash);
358                         if (porphan->setDependsOn.empty())
359                         {
360                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
361                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
362                         }
363                     }
364                 }
365             }
366         }
367
368         nLastBlockTx = nBlockTx;
369         nLastBlockSize = nBlockSize;
370         LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
371
372         // Create coinbase tx
373         CMutableTransaction txNew;
374         //txNew.nLockTime = (uint32_t)time(NULL) - 60;
375         txNew.vin.resize(1);
376         txNew.vin[0].prevout.SetNull();
377         txNew.vout.resize(1);
378         txNew.vout[0].scriptPubKey = scriptPubKeyIn;
379         txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
380         // Add fees
381         txNew.vout[0].nValue += nFees;
382         txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
383         if ( ASSETCHAINS_SYMBOL[0] == 0 )
384         {
385             int32_t i,opretlen; uint8_t opret[256],*ptr;
386             if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
387             {
388                 if ( (opretlen= komodo_pax_opreturn(opret,sizeof(opret))) > 0 ) // have pricefeed
389                 {
390                     txNew.vout.resize(2);
391                     txNew.vout[1].scriptPubKey.resize(opretlen);
392                     ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
393                     for (i=0; i<opretlen; i++)
394                         ptr[i] = opret[i];
395                     txNew.vout[1].nValue = 0;
396                     //fprintf(stderr,"opretlen.%d\n",opretlen);
397                 }
398             }
399         }
400         else if ( komodo_is_issuer() != 0 )
401         {
402             komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
403             if ( txNew.vout.size() > 1 )
404                 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
405         }
406         pblock->vtx[0] = txNew;
407         pblocktemplate->vTxFees[0] = -nFees;
408         // Randomise nonce
409         arith_uint256 nonce = UintToArith256(GetRandHash());
410         // Clear the top and bottom 16 bits (for local use as thread flags and counters)
411         nonce <<= 32;
412         nonce >>= 16;
413         pblock->nNonce = ArithToUint256(nonce);
414
415         // Fill in header
416         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
417         pblock->hashReserved   = uint256();
418         UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
419         pblock->nBits         = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
420         pblock->nSolution.clear();
421         pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
422
423         CValidationState state;
424         if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
425         {
426             fprintf(stderr,"testblockvalidity failed\n");
427             //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
428         }
429     }
430
431     return pblocktemplate.release();
432 }
433
434 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
435 {
436     // Update nExtraNonce
437     static uint256 hashPrevBlock;
438     if (hashPrevBlock != pblock->hashPrevBlock)
439     {
440         nExtraNonce = 0;
441         hashPrevBlock = pblock->hashPrevBlock;
442     }
443     ++nExtraNonce;
444     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
445     CMutableTransaction txCoinbase(pblock->vtx[0]);
446     txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
447     assert(txCoinbase.vin[0].scriptSig.size() <= 100);
448
449     pblock->vtx[0] = txCoinbase;
450     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
451 }
452
453 #ifdef ENABLE_WALLET
454 //////////////////////////////////////////////////////////////////////////////
455 //
456 // Internal miner
457 //
458 int8_t komodo_minerid(int32_t height);
459
460 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
461 {
462     CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
463     if ( USE_EXTERNAL_PUBKEY != 0 )
464     {
465         //fprintf(stderr,"use notary pubkey\n");
466         scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
467     }
468     else
469     {
470         if (!reservekey.GetReservedKey(pubkey))
471             return NULL;
472         scriptPubKey.resize(35);
473         ptr = (uint8_t *)pubkey.begin();
474         script = (uint8_t *)scriptPubKey.data();
475         script[0] = 33;
476         for (i=0; i<33; i++)
477             script[i+1] = ptr[i];
478         script[34] = OP_CHECKSIG;
479         //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
480     }
481     if ( 0 && ASSETCHAINS_SYMBOL[0] == 0 )
482     {
483         for (i=0; i<65; i++)
484             fprintf(stderr,"%d ",komodo_minerid(chainActive.Tip()->nHeight-i));
485         fprintf(stderr," minerids.special %d from ht.%d\n",komodo_is_special(chainActive.Tip()->nHeight+1,NOTARY_PUBKEY33),chainActive.Tip()->nHeight);
486     }
487     return CreateNewBlock(scriptPubKey);
488 }
489
490 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
491 {
492     LogPrintf("%s\n", pblock->ToString());
493     LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
494
495     // Found a solution
496     {
497         LOCK(cs_main);
498         if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
499             return error("KomodoMiner: generated block is stale");
500     }
501
502     // Remove key from key pool
503     if ( IS_KOMODO_NOTARY == 0 )
504         reservekey.KeepKey();
505
506     // Track how many getdata requests this block gets
507     {
508         LOCK(wallet.cs_wallet);
509         wallet.mapRequestCount[pblock->GetHash()] = 0;
510     }
511
512     // Process this block the same as if we had received it from another node
513     CValidationState state;
514     if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
515         return error("KomodoMiner: ProcessNewBlock, block not accepted");
516
517     TrackMinedBlock(pblock->GetHash());
518
519     return true;
520 }
521
522 int32_t komodo_baseid(char *origbase);
523
524 void static BitcoinMiner(CWallet *pwallet)
525 {
526     LogPrintf("KomodoMiner started\n");
527     SetThreadPriority(THREAD_PRIORITY_LOWEST);
528     RenameThread("komodo-miner");
529     const CChainParams& chainparams = Params();
530
531     // Each thread has its own key and counter
532     CReserveKey reservekey(pwallet);
533     unsigned int nExtraNonce = 0;
534
535     unsigned int n = chainparams.EquihashN();
536     unsigned int k = chainparams.EquihashK();
537     int32_t notaryid = -1;
538     while ( ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0 )
539     {
540         sleep(1);
541         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
542             break;
543     }
544     komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33);
545
546     std::string solver;
547     if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
548         solver = "tromp";
549     else solver = "default";
550     assert(solver == "tromp" || solver == "default");
551     LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
552     //fprintf(stderr,"Mining with %s\n",solver.c_str());
553     std::mutex m_cs;
554     bool cancelSolver = false;
555     boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
556         [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
557             std::lock_guard<std::mutex> lock{m_cs};
558             cancelSolver = true;
559         }
560     );
561
562     try {
563         //fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
564         while (true)
565         {
566             if (chainparams.MiningRequiresPeers())
567             {
568                 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
569                 //    break;
570                 // Busy-wait for the network to come online so we don't waste time mining
571                 // on an obsolete chain. In regtest mode we expect to fly solo.
572                 //fprintf(stderr,"Wait for peers...\n");
573                 do {
574                     bool fvNodesEmpty;
575                     {
576                         LOCK(cs_vNodes);
577                         fvNodesEmpty = vNodes.empty();
578                     }
579                     if (!fvNodesEmpty && !IsInitialBlockDownload())
580                         break;
581                     MilliSleep(5000);
582                     //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
583
584                 } while (true);
585                 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
586             }
587             /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
588             {
589                 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
590                 sleep(3);
591             }*/
592             //
593             // Create new block
594             //
595             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
596             CBlockIndex* pindexPrev = chainActive.Tip();
597             if ( Mining_height != pindexPrev->nHeight+1 )
598             {
599                 Mining_height = pindexPrev->nHeight+1;
600                 Mining_start = (uint32_t)time(NULL);
601             }
602             if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
603                 fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
604
605             unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
606             if (!pblocktemplate.get())
607             {
608                 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
609                 return;
610             }
611             CBlock *pblock = &pblocktemplate->block;
612             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
613             LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
614             //
615             // Search
616             //
617             uint32_t savebits; int64_t nStart = GetTime();
618             savebits = pblock->nBits;
619             arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
620             if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
621             {
622                 if ( (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
623                 {
624                     hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
625                     fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
626                 } else Mining_start = 0;
627             } else Mining_start = 0;
628             while (true)
629             {
630                 if ( ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
631                 {
632                     //fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
633                     sleep(10);
634                     break;
635                 }
636                 // Hash state
637                 KOMODO_CHOSEN_ONE = 0;
638                 crypto_generichash_blake2b_state state;
639                 EhInitialiseState(n, k, state);
640                 // I = the block header minus nonce and solution.
641                 CEquihashInput I{*pblock};
642                 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
643                 ss << I;
644                 // H(I||...
645                 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
646                 // H(I||V||...
647                 crypto_generichash_blake2b_state curr_state;
648                 curr_state = state;
649                 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
650                 // (x_1, x_2, ...) = A(I, V, n, k)
651                 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
652                 std::function<bool(std::vector<unsigned char>)> validBlock =
653                         [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
654                         (std::vector<unsigned char> soln)
655                 {
656                     // Write the solution to the hash and compute the result.
657                     LogPrint("pow", "- Checking solution against target\n");
658                     pblock->nSolution = soln;
659                     solutionTargetChecks.increment();
660                     if ( UintToArith256(pblock->GetHash()) > hashTarget )
661                     {
662                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
663                             fprintf(stderr,"missed target\n");
664                         return false;
665                     }
666                     if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+ROUNDROBIN_DELAY )
667                     {
668                         //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+ROUNDROBIN_DELAY-time(NULL)));
669                         int32_t nseconds = Mining_start+ROUNDROBIN_DELAY-time(NULL);
670                         if ( nseconds > 0 )
671                             sleep(nseconds);
672                         MilliSleep((rand() % 700) + 1);
673                     }
674                     KOMODO_CHOSEN_ONE = 1;
675                     // Found a solution
676                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
677                     LogPrintf("KomodoMiner:\n");
678                     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
679                     if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
680                         // Ignore chain updates caused by us
681                         std::lock_guard<std::mutex> lock{m_cs};
682                         cancelSolver = false;
683                     }
684                     KOMODO_CHOSEN_ONE = 0;
685                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
686                     // In regression test mode, stop mining after a block is found.
687                     if (chainparams.MineBlocksOnDemand()) {
688                         // Increment here because throwing skips the call below
689                         ehSolverRuns.increment();
690                         throw boost::thread_interrupted();
691                     }
692                     return true;
693                 };
694                 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
695                     std::lock_guard<std::mutex> lock{m_cs};
696                     return cancelSolver;
697                 };
698
699                 // TODO: factor this out into a function with the same API for each solver.
700                 if (solver == "tromp" && notaryid >= 0 ) {
701                     // Create solver and initialize it.
702                     equi eq(1);
703                     eq.setstate(&curr_state);
704
705                     // Intialization done, start algo driver.
706                     eq.digit0(0);
707                     eq.xfull = eq.bfull = eq.hfull = 0;
708                     eq.showbsizes(0);
709                     for (u32 r = 1; r < WK; r++) {
710                         (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
711                         eq.xfull = eq.bfull = eq.hfull = 0;
712                         eq.showbsizes(r);
713                     }
714                     eq.digitK(0);
715                     ehSolverRuns.increment();
716
717                     // Convert solution indices to byte array (decompress) and pass it to validBlock method.
718                     for (size_t s = 0; s < eq.nsols; s++) {
719                         LogPrint("pow", "Checking solution %d\n", s+1);
720                         std::vector<eh_index> index_vector(PROOFSIZE);
721                         for (size_t i = 0; i < PROOFSIZE; i++) {
722                             index_vector[i] = eq.sols[s][i];
723                         }
724                         std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
725
726                         if (validBlock(sol_char)) {
727                             // If we find a POW solution, do not try other solutions
728                             // because they become invalid as we created a new block in blockchain.
729                             break;
730                         }
731                     }
732                 } else {
733                     try {
734                         // If we find a valid block, we rebuild
735                         bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
736                         ehSolverRuns.increment();
737                         if (found) {
738                             int32_t i; uint256 hash = pblock->GetHash();
739                             for (i=0; i<32; i++)
740                                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
741                             fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
742                             sleep(60); // avoid mining forks
743                             break;
744                         }
745                     } catch (EhSolverCancelledException&) {
746                         LogPrint("pow", "Equihash solver cancelled\n");
747                         std::lock_guard<std::mutex> lock{m_cs};
748                         cancelSolver = false;
749                     }
750                 }
751
752                 // Check for stop or if block needs to be rebuilt
753                 boost::this_thread::interruption_point();
754                 // Regtest mode doesn't require peers
755                 if (vNodes.empty() && chainparams.MiningRequiresPeers())
756                 {
757                     if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
758                     {
759                         //fprintf(stderr,"no nodes, break\n");
760                         break;
761                     }
762                 }
763                 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
764                 {
765                     if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
766                         fprintf(stderr,"0xffff, break\n");
767                     break;
768                 }
769                 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
770                 {
771                     if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
772                         fprintf(stderr,"timeout, break\n");
773                     break;
774                 }
775                 if ( pindexPrev != chainActive.Tip() )
776                 {
777                     if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
778                         fprintf(stderr,"Tip advanced, break\n");
779                     break;
780                 }
781                 // Update nNonce and nTime
782                 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
783                 pblock->nBits = savebits;
784                 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
785                 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
786                 {
787                     // Changing pblock->nTime can change work required on testnet:
788                     hashTarget.SetCompact(pblock->nBits);
789                 }
790             }
791         }
792     }
793     catch (const boost::thread_interrupted&)
794     {
795         c.disconnect();
796         LogPrintf("KomodoMiner terminated\n");
797         throw;
798     }
799     catch (const std::runtime_error &e)
800     {
801         c.disconnect();
802         LogPrintf("KomodoMiner runtime error: %s\n", e.what());
803         return;
804     }
805     c.disconnect();
806 }
807
808 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
809 {
810     static boost::thread_group* minerThreads = NULL;
811
812     if (nThreads < 0) {
813         // In regtest threads defaults to 1
814         if (Params().DefaultMinerThreads())
815             nThreads = Params().DefaultMinerThreads();
816         else
817             nThreads = boost::thread::hardware_concurrency();
818     }
819
820     if (minerThreads != NULL)
821     {
822         minerThreads->interrupt_all();
823         delete minerThreads;
824         minerThreads = NULL;
825     }
826
827     if (nThreads == 0 || !fGenerate)
828         return;
829
830     minerThreads = new boost::thread_group();
831     for (int i = 0; i < nThreads; i++)
832         minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
833 }
834
835 #endif // ENABLE_WALLET
This page took 0.073867 seconds and 4 git commands to generate.