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